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
graphology/graphology-layout-forceatlas2
index.js
inferSettings
function inferSettings(graph) { var order = graph.order; return { barnesHutOptimize: order > 2000, strongGravityMode: true, gravity: 0.05, scalingRatio: 10, slowDown: 1 + Math.log(order) }; }
javascript
function inferSettings(graph) { var order = graph.order; return { barnesHutOptimize: order > 2000, strongGravityMode: true, gravity: 0.05, scalingRatio: 10, slowDown: 1 + Math.log(order) }; }
[ "function", "inferSettings", "(", "graph", ")", "{", "var", "order", "=", "graph", ".", "order", ";", "return", "{", "barnesHutOptimize", ":", "order", ">", "2000", ",", "strongGravityMode", ":", "true", ",", "gravity", ":", "0.05", ",", "scalingRatio", ":", "10", ",", "slowDown", ":", "1", "+", "Math", ".", "log", "(", "order", ")", "}", ";", "}" ]
Function returning sane layout settings for the given graph. @param {Graph} graph - Target graph. @return {object}
[ "Function", "returning", "sane", "layout", "settings", "for", "the", "given", "graph", "." ]
87c8664603ab15f8aa0e7aeb4960b9425a2811e2
https://github.com/graphology/graphology-layout-forceatlas2/blob/87c8664603ab15f8aa0e7aeb4960b9425a2811e2/index.js#L68-L78
train
jaredhanson/kerouac
lib/page.js
Page
function Page(path, ctx) { events.EventEmitter.call(this); this.path = path; this.context = ctx; this._isOpen = false; }
javascript
function Page(path, ctx) { events.EventEmitter.call(this); this.path = path; this.context = ctx; this._isOpen = false; }
[ "function", "Page", "(", "path", ",", "ctx", ")", "{", "events", ".", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "path", "=", "path", ";", "this", ".", "context", "=", "ctx", ";", "this", ".", "_isOpen", "=", "false", ";", "}" ]
Initialize a new `Page`. `Page` represents a page in a site. In the process of generating a page, it will pass through a chain of middleware functions. It is expected that one of these middleware will write a page, either directly by calling `write()` and `end()`, or indirectly by `render()`ing a layout. @param {String} path @api private
[ "Initialize", "a", "new", "Page", "." ]
ab479484f56c1a530467e726f1271d08593b29c8
https://github.com/jaredhanson/kerouac/blob/ab479484f56c1a530467e726f1271d08593b29c8/lib/page.js#L22-L27
train
jaredhanson/kerouac
lib/application.js
dispatch
function dispatch(req, done) { var site = req.site , path = upath.join(site.path || '', req.path) , parent = site.parent; while (parent) { path = upath.join(parent.path || '', path); parent = parent.parent; } console.log('# ' + path); var page = new Page(path, req.context); pages.push(page); page.once('close', done); //page.site = self; //page.pages = pages; self.handle(page); }
javascript
function dispatch(req, done) { var site = req.site , path = upath.join(site.path || '', req.path) , parent = site.parent; while (parent) { path = upath.join(parent.path || '', path); parent = parent.parent; } console.log('# ' + path); var page = new Page(path, req.context); pages.push(page); page.once('close', done); //page.site = self; //page.pages = pages; self.handle(page); }
[ "function", "dispatch", "(", "req", ",", "done", ")", "{", "var", "site", "=", "req", ".", "site", ",", "path", "=", "upath", ".", "join", "(", "site", ".", "path", "||", "''", ",", "req", ".", "path", ")", ",", "parent", "=", "site", ".", "parent", ";", "while", "(", "parent", ")", "{", "path", "=", "upath", ".", "join", "(", "parent", ".", "path", "||", "''", ",", "path", ")", ";", "parent", "=", "parent", ".", "parent", ";", "}", "console", ".", "log", "(", "'# '", "+", "path", ")", ";", "var", "page", "=", "new", "Page", "(", "path", ",", "req", ".", "context", ")", ";", "pages", ".", "push", "(", "page", ")", ";", "page", ".", "once", "(", "'close'", ",", "done", ")", ";", "self", ".", "handle", "(", "page", ")", ";", "}" ]
Binding is complete, producing a complete list of all pages that need to be generated. Dispatch those pages into the application, so that the content can be written to files which constitute the static site.
[ "Binding", "is", "complete", "producing", "a", "complete", "list", "of", "all", "pages", "that", "need", "to", "be", "generated", ".", "Dispatch", "those", "pages", "into", "the", "application", "so", "that", "the", "content", "can", "be", "written", "to", "files", "which", "constitute", "the", "static", "site", "." ]
ab479484f56c1a530467e726f1271d08593b29c8
https://github.com/jaredhanson/kerouac/blob/ab479484f56c1a530467e726f1271d08593b29c8/lib/application.js#L650-L668
train
SchizoDuckie/CreateReadUpdateDelete.js
cli/existingentitymodifier.js
rewrite_code
function rewrite_code(code, node, replacement_string) { return code.substr(0, node.start.pos) + replacement_string + code.substr(node.end.endpos); }
javascript
function rewrite_code(code, node, replacement_string) { return code.substr(0, node.start.pos) + replacement_string + code.substr(node.end.endpos); }
[ "function", "rewrite_code", "(", "code", ",", "node", ",", "replacement_string", ")", "{", "return", "code", ".", "substr", "(", "0", ",", "node", ".", "start", ".", "pos", ")", "+", "replacement_string", "+", "code", ".", "substr", "(", "node", ".", "end", ".", "endpos", ")", ";", "}" ]
Modify code string with a new value based on start and end position of an UglifyJS.AST_Node @param {string} code code to modify @param {UglifyJS.AST_Node} node node to replace the content for @param {string} replacement_string replacement js encoded value for the property @return {string} modified code
[ "Modify", "code", "string", "with", "a", "new", "value", "based", "on", "start", "and", "end", "position", "of", "an", "UglifyJS", ".", "AST_Node" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/cli/existingentitymodifier.js#L40-L42
train
ceee/grunt-datauri
tasks/datauri.js
generateData
function generateData( filepath ) { var dataObj = new datauri( filepath ); return { data: dataObj.content, path: filepath }; }
javascript
function generateData( filepath ) { var dataObj = new datauri( filepath ); return { data: dataObj.content, path: filepath }; }
[ "function", "generateData", "(", "filepath", ")", "{", "var", "dataObj", "=", "new", "datauri", "(", "filepath", ")", ";", "return", "{", "data", ":", "dataObj", ".", "content", ",", "path", ":", "filepath", "}", ";", "}" ]
generates a datauri object from file ~~~~~~~~~~~~~~~~~~~~~
[ "generates", "a", "datauri", "object", "from", "file", "~~~~~~~~~~~~~~~~~~~~~" ]
462a0ab9a72886f2a54ec8ba5dcc41a747777cca
https://github.com/ceee/grunt-datauri/blob/462a0ab9a72886f2a54ec8ba5dcc41a747777cca/tasks/datauri.js#L72-L80
train
ceee/grunt-datauri
tasks/datauri.js
generateCss
function generateCss( filepath, data ) { var filetype = filepath.split( '.' ).pop().toLowerCase(); var className; var template; className = options.classPrefix + path.basename( data.path ).split( '.' )[0] + options.classSuffix; filetype = options.usePlaceholder ? filetype : filetype + '_no'; if (options.variables) { template = cssTemplates.variables; } else { template = cssTemplates[ filetype ] || cssTemplates.default; } return template.replace( '{{class}}', className ).replace( '{{data}}', data.data ); }
javascript
function generateCss( filepath, data ) { var filetype = filepath.split( '.' ).pop().toLowerCase(); var className; var template; className = options.classPrefix + path.basename( data.path ).split( '.' )[0] + options.classSuffix; filetype = options.usePlaceholder ? filetype : filetype + '_no'; if (options.variables) { template = cssTemplates.variables; } else { template = cssTemplates[ filetype ] || cssTemplates.default; } return template.replace( '{{class}}', className ).replace( '{{data}}', data.data ); }
[ "function", "generateCss", "(", "filepath", ",", "data", ")", "{", "var", "filetype", "=", "filepath", ".", "split", "(", "'.'", ")", ".", "pop", "(", ")", ".", "toLowerCase", "(", ")", ";", "var", "className", ";", "var", "template", ";", "className", "=", "options", ".", "classPrefix", "+", "path", ".", "basename", "(", "data", ".", "path", ")", ".", "split", "(", "'.'", ")", "[", "0", "]", "+", "options", ".", "classSuffix", ";", "filetype", "=", "options", ".", "usePlaceholder", "?", "filetype", ":", "filetype", "+", "'_no'", ";", "if", "(", "options", ".", "variables", ")", "{", "template", "=", "cssTemplates", ".", "variables", ";", "}", "else", "{", "template", "=", "cssTemplates", "[", "filetype", "]", "||", "cssTemplates", ".", "default", ";", "}", "return", "template", ".", "replace", "(", "'{{class}}'", ",", "className", ")", ".", "replace", "(", "'{{data}}'", ",", "data", ".", "data", ")", ";", "}" ]
wraps daturi in css class ~~~~~~~~~~~~~~~~~~~~~
[ "wraps", "daturi", "in", "css", "class", "~~~~~~~~~~~~~~~~~~~~~" ]
462a0ab9a72886f2a54ec8ba5dcc41a747777cca
https://github.com/ceee/grunt-datauri/blob/462a0ab9a72886f2a54ec8ba5dcc41a747777cca/tasks/datauri.js#L85-L104
train
nathanpdaniel/uber-api
lib/index.js
getHistory
function getHistory(callback) { if (_.isUndefined(callback)) { } else { var u = config.baseUrl + ((api_version == "v1") ? "v1.1" : api_version) + "/history", tokenData = this.getAuthToken(); if (tokenData.type != "bearer") { throw new Error("Invalid token type. Must use a token of type bearer."); } return helper.get(tokenData, u, callback); } }
javascript
function getHistory(callback) { if (_.isUndefined(callback)) { } else { var u = config.baseUrl + ((api_version == "v1") ? "v1.1" : api_version) + "/history", tokenData = this.getAuthToken(); if (tokenData.type != "bearer") { throw new Error("Invalid token type. Must use a token of type bearer."); } return helper.get(tokenData, u, callback); } }
[ "function", "getHistory", "(", "callback", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "callback", ")", ")", "{", "}", "else", "{", "var", "u", "=", "config", ".", "baseUrl", "+", "(", "(", "api_version", "==", "\"v1\"", ")", "?", "\"v1.1\"", ":", "api_version", ")", "+", "\"/history\"", ",", "tokenData", "=", "this", ".", "getAuthToken", "(", ")", ";", "if", "(", "tokenData", ".", "type", "!=", "\"bearer\"", ")", "{", "throw", "new", "Error", "(", "\"Invalid token type. Must use a token of type bearer.\"", ")", ";", "}", "return", "helper", ".", "get", "(", "tokenData", ",", "u", ",", "callback", ")", ";", "}", "}" ]
getHistory Get the currently logged in user history @param Function A callback function which takes two paramenters
[ "getHistory", "Get", "the", "currently", "logged", "in", "user", "history" ]
75682acf50fa84ad2d0e0bc144ec3d4b779da8b4
https://github.com/nathanpdaniel/uber-api/blob/75682acf50fa84ad2d0e0bc144ec3d4b779da8b4/lib/index.js#L150-L160
train
nathanpdaniel/uber-api
lib/index.js
getUserProfile
function getUserProfile(callback) { if (_.isUndefined(callback)) { } else { var u = baseUrl + "/me"; var tokenData = this.getAuthToken(); if (tokenData.type != "bearer") { throw new Error("Invalid token type. Must use a token of type bearer."); } return helper.get(tokenData, u, callback); } }
javascript
function getUserProfile(callback) { if (_.isUndefined(callback)) { } else { var u = baseUrl + "/me"; var tokenData = this.getAuthToken(); if (tokenData.type != "bearer") { throw new Error("Invalid token type. Must use a token of type bearer."); } return helper.get(tokenData, u, callback); } }
[ "function", "getUserProfile", "(", "callback", ")", "{", "if", "(", "_", ".", "isUndefined", "(", "callback", ")", ")", "{", "}", "else", "{", "var", "u", "=", "baseUrl", "+", "\"/me\"", ";", "var", "tokenData", "=", "this", ".", "getAuthToken", "(", ")", ";", "if", "(", "tokenData", ".", "type", "!=", "\"bearer\"", ")", "{", "throw", "new", "Error", "(", "\"Invalid token type. Must use a token of type bearer.\"", ")", ";", "}", "return", "helper", ".", "get", "(", "tokenData", ",", "u", ",", "callback", ")", ";", "}", "}" ]
getMe Get the currently logged in user profile. @param Function A callback function which takes two parameters
[ "getMe", "Get", "the", "currently", "logged", "in", "user", "profile", "." ]
75682acf50fa84ad2d0e0bc144ec3d4b779da8b4
https://github.com/nathanpdaniel/uber-api/blob/75682acf50fa84ad2d0e0bc144ec3d4b779da8b4/lib/index.js#L167-L177
train
SchizoDuckie/CreateReadUpdateDelete.js
cli/entityfinder.js
function() { return new Promise(function(resolve, reject) { exec("find . ! -name '" + __filename.split('/').pop() + "' -iname '*\.js' | xargs grep 'CRUD.Entity.call(this);' -isl", { timeout: 3000, cwd: process.cwd() }, function(err, stdout, stdin) { var results = stdout.trim().split('\n'); for (var i = 0; i < results.length; i++) { eval(fs.readFileSync(results[i]) + ''); } resolve(Object.keys(CRUD.entities)); }); }); }
javascript
function() { return new Promise(function(resolve, reject) { exec("find . ! -name '" + __filename.split('/').pop() + "' -iname '*\.js' | xargs grep 'CRUD.Entity.call(this);' -isl", { timeout: 3000, cwd: process.cwd() }, function(err, stdout, stdin) { var results = stdout.trim().split('\n'); for (var i = 0; i < results.length; i++) { eval(fs.readFileSync(results[i]) + ''); } resolve(Object.keys(CRUD.entities)); }); }); }
[ "function", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "exec", "(", "\"find . ! -name '\"", "+", "__filename", ".", "split", "(", "'/'", ")", ".", "pop", "(", ")", "+", "\"' -iname '*\\.js' | xargs grep 'CRUD.Entity.call(this);' -isl\"", ",", "\\.", ",", "{", "timeout", ":", "3000", ",", "cwd", ":", "process", ".", "cwd", "(", ")", "}", ")", ";", "}", ")", ";", "}" ]
Find and register all CRUD entities under the base dir. evaluates the files @return {Promise} array of defined CRUD entities
[ "Find", "and", "register", "all", "CRUD", "entities", "under", "the", "base", "dir", ".", "evaluates", "the", "files" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/cli/entityfinder.js#L13-L26
train
SchizoDuckie/CreateReadUpdateDelete.js
cli/entityfinder.js
function() { return new Promise(function(resolve, reject) { exec("find . ! -name '" + __filename.split('/').pop() + "' -iname '*\.js' | xargs grep 'CRUD.Entity.call(this);' -isl", { timeout: 3000, cwd: process.cwd() }, function(err, stdout, stdin) { var results = stdout.trim().split('\n'); var entities = {}; // iterate all found js files and search for CRUD.define calls results.map(function(filename) { if (filename.trim() == '') return; var code = fs.readFileSync(filename) + ''; var ast = UglifyJS.parse(code); ast.walk(new UglifyJS.TreeWalker(function(node) { if (node instanceof UglifyJS.AST_Call && node.start.value == 'CRUD' && node.expression.property == 'define') { entities[node.args[0].start.value] = filename; } })); }); resolve(entities); }); }); }
javascript
function() { return new Promise(function(resolve, reject) { exec("find . ! -name '" + __filename.split('/').pop() + "' -iname '*\.js' | xargs grep 'CRUD.Entity.call(this);' -isl", { timeout: 3000, cwd: process.cwd() }, function(err, stdout, stdin) { var results = stdout.trim().split('\n'); var entities = {}; // iterate all found js files and search for CRUD.define calls results.map(function(filename) { if (filename.trim() == '') return; var code = fs.readFileSync(filename) + ''; var ast = UglifyJS.parse(code); ast.walk(new UglifyJS.TreeWalker(function(node) { if (node instanceof UglifyJS.AST_Call && node.start.value == 'CRUD' && node.expression.property == 'define') { entities[node.args[0].start.value] = filename; } })); }); resolve(entities); }); }); }
[ "function", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "exec", "(", "\"find . ! -name '\"", "+", "__filename", ".", "split", "(", "'/'", ")", ".", "pop", "(", ")", "+", "\"' -iname '*\\.js' | xargs grep 'CRUD.Entity.call(this);' -isl\"", ",", "\\.", ",", "{", "timeout", ":", "3000", ",", "cwd", ":", "process", ".", "cwd", "(", ")", "}", ")", ";", "}", ")", ";", "}" ]
Find the filenames for all CRUD entities under the base dir @return {Promise} object with keys: entity names, values: filename
[ "Find", "the", "filenames", "for", "all", "CRUD", "entities", "under", "the", "base", "dir" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/cli/entityfinder.js#L31-L55
train
sapegin/react-group
index.js
Group
function Group(props) { var children = React.Children.toArray(props.children).filter(Boolean); if (children.length === 1) { return children; } // Insert separators var separator = props.separator; var separatorIsElement = React.isValidElement(separator); var items = [children.shift()]; children.forEach(function(item, index) { if (separatorIsElement) { var key = 'separator-' + (item.key || index); separator = React.cloneElement(separator, { key: key }); } items.push(separator, item); }); return items; }
javascript
function Group(props) { var children = React.Children.toArray(props.children).filter(Boolean); if (children.length === 1) { return children; } // Insert separators var separator = props.separator; var separatorIsElement = React.isValidElement(separator); var items = [children.shift()]; children.forEach(function(item, index) { if (separatorIsElement) { var key = 'separator-' + (item.key || index); separator = React.cloneElement(separator, { key: key }); } items.push(separator, item); }); return items; }
[ "function", "Group", "(", "props", ")", "{", "var", "children", "=", "React", ".", "Children", ".", "toArray", "(", "props", ".", "children", ")", ".", "filter", "(", "Boolean", ")", ";", "if", "(", "children", ".", "length", "===", "1", ")", "{", "return", "children", ";", "}", "var", "separator", "=", "props", ".", "separator", ";", "var", "separatorIsElement", "=", "React", ".", "isValidElement", "(", "separator", ")", ";", "var", "items", "=", "[", "children", ".", "shift", "(", ")", "]", ";", "children", ".", "forEach", "(", "function", "(", "item", ",", "index", ")", "{", "if", "(", "separatorIsElement", ")", "{", "var", "key", "=", "'separator-'", "+", "(", "item", ".", "key", "||", "index", ")", ";", "separator", "=", "React", ".", "cloneElement", "(", "separator", ",", "{", "key", ":", "key", "}", ")", ";", "}", "items", ".", "push", "(", "separator", ",", "item", ")", ";", "}", ")", ";", "return", "items", ";", "}" ]
React component to render collection of items separated by space or other separator. @visibleName React Group
[ "React", "component", "to", "render", "collection", "of", "items", "separated", "by", "space", "or", "other", "separator", "." ]
13dbc3a37be17a1bcccb86277f04685fdbb7aeeb
https://github.com/sapegin/react-group/blob/13dbc3a37be17a1bcccb86277f04685fdbb7aeeb/index.js#L9-L28
train
jaredhanson/kerouac
lib/index.js
createSite
function createSite() { function app(page) { app.handle(page); } mixin(app, EventEmitter.prototype, false); mixin(app, proto, false); app.init(); return app; }
javascript
function createSite() { function app(page) { app.handle(page); } mixin(app, EventEmitter.prototype, false); mixin(app, proto, false); app.init(); return app; }
[ "function", "createSite", "(", ")", "{", "function", "app", "(", "page", ")", "{", "app", ".", "handle", "(", "page", ")", ";", "}", "mixin", "(", "app", ",", "EventEmitter", ".", "prototype", ",", "false", ")", ";", "mixin", "(", "app", ",", "proto", ",", "false", ")", ";", "app", ".", "init", "(", ")", ";", "return", "app", ";", "}" ]
Create a Kerouac site. @return {Function} @api public
[ "Create", "a", "Kerouac", "site", "." ]
ab479484f56c1a530467e726f1271d08593b29c8
https://github.com/jaredhanson/kerouac/blob/ab479484f56c1a530467e726f1271d08593b29c8/lib/index.js#L16-L22
train
ethjs/ethjs-provider-http
src/index.js
invalidResponseError
function invalidResponseError(result, host) { const message = !!result && !!result.error && !!result.error.message ? `[ethjs-provider-http] ${result.error.message}` : `[ethjs-provider-http] Invalid JSON RPC response from host provider ${host}: ${JSON.stringify(result, null, 2)}`; return new Error(message); }
javascript
function invalidResponseError(result, host) { const message = !!result && !!result.error && !!result.error.message ? `[ethjs-provider-http] ${result.error.message}` : `[ethjs-provider-http] Invalid JSON RPC response from host provider ${host}: ${JSON.stringify(result, null, 2)}`; return new Error(message); }
[ "function", "invalidResponseError", "(", "result", ",", "host", ")", "{", "const", "message", "=", "!", "!", "result", "&&", "!", "!", "result", ".", "error", "&&", "!", "!", "result", ".", "error", ".", "message", "?", "`", "${", "result", ".", "error", ".", "message", "}", "`", ":", "`", "${", "host", "}", "${", "JSON", ".", "stringify", "(", "result", ",", "null", ",", "2", ")", "}", "`", ";", "return", "new", "Error", "(", "message", ")", ";", "}" ]
InvalidResponseError helper for invalid errors.
[ "InvalidResponseError", "helper", "for", "invalid", "errors", "." ]
03f911db08757bd5edeb5b613255a25df0124d84
https://github.com/ethjs/ethjs-provider-http/blob/03f911db08757bd5edeb5b613255a25df0124d84/src/index.js#L15-L18
train
ethjs/ethjs-provider-http
src/index.js
HttpProvider
function HttpProvider(host, timeout) { if (!(this instanceof HttpProvider)) { throw new Error('[ethjs-provider-http] the HttpProvider instance requires the "new" flag in order to function normally (e.g. `const eth = new Eth(new HttpProvider());`).'); } if (typeof host !== 'string') { throw new Error('[ethjs-provider-http] the HttpProvider instance requires that the host be specified (e.g. `new HttpProvider("http://localhost:8545")` or via service like infura `new HttpProvider("http://ropsten.infura.io")`)'); } const self = this; self.host = host; self.timeout = timeout || 0; }
javascript
function HttpProvider(host, timeout) { if (!(this instanceof HttpProvider)) { throw new Error('[ethjs-provider-http] the HttpProvider instance requires the "new" flag in order to function normally (e.g. `const eth = new Eth(new HttpProvider());`).'); } if (typeof host !== 'string') { throw new Error('[ethjs-provider-http] the HttpProvider instance requires that the host be specified (e.g. `new HttpProvider("http://localhost:8545")` or via service like infura `new HttpProvider("http://ropsten.infura.io")`)'); } const self = this; self.host = host; self.timeout = timeout || 0; }
[ "function", "HttpProvider", "(", "host", ",", "timeout", ")", "{", "if", "(", "!", "(", "this", "instanceof", "HttpProvider", ")", ")", "{", "throw", "new", "Error", "(", "'[ethjs-provider-http] the HttpProvider instance requires the \"new\" flag in order to function normally (e.g. `const eth = new Eth(new HttpProvider());`).'", ")", ";", "}", "if", "(", "typeof", "host", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'[ethjs-provider-http] the HttpProvider instance requires that the host be specified (e.g. `new HttpProvider(\"http://localhost:8545\")` or via service like infura `new HttpProvider(\"http://ropsten.infura.io\")`)'", ")", ";", "}", "const", "self", "=", "this", ";", "self", ".", "host", "=", "host", ";", "self", ".", "timeout", "=", "timeout", "||", "0", ";", "}" ]
HttpProvider should be used to send rpc calls over http
[ "HttpProvider", "should", "be", "used", "to", "send", "rpc", "calls", "over", "http" ]
03f911db08757bd5edeb5b613255a25df0124d84
https://github.com/ethjs/ethjs-provider-http/blob/03f911db08757bd5edeb5b613255a25df0124d84/src/index.js#L23-L30
train
k3erg/marantz-denon-telnet
index.js
function(ip) { this.connectionparams = { host: ip, port: 23, timeout: 1000, // The RESPONSE should be sent within 200ms of receiving the request COMMAND. (plus network delay) sendTimeout: 1200, negotiationMandatory: false, ors: '\r', // Set outbound record separator irs: '\r' }; this.cmdCue = []; this.connection = null; }
javascript
function(ip) { this.connectionparams = { host: ip, port: 23, timeout: 1000, // The RESPONSE should be sent within 200ms of receiving the request COMMAND. (plus network delay) sendTimeout: 1200, negotiationMandatory: false, ors: '\r', // Set outbound record separator irs: '\r' }; this.cmdCue = []; this.connection = null; }
[ "function", "(", "ip", ")", "{", "this", ".", "connectionparams", "=", "{", "host", ":", "ip", ",", "port", ":", "23", ",", "timeout", ":", "1000", ",", "sendTimeout", ":", "1200", ",", "negotiationMandatory", ":", "false", ",", "ors", ":", "'\\r'", ",", "\\r", "}", ";", "irs", ":", "'\\r'", "\\r", "}" ]
Returns an instance of MarantzDenonTelnet that can handle telnet commands to the given IP. @constructor @param {string} ip Address of the AVR.
[ "Returns", "an", "instance", "of", "MarantzDenonTelnet", "that", "can", "handle", "telnet", "commands", "to", "the", "given", "IP", "." ]
94ec2a19afd462a5ed82b38cfac33967519a03b5
https://github.com/k3erg/marantz-denon-telnet/blob/94ec2a19afd462a5ed82b38cfac33967519a03b5/index.js#L27-L39
train
MicrosoftDX/kurvejs
Samples/Client/Angular2/protractor.config.js
sendKeys
function sendKeys(element, str) { return str.split('').reduce(function (promise, char) { return promise.then(function () { return element.sendKeys(char); }); }, element.getAttribute('value')); // better to create a resolved promise here but ... don't know how with protractor; }
javascript
function sendKeys(element, str) { return str.split('').reduce(function (promise, char) { return promise.then(function () { return element.sendKeys(char); }); }, element.getAttribute('value')); // better to create a resolved promise here but ... don't know how with protractor; }
[ "function", "sendKeys", "(", "element", ",", "str", ")", "{", "return", "str", ".", "split", "(", "''", ")", ".", "reduce", "(", "function", "(", "promise", ",", "char", ")", "{", "return", "promise", ".", "then", "(", "function", "(", ")", "{", "return", "element", ".", "sendKeys", "(", "char", ")", ";", "}", ")", ";", "}", ",", "element", ".", "getAttribute", "(", "'value'", ")", ")", ";", "}" ]
Hack - because of bug with protractor send keys
[ "Hack", "-", "because", "of", "bug", "with", "protractor", "send", "keys" ]
72996425f1041ece8b4aa151db26c19a79f72f98
https://github.com/MicrosoftDX/kurvejs/blob/72996425f1041ece8b4aa151db26c19a79f72f98/Samples/Client/Angular2/protractor.config.js#L70-L77
train
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.SqliteAdapter.js
insertQuerySuccess
function insertQuerySuccess(resultSet) { resultSet.Action = 'inserted'; resultSet.ID = resultSet.rs.insertId; CRUD.stats.writesExecuted++; return resultSet; }
javascript
function insertQuerySuccess(resultSet) { resultSet.Action = 'inserted'; resultSet.ID = resultSet.rs.insertId; CRUD.stats.writesExecuted++; return resultSet; }
[ "function", "insertQuerySuccess", "(", "resultSet", ")", "{", "resultSet", ".", "Action", "=", "'inserted'", ";", "resultSet", ".", "ID", "=", "resultSet", ".", "rs", ".", "insertId", ";", "CRUD", ".", "stats", ".", "writesExecuted", "++", ";", "return", "resultSet", ";", "}" ]
Generic insert query callback that logs writesExecuted and sets inserted action + id @param {resultSet} resultSet resulting from an insert query. @return {resultSet} enriched resultSet with Action executed and ID property
[ "Generic", "insert", "query", "callback", "that", "logs", "writesExecuted", "and", "sets", "inserted", "action", "+", "id" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.SqliteAdapter.js#L71-L76
train
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.SqliteAdapter.js
insertQueryError
function insertQueryError(err, tx) { CRUD.stats.writesExecuted++; console.error("Insert query error: ", err); return err; }
javascript
function insertQueryError(err, tx) { CRUD.stats.writesExecuted++; console.error("Insert query error: ", err); return err; }
[ "function", "insertQueryError", "(", "err", ",", "tx", ")", "{", "CRUD", ".", "stats", ".", "writesExecuted", "++", ";", "console", ".", "error", "(", "\"Insert query error: \"", ",", "err", ")", ";", "return", "err", ";", "}" ]
Generic insert query error callback that logs writesExecuted and the error. @param {Error} err WebSQL error @param {Transaction} tx WebSQL Transaction @return {error}
[ "Generic", "insert", "query", "error", "callback", "that", "logs", "writesExecuted", "and", "the", "error", "." ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.SqliteAdapter.js#L84-L88
train
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.SqliteAdapter.js
parseSchemaInfo
function parseSchemaInfo(resultset) { for (var i = 0; i < resultset.rs.rows.length; i++) { var row = resultset.rs.rows.item(i); if (row.name.indexOf('sqlite_autoindex') > -1 || row.name == '__WebKitDatabaseInfoTable__') continue; if (row.type == 'table') { tables.push(row.tbl_name); } else if (row.type == 'index') { if (!(row.tbl_name in indexes)) { indexes[row.tbl_name] = []; } indexes[row.tbl_name].push(row.name); } } return; }
javascript
function parseSchemaInfo(resultset) { for (var i = 0; i < resultset.rs.rows.length; i++) { var row = resultset.rs.rows.item(i); if (row.name.indexOf('sqlite_autoindex') > -1 || row.name == '__WebKitDatabaseInfoTable__') continue; if (row.type == 'table') { tables.push(row.tbl_name); } else if (row.type == 'index') { if (!(row.tbl_name in indexes)) { indexes[row.tbl_name] = []; } indexes[row.tbl_name].push(row.name); } } return; }
[ "function", "parseSchemaInfo", "(", "resultset", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "resultset", ".", "rs", ".", "rows", ".", "length", ";", "i", "++", ")", "{", "var", "row", "=", "resultset", ".", "rs", ".", "rows", ".", "item", "(", "i", ")", ";", "if", "(", "row", ".", "name", ".", "indexOf", "(", "'sqlite_autoindex'", ")", ">", "-", "1", "||", "row", ".", "name", "==", "'__WebKitDatabaseInfoTable__'", ")", "continue", ";", "if", "(", "row", ".", "type", "==", "'table'", ")", "{", "tables", ".", "push", "(", "row", ".", "tbl_name", ")", ";", "}", "else", "if", "(", "row", ".", "type", "==", "'index'", ")", "{", "if", "(", "!", "(", "row", ".", "tbl_name", "in", "indexes", ")", ")", "{", "indexes", "[", "row", ".", "tbl_name", "]", "=", "[", "]", ";", "}", "indexes", "[", "row", ".", "tbl_name", "]", ".", "push", "(", "row", ".", "name", ")", ";", "}", "}", "return", ";", "}" ]
Pre-Parse database schema info for further processing. Finds tables and indexes. @param {resultSet} database description @return {void} void
[ "Pre", "-", "Parse", "database", "schema", "info", "for", "further", "processing", ".", "Finds", "tables", "and", "indexes", "." ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.SqliteAdapter.js#L111-L125
train
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.SqliteAdapter.js
createTables
function createTables() { return Promise.all(Object.keys(CRUD.EntityManager.entities).map(function(entityName) { var entity = CRUD.EntityManager.entities[entityName]; if (tables.indexOf(entity.table) == -1) { if (!entity.createStatement) { throw "No create statement found for " + entity.getType() + ". Don't know how to create table."; } return db.execute(entity.createStatement).then(function() { tables.push(entity.table); localStorage.setItem('database.version.' + entity.table, ('migrations' in entity) ? Math.max.apply(Math, Object.keys(entity.migrations)) : 1); CRUD.log(entity.table + " table created."); return entity; }, function(err) { CRUD.log("Error creating " + entity.table, err, entity.createStatement); throw "Error creating table: " + entity.table; }).then(createFixtures).then(function() { CRUD.log("Table created and fixtures inserted for ", entityName); return; }); } return; })); }
javascript
function createTables() { return Promise.all(Object.keys(CRUD.EntityManager.entities).map(function(entityName) { var entity = CRUD.EntityManager.entities[entityName]; if (tables.indexOf(entity.table) == -1) { if (!entity.createStatement) { throw "No create statement found for " + entity.getType() + ". Don't know how to create table."; } return db.execute(entity.createStatement).then(function() { tables.push(entity.table); localStorage.setItem('database.version.' + entity.table, ('migrations' in entity) ? Math.max.apply(Math, Object.keys(entity.migrations)) : 1); CRUD.log(entity.table + " table created."); return entity; }, function(err) { CRUD.log("Error creating " + entity.table, err, entity.createStatement); throw "Error creating table: " + entity.table; }).then(createFixtures).then(function() { CRUD.log("Table created and fixtures inserted for ", entityName); return; }); } return; })); }
[ "function", "createTables", "(", ")", "{", "return", "Promise", ".", "all", "(", "Object", ".", "keys", "(", "CRUD", ".", "EntityManager", ".", "entities", ")", ".", "map", "(", "function", "(", "entityName", ")", "{", "var", "entity", "=", "CRUD", ".", "EntityManager", ".", "entities", "[", "entityName", "]", ";", "if", "(", "tables", ".", "indexOf", "(", "entity", ".", "table", ")", "==", "-", "1", ")", "{", "if", "(", "!", "entity", ".", "createStatement", ")", "{", "throw", "\"No create statement found for \"", "+", "entity", ".", "getType", "(", ")", "+", "\". Don't know how to create table.\"", ";", "}", "return", "db", ".", "execute", "(", "entity", ".", "createStatement", ")", ".", "then", "(", "function", "(", ")", "{", "tables", ".", "push", "(", "entity", ".", "table", ")", ";", "localStorage", ".", "setItem", "(", "'database.version.'", "+", "entity", ".", "table", ",", "(", "'migrations'", "in", "entity", ")", "?", "Math", ".", "max", ".", "apply", "(", "Math", ",", "Object", ".", "keys", "(", "entity", ".", "migrations", ")", ")", ":", "1", ")", ";", "CRUD", ".", "log", "(", "entity", ".", "table", "+", "\" table created.\"", ")", ";", "return", "entity", ";", "}", ",", "function", "(", "err", ")", "{", "CRUD", ".", "log", "(", "\"Error creating \"", "+", "entity", ".", "table", ",", "err", ",", "entity", ".", "createStatement", ")", ";", "throw", "\"Error creating table: \"", "+", "entity", ".", "table", ";", "}", ")", ".", "then", "(", "createFixtures", ")", ".", "then", "(", "function", "(", ")", "{", "CRUD", ".", "log", "(", "\"Table created and fixtures inserted for \"", ",", "entityName", ")", ";", "return", ";", "}", ")", ";", "}", "return", ";", "}", ")", ")", ";", "}" ]
Iterate the list of registered entities and creates their tables if they don't exist. Run the migrations when needed if the table version is out of sync @return {void} void
[ "Iterate", "the", "list", "of", "registered", "entities", "and", "creates", "their", "tables", "if", "they", "don", "t", "exist", ".", "Run", "the", "migrations", "when", "needed", "if", "the", "table", "version", "is", "out", "of", "sync" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.SqliteAdapter.js#L132-L154
train
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.SqliteAdapter.js
createIndexes
function createIndexes() { // create listed indexes if they don't already exist. return Promise.all(Object.keys(CRUD.EntityManager.entities).map(function(entityName) { var entity = CRUD.EntityManager.entities[entityName]; if (('indexes' in entity)) { return Promise.all(entity.indexes.map(function(index) { var indexName = index.replace(/\W/g, '') + '_idx'; if (!(entity.table in indexes) || indexes[entity.table].indexOf(indexName) == -1) { return db.execute("create index if not exists " + indexName + " on " + entity.table + " (" + index + ")").then(function(result) { CRUD.log("index created: ", entity.table, index, indexName); if (!(entity.table in indexes)) { indexes[entity.table] = []; } indexes[entity.table].push(indexName); return; }); } return; })); } })); }
javascript
function createIndexes() { // create listed indexes if they don't already exist. return Promise.all(Object.keys(CRUD.EntityManager.entities).map(function(entityName) { var entity = CRUD.EntityManager.entities[entityName]; if (('indexes' in entity)) { return Promise.all(entity.indexes.map(function(index) { var indexName = index.replace(/\W/g, '') + '_idx'; if (!(entity.table in indexes) || indexes[entity.table].indexOf(indexName) == -1) { return db.execute("create index if not exists " + indexName + " on " + entity.table + " (" + index + ")").then(function(result) { CRUD.log("index created: ", entity.table, index, indexName); if (!(entity.table in indexes)) { indexes[entity.table] = []; } indexes[entity.table].push(indexName); return; }); } return; })); } })); }
[ "function", "createIndexes", "(", ")", "{", "return", "Promise", ".", "all", "(", "Object", ".", "keys", "(", "CRUD", ".", "EntityManager", ".", "entities", ")", ".", "map", "(", "function", "(", "entityName", ")", "{", "var", "entity", "=", "CRUD", ".", "EntityManager", ".", "entities", "[", "entityName", "]", ";", "if", "(", "(", "'indexes'", "in", "entity", ")", ")", "{", "return", "Promise", ".", "all", "(", "entity", ".", "indexes", ".", "map", "(", "function", "(", "index", ")", "{", "var", "indexName", "=", "index", ".", "replace", "(", "/", "\\W", "/", "g", ",", "''", ")", "+", "'_idx'", ";", "if", "(", "!", "(", "entity", ".", "table", "in", "indexes", ")", "||", "indexes", "[", "entity", ".", "table", "]", ".", "indexOf", "(", "indexName", ")", "==", "-", "1", ")", "{", "return", "db", ".", "execute", "(", "\"create index if not exists \"", "+", "indexName", "+", "\" on \"", "+", "entity", ".", "table", "+", "\" (\"", "+", "index", "+", "\")\"", ")", ".", "then", "(", "function", "(", "result", ")", "{", "CRUD", ".", "log", "(", "\"index created: \"", ",", "entity", ".", "table", ",", "index", ",", "indexName", ")", ";", "if", "(", "!", "(", "entity", ".", "table", "in", "indexes", ")", ")", "{", "indexes", "[", "entity", ".", "table", "]", "=", "[", "]", ";", "}", "indexes", "[", "entity", ".", "table", "]", ".", "push", "(", "indexName", ")", ";", "return", ";", "}", ")", ";", "}", "return", ";", "}", ")", ")", ";", "}", "}", ")", ")", ";", "}" ]
Iterate the list of existing and non-existing indexes for each entity and create the ones that don't exist. @return {void} void
[ "Iterate", "the", "list", "of", "existing", "and", "non", "-", "existing", "indexes", "for", "each", "entity", "and", "create", "the", "ones", "that", "don", "t", "exist", "." ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.SqliteAdapter.js#L198-L219
train
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.SqliteAdapter.js
createFixtures
function createFixtures(entity) { return new Promise(function(resolve, reject) { if (!entity.fixtures) return resolve(); return Promise.all(entity.fixtures.map(function(fixture) { CRUD.fromCache(entity.getType(), fixture).Persist(true); })).then(resolve, reject); }); }
javascript
function createFixtures(entity) { return new Promise(function(resolve, reject) { if (!entity.fixtures) return resolve(); return Promise.all(entity.fixtures.map(function(fixture) { CRUD.fromCache(entity.getType(), fixture).Persist(true); })).then(resolve, reject); }); }
[ "function", "createFixtures", "(", "entity", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "if", "(", "!", "entity", ".", "fixtures", ")", "return", "resolve", "(", ")", ";", "return", "Promise", ".", "all", "(", "entity", ".", "fixtures", ".", "map", "(", "function", "(", "fixture", ")", "{", "CRUD", ".", "fromCache", "(", "entity", ".", "getType", "(", ")", ",", "fixture", ")", ".", "Persist", "(", "true", ")", ";", "}", ")", ")", ".", "then", "(", "resolve", ",", "reject", ")", ";", "}", ")", ";", "}" ]
Insert fixtures for an entity if they exist @param {CRUD.Entity} entity entity to insert fixtures for @return {Promise} that resolves when all fixtures were inserted or immediately when none are defined
[ "Insert", "fixtures", "for", "an", "entity", "if", "they", "exist" ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.SqliteAdapter.js#L237-L244
train
SchizoDuckie/CreateReadUpdateDelete.js
src/CRUD.js
function(field, def) { var ret; if (field in this.__dirtyValues__) { ret = this.__dirtyValues__[field]; } else if (field in this.__values__) { ret = this.__values__[field]; } else if (CRUD.EntityManager.entities[this.getType()].fields.indexOf(field) > -1) { ret = (field in CRUD.EntityManager.entities[this.getType()].defaultValues) ? CRUD.EntityManager.entities[this.getType()].defaultValues[field] : null; } else { CRUD.log('Could not find field \'' + field + '\' in \'' + this.getType() + '\' (for get)'); } return ret; }
javascript
function(field, def) { var ret; if (field in this.__dirtyValues__) { ret = this.__dirtyValues__[field]; } else if (field in this.__values__) { ret = this.__values__[field]; } else if (CRUD.EntityManager.entities[this.getType()].fields.indexOf(field) > -1) { ret = (field in CRUD.EntityManager.entities[this.getType()].defaultValues) ? CRUD.EntityManager.entities[this.getType()].defaultValues[field] : null; } else { CRUD.log('Could not find field \'' + field + '\' in \'' + this.getType() + '\' (for get)'); } return ret; }
[ "function", "(", "field", ",", "def", ")", "{", "var", "ret", ";", "if", "(", "field", "in", "this", ".", "__dirtyValues__", ")", "{", "ret", "=", "this", ".", "__dirtyValues__", "[", "field", "]", ";", "}", "else", "if", "(", "field", "in", "this", ".", "__values__", ")", "{", "ret", "=", "this", ".", "__values__", "[", "field", "]", ";", "}", "else", "if", "(", "CRUD", ".", "EntityManager", ".", "entities", "[", "this", ".", "getType", "(", ")", "]", ".", "fields", ".", "indexOf", "(", "field", ")", ">", "-", "1", ")", "{", "ret", "=", "(", "field", "in", "CRUD", ".", "EntityManager", ".", "entities", "[", "this", ".", "getType", "(", ")", "]", ".", "defaultValues", ")", "?", "CRUD", ".", "EntityManager", ".", "entities", "[", "this", ".", "getType", "(", ")", "]", ".", "defaultValues", "[", "field", "]", ":", "null", ";", "}", "else", "{", "CRUD", ".", "log", "(", "'Could not find field \\''", "+", "\\'", "+", "field", "+", "'\\' in \\''", "+", "\\'", ")", ";", "}", "\\'", "}" ]
Accessor. Gets one field, optionally returns the default value.
[ "Accessor", ".", "Gets", "one", "field", "optionally", "returns", "the", "default", "value", "." ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/src/CRUD.js#L366-L378
train
jaredhanson/kerouac
lib/route.js
Route
function Route(path, fns, options) { options = options || {}; this.path = path; this.fns = fns; this.regexp = pathRegexp(path, this.keys = [], options); }
javascript
function Route(path, fns, options) { options = options || {}; this.path = path; this.fns = fns; this.regexp = pathRegexp(path, this.keys = [], options); }
[ "function", "Route", "(", "path", ",", "fns", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "path", "=", "path", ";", "this", ".", "fns", "=", "fns", ";", "this", ".", "regexp", "=", "pathRegexp", "(", "path", ",", "this", ".", "keys", "=", "[", "]", ",", "options", ")", ";", "}" ]
Initialize a new `Route` with the given `path`, an array of callback `fns`, and `options`. Options: - `sensitive` enable case-sensitive routes - `strict` enable strict matching for trailing slashes @param {String} path @param {Array} fns @param {Object} options @api private
[ "Initialize", "a", "new", "Route", "with", "the", "given", "path", "an", "array", "of", "callback", "fns", "and", "options", "." ]
ab479484f56c1a530467e726f1271d08593b29c8
https://github.com/jaredhanson/kerouac/blob/ab479484f56c1a530467e726f1271d08593b29c8/lib/route.js#L18-L23
train
ShaneGH/analogue-time-picker
tools/generateHtmlFile.js
buildFile
function buildFile() { var reader = readline.createInterface({ input: fs.createReadStream(path.resolve("./src/assets/template.html")) }); var lines = []; reader.on("line", line => lines.push(line)); return new Promise(resolve => { reader.on("close", () => resolve(buildJsFileContents(lines))); }); }
javascript
function buildFile() { var reader = readline.createInterface({ input: fs.createReadStream(path.resolve("./src/assets/template.html")) }); var lines = []; reader.on("line", line => lines.push(line)); return new Promise(resolve => { reader.on("close", () => resolve(buildJsFileContents(lines))); }); }
[ "function", "buildFile", "(", ")", "{", "var", "reader", "=", "readline", ".", "createInterface", "(", "{", "input", ":", "fs", ".", "createReadStream", "(", "path", ".", "resolve", "(", "\"./src/assets/template.html\"", ")", ")", "}", ")", ";", "var", "lines", "=", "[", "]", ";", "reader", ".", "on", "(", "\"line\"", ",", "line", "=>", "lines", ".", "push", "(", "line", ")", ")", ";", "return", "new", "Promise", "(", "resolve", "=>", "{", "reader", ".", "on", "(", "\"close\"", ",", "(", ")", "=>", "resolve", "(", "buildJsFileContents", "(", "lines", ")", ")", ")", ";", "}", ")", ";", "}" ]
Build a promise which will generate css -> js file contents
[ "Build", "a", "promise", "which", "will", "generate", "css", "-", ">", "js", "file", "contents" ]
026c0c37608f749041dde375551f5ff16cd5621e
https://github.com/ShaneGH/analogue-time-picker/blob/026c0c37608f749041dde375551f5ff16cd5621e/tools/generateHtmlFile.js#L76-L87
train
chemerisuk/cordova-plugin-core-android-extensions
www/android/coreextensions.js
function(moveBack) { return new Promise(function(resolve, reject) { exec(resolve, reject, APP_PLUGIN_NAME, "minimizeApp", [moveBack || false]); }); }
javascript
function(moveBack) { return new Promise(function(resolve, reject) { exec(resolve, reject, APP_PLUGIN_NAME, "minimizeApp", [moveBack || false]); }); }
[ "function", "(", "moveBack", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "exec", "(", "resolve", ",", "reject", ",", "APP_PLUGIN_NAME", ",", "\"minimizeApp\"", ",", "[", "moveBack", "||", "false", "]", ")", ";", "}", ")", ";", "}" ]
Go to home screen
[ "Go", "to", "home", "screen" ]
d65ad5dbde7bd3024d4e978f71fa5214b02b18e6
https://github.com/chemerisuk/cordova-plugin-core-android-extensions/blob/d65ad5dbde7bd3024d4e978f71fa5214b02b18e6/www/android/coreextensions.js#L8-L12
train
chemerisuk/cordova-plugin-core-android-extensions
www/android/coreextensions.js
function(packageName, componentName) { return new Promise(function(resolve, reject) { exec(resolve, reject, APP_PLUGIN_NAME, "startApp", [packageName, componentName]); }); }
javascript
function(packageName, componentName) { return new Promise(function(resolve, reject) { exec(resolve, reject, APP_PLUGIN_NAME, "startApp", [packageName, componentName]); }); }
[ "function", "(", "packageName", ",", "componentName", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "exec", "(", "resolve", ",", "reject", ",", "APP_PLUGIN_NAME", ",", "\"startApp\"", ",", "[", "packageName", ",", "componentName", "]", ")", ";", "}", ")", ";", "}" ]
Starts app intent
[ "Starts", "app", "intent" ]
d65ad5dbde7bd3024d4e978f71fa5214b02b18e6
https://github.com/chemerisuk/cordova-plugin-core-android-extensions/blob/d65ad5dbde7bd3024d4e978f71fa5214b02b18e6/www/android/coreextensions.js#L44-L48
train
SchizoDuckie/CreateReadUpdateDelete.js
cli/questions.js
promisePrompt
function promisePrompt(questions) { return new Promise(function(resolve, reject) { inquirer.prompt(questions, function(results) { resolve(results); }); }); }
javascript
function promisePrompt(questions) { return new Promise(function(resolve, reject) { inquirer.prompt(questions, function(results) { resolve(results); }); }); }
[ "function", "promisePrompt", "(", "questions", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "inquirer", ".", "prompt", "(", "questions", ",", "function", "(", "results", ")", "{", "resolve", "(", "results", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Convert inquirer.prompt to a promise.
[ "Convert", "inquirer", ".", "prompt", "to", "a", "promise", "." ]
e8fb05fd0b36931699eb779e98086e9e6f7328aa
https://github.com/SchizoDuckie/CreateReadUpdateDelete.js/blob/e8fb05fd0b36931699eb779e98086e9e6f7328aa/cli/questions.js#L20-L26
train
ShaneGH/analogue-time-picker
tools/generateCssFile.js
buildJsFileContent
function buildJsFileContent(lines) { var ls = lines .map(l => l // remove space at beginning of line .replace(/^\s*/g, "") // remove space at end of line .replace(/\s*$/g, "") // convert \ to \\ .replace(/\\/g, "\\\\") // convert " to \" .replace(/"/g, "\\\"") // convert " { " to "{" .replace(/\s*\{\s*/g, "{") // convert " : " to ":" .replace(/\s*:\s*/g, ":")) .join("") // remove comments .replace(/\/\*.+?\*\//g, ""); return [ // add css string `var css = "${ls}";`, "var enabled = false;", "", // add function which injects css into page "function enable () {", "\tif (enabled) return;", "\tenabled = true;", "", "\tvar el = document.createElement('style');", "\tel.innerHTML = css;", "", "\tvar parent = document.head || document.body;", "\tparent.firstChild ?", "\t\tparent.insertBefore(el, parent.firstChild) :", "\t\tparent.appendChild(el);", "}", "", "export {", "\tenable", "}" ].join("\n"); }
javascript
function buildJsFileContent(lines) { var ls = lines .map(l => l // remove space at beginning of line .replace(/^\s*/g, "") // remove space at end of line .replace(/\s*$/g, "") // convert \ to \\ .replace(/\\/g, "\\\\") // convert " to \" .replace(/"/g, "\\\"") // convert " { " to "{" .replace(/\s*\{\s*/g, "{") // convert " : " to ":" .replace(/\s*:\s*/g, ":")) .join("") // remove comments .replace(/\/\*.+?\*\//g, ""); return [ // add css string `var css = "${ls}";`, "var enabled = false;", "", // add function which injects css into page "function enable () {", "\tif (enabled) return;", "\tenabled = true;", "", "\tvar el = document.createElement('style');", "\tel.innerHTML = css;", "", "\tvar parent = document.head || document.body;", "\tparent.firstChild ?", "\t\tparent.insertBefore(el, parent.firstChild) :", "\t\tparent.appendChild(el);", "}", "", "export {", "\tenable", "}" ].join("\n"); }
[ "function", "buildJsFileContent", "(", "lines", ")", "{", "var", "ls", "=", "lines", ".", "map", "(", "l", "=>", "l", ".", "replace", "(", "/", "^\\s*", "/", "g", ",", "\"\"", ")", ".", "replace", "(", "/", "\\s*$", "/", "g", ",", "\"\"", ")", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "\"\\\\\\\\\"", ")", ".", "\\\\", "\\\\", ".", "replace", "(", "/", "\"", "/", "g", ",", "\"\\\\\\\"\"", ")", ".", "\\\\", "\\\"", ")", ".", "replace", "(", "/", "\\s*\\{\\s*", "/", "g", ",", "\"{\"", ")", ".", "replace", "(", "/", "\\s*:\\s*", "/", "g", ",", "\":\"", ")", ";", "join", "}" ]
Create the js content of the file to add css
[ "Create", "the", "js", "content", "of", "the", "file", "to", "add", "css" ]
026c0c37608f749041dde375551f5ff16cd5621e
https://github.com/ShaneGH/analogue-time-picker/blob/026c0c37608f749041dde375551f5ff16cd5621e/tools/generateCssFile.js#L6-L48
train
bvaughn/jasmine-es6-promise-matchers
jasmine-es6-promise-matchers.js
function(done, promise, expectedState, expectedData, isNegative) { function verify(promiseState) { return function(data) { var test = verifyState(promiseState, expectedState); if (test.pass) { test = verifyData(data, expectedData); } if (!test.pass && !isNegative) { done.fail(new Error(test.message)); return; } done(); } } promise.then( verify(PROMISE_STATE.RESOLVED), verify(PROMISE_STATE.REJECTED) ); return { pass: true }; }
javascript
function(done, promise, expectedState, expectedData, isNegative) { function verify(promiseState) { return function(data) { var test = verifyState(promiseState, expectedState); if (test.pass) { test = verifyData(data, expectedData); } if (!test.pass && !isNegative) { done.fail(new Error(test.message)); return; } done(); } } promise.then( verify(PROMISE_STATE.RESOLVED), verify(PROMISE_STATE.REJECTED) ); return { pass: true }; }
[ "function", "(", "done", ",", "promise", ",", "expectedState", ",", "expectedData", ",", "isNegative", ")", "{", "function", "verify", "(", "promiseState", ")", "{", "return", "function", "(", "data", ")", "{", "var", "test", "=", "verifyState", "(", "promiseState", ",", "expectedState", ")", ";", "if", "(", "test", ".", "pass", ")", "{", "test", "=", "verifyData", "(", "data", ",", "expectedData", ")", ";", "}", "if", "(", "!", "test", ".", "pass", "&&", "!", "isNegative", ")", "{", "done", ".", "fail", "(", "new", "Error", "(", "test", ".", "message", ")", ")", ";", "return", ";", "}", "done", "(", ")", ";", "}", "}", "promise", ".", "then", "(", "verify", "(", "PROMISE_STATE", ".", "RESOLVED", ")", ",", "verify", "(", "PROMISE_STATE", ".", "REJECTED", ")", ")", ";", "return", "{", "pass", ":", "true", "}", ";", "}" ]
Helper method to verify expectations and return a Jasmine-friendly info-object
[ "Helper", "method", "to", "verify", "expectations", "and", "return", "a", "Jasmine", "-", "friendly", "info", "-", "object" ]
7c1eabf0919b2b28d19628ecd49e5d7a092104b7
https://github.com/bvaughn/jasmine-es6-promise-matchers/blob/7c1eabf0919b2b28d19628ecd49e5d7a092104b7/jasmine-es6-promise-matchers.js#L81-L105
train
kogarashisan/ClassManager
lib/class_manager.js
function(class_data, path) { var implements_source = this._sources[path], name, references_offset; if (Lava.schema.DEBUG) { if (!implements_source) Lava.t('Implements: class not found - "' + path + '"'); for (name in implements_source.shared) Lava.t("Implements: unable to use a class with Shared as mixin."); if (class_data.implements.indexOf(path) != -1) Lava.t("Implements: class " + class_data.path + " already implements " + path); } class_data.implements.push(path); references_offset = class_data.references.length; // array copy is inexpensive, cause it contains only reference types class_data.references = class_data.references.concat(implements_source.references); this._extend(class_data, class_data.skeleton, implements_source, implements_source.skeleton, true, references_offset); }
javascript
function(class_data, path) { var implements_source = this._sources[path], name, references_offset; if (Lava.schema.DEBUG) { if (!implements_source) Lava.t('Implements: class not found - "' + path + '"'); for (name in implements_source.shared) Lava.t("Implements: unable to use a class with Shared as mixin."); if (class_data.implements.indexOf(path) != -1) Lava.t("Implements: class " + class_data.path + " already implements " + path); } class_data.implements.push(path); references_offset = class_data.references.length; // array copy is inexpensive, cause it contains only reference types class_data.references = class_data.references.concat(implements_source.references); this._extend(class_data, class_data.skeleton, implements_source, implements_source.skeleton, true, references_offset); }
[ "function", "(", "class_data", ",", "path", ")", "{", "var", "implements_source", "=", "this", ".", "_sources", "[", "path", "]", ",", "name", ",", "references_offset", ";", "if", "(", "Lava", ".", "schema", ".", "DEBUG", ")", "{", "if", "(", "!", "implements_source", ")", "Lava", ".", "t", "(", "'Implements: class not found - \"'", "+", "path", "+", "'\"'", ")", ";", "for", "(", "name", "in", "implements_source", ".", "shared", ")", "Lava", ".", "t", "(", "\"Implements: unable to use a class with Shared as mixin.\"", ")", ";", "if", "(", "class_data", ".", "implements", ".", "indexOf", "(", "path", ")", "!=", "-", "1", ")", "Lava", ".", "t", "(", "\"Implements: class \"", "+", "class_data", ".", "path", "+", "\" already implements \"", "+", "path", ")", ";", "}", "class_data", ".", "implements", ".", "push", "(", "path", ")", ";", "references_offset", "=", "class_data", ".", "references", ".", "length", ";", "class_data", ".", "references", "=", "class_data", ".", "references", ".", "concat", "(", "implements_source", ".", "references", ")", ";", "this", ".", "_extend", "(", "class_data", ",", "class_data", ".", "skeleton", ",", "implements_source", ",", "implements_source", ".", "skeleton", ",", "true", ",", "references_offset", ")", ";", "}" ]
Implement members from another class into current class data @param {_cClassData} class_data @param {string} path
[ "Implement", "members", "from", "another", "class", "into", "current", "class", "data" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L427-L448
train
kogarashisan/ClassManager
lib/class_manager.js
function(class_data, source_object, is_root) { var name, skeleton = {}, value, type, skeleton_value; for (name in source_object) { if (is_root && (this._reserved_members.indexOf(name) != -1 || (name in class_data.shared))) { continue; } value = source_object[name]; type = Firestorm.getType(value); switch (type) { case 'null': case 'boolean': case 'number': skeleton_value = {type: this.MEMBER_TYPES.PRIMITIVE, value: value}; break; case 'string': skeleton_value = {type: this.MEMBER_TYPES.STRING, value: value}; break; case 'function': skeleton_value = {type: this.MEMBER_TYPES.FUNCTION, index: class_data.references.length}; class_data.references.push(value); break; case 'regexp': skeleton_value = {type: this.MEMBER_TYPES.REGEXP, index: class_data.references.length}; class_data.references.push(value); break; case 'object': skeleton_value = { type: this.MEMBER_TYPES.OBJECT, skeleton: this._disassemble(class_data, value, false) }; break; case 'array': if (value.length == 0) { skeleton_value = {type: this.MEMBER_TYPES.EMPTY_ARRAY}; } else if (this.inline_simple_arrays && this.isInlineArray(value)) { skeleton_value = {type: this.MEMBER_TYPES.INLINE_ARRAY, value: value}; } else { skeleton_value = {type: this.MEMBER_TYPES.SLICE_ARRAY, index: class_data.references.length}; class_data.references.push(value); } break; case 'undefined': Lava.t("[ClassManager] Forced code style restriction: please, replace undefined member values with null. Member name: " + name); break; default: Lava.t("[ClassManager] Unsupported property type in source object: " + type); break; } skeleton[name] = skeleton_value; } return skeleton; }
javascript
function(class_data, source_object, is_root) { var name, skeleton = {}, value, type, skeleton_value; for (name in source_object) { if (is_root && (this._reserved_members.indexOf(name) != -1 || (name in class_data.shared))) { continue; } value = source_object[name]; type = Firestorm.getType(value); switch (type) { case 'null': case 'boolean': case 'number': skeleton_value = {type: this.MEMBER_TYPES.PRIMITIVE, value: value}; break; case 'string': skeleton_value = {type: this.MEMBER_TYPES.STRING, value: value}; break; case 'function': skeleton_value = {type: this.MEMBER_TYPES.FUNCTION, index: class_data.references.length}; class_data.references.push(value); break; case 'regexp': skeleton_value = {type: this.MEMBER_TYPES.REGEXP, index: class_data.references.length}; class_data.references.push(value); break; case 'object': skeleton_value = { type: this.MEMBER_TYPES.OBJECT, skeleton: this._disassemble(class_data, value, false) }; break; case 'array': if (value.length == 0) { skeleton_value = {type: this.MEMBER_TYPES.EMPTY_ARRAY}; } else if (this.inline_simple_arrays && this.isInlineArray(value)) { skeleton_value = {type: this.MEMBER_TYPES.INLINE_ARRAY, value: value}; } else { skeleton_value = {type: this.MEMBER_TYPES.SLICE_ARRAY, index: class_data.references.length}; class_data.references.push(value); } break; case 'undefined': Lava.t("[ClassManager] Forced code style restriction: please, replace undefined member values with null. Member name: " + name); break; default: Lava.t("[ClassManager] Unsupported property type in source object: " + type); break; } skeleton[name] = skeleton_value; } return skeleton; }
[ "function", "(", "class_data", ",", "source_object", ",", "is_root", ")", "{", "var", "name", ",", "skeleton", "=", "{", "}", ",", "value", ",", "type", ",", "skeleton_value", ";", "for", "(", "name", "in", "source_object", ")", "{", "if", "(", "is_root", "&&", "(", "this", ".", "_reserved_members", ".", "indexOf", "(", "name", ")", "!=", "-", "1", "||", "(", "name", "in", "class_data", ".", "shared", ")", ")", ")", "{", "continue", ";", "}", "value", "=", "source_object", "[", "name", "]", ";", "type", "=", "Firestorm", ".", "getType", "(", "value", ")", ";", "switch", "(", "type", ")", "{", "case", "'null'", ":", "case", "'boolean'", ":", "case", "'number'", ":", "skeleton_value", "=", "{", "type", ":", "this", ".", "MEMBER_TYPES", ".", "PRIMITIVE", ",", "value", ":", "value", "}", ";", "break", ";", "case", "'string'", ":", "skeleton_value", "=", "{", "type", ":", "this", ".", "MEMBER_TYPES", ".", "STRING", ",", "value", ":", "value", "}", ";", "break", ";", "case", "'function'", ":", "skeleton_value", "=", "{", "type", ":", "this", ".", "MEMBER_TYPES", ".", "FUNCTION", ",", "index", ":", "class_data", ".", "references", ".", "length", "}", ";", "class_data", ".", "references", ".", "push", "(", "value", ")", ";", "break", ";", "case", "'regexp'", ":", "skeleton_value", "=", "{", "type", ":", "this", ".", "MEMBER_TYPES", ".", "REGEXP", ",", "index", ":", "class_data", ".", "references", ".", "length", "}", ";", "class_data", ".", "references", ".", "push", "(", "value", ")", ";", "break", ";", "case", "'object'", ":", "skeleton_value", "=", "{", "type", ":", "this", ".", "MEMBER_TYPES", ".", "OBJECT", ",", "skeleton", ":", "this", ".", "_disassemble", "(", "class_data", ",", "value", ",", "false", ")", "}", ";", "break", ";", "case", "'array'", ":", "if", "(", "value", ".", "length", "==", "0", ")", "{", "skeleton_value", "=", "{", "type", ":", "this", ".", "MEMBER_TYPES", ".", "EMPTY_ARRAY", "}", ";", "}", "else", "if", "(", "this", ".", "inline_simple_arrays", "&&", "this", ".", "isInlineArray", "(", "value", ")", ")", "{", "skeleton_value", "=", "{", "type", ":", "this", ".", "MEMBER_TYPES", ".", "INLINE_ARRAY", ",", "value", ":", "value", "}", ";", "}", "else", "{", "skeleton_value", "=", "{", "type", ":", "this", ".", "MEMBER_TYPES", ".", "SLICE_ARRAY", ",", "index", ":", "class_data", ".", "references", ".", "length", "}", ";", "class_data", ".", "references", ".", "push", "(", "value", ")", ";", "}", "break", ";", "case", "'undefined'", ":", "Lava", ".", "t", "(", "\"[ClassManager] Forced code style restriction: please, replace undefined member values with null. Member name: \"", "+", "name", ")", ";", "break", ";", "default", ":", "Lava", ".", "t", "(", "\"[ClassManager] Unsupported property type in source object: \"", "+", "type", ")", ";", "break", ";", "}", "skeleton", "[", "name", "]", "=", "skeleton_value", ";", "}", "return", "skeleton", ";", "}" ]
Recursively create skeletons for all objects inside class body @param {_cClassData} class_data @param {Object} source_object @param {boolean} is_root @returns {Object}
[ "Recursively", "create", "skeletons", "for", "all", "objects", "inside", "class", "body" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L524-L590
train
kogarashisan/ClassManager
lib/class_manager.js
function(skeleton, class_data, padding, serialized_properties) { var name, serialized_value, uses_references = false, object_properties; for (name in skeleton) { switch (skeleton[name].type) { case this.MEMBER_TYPES.STRING: serialized_value = Firestorm.String.quote(skeleton[name].value); break; case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number serialized_value = skeleton[name].value + ''; break; case this.MEMBER_TYPES.REGEXP: case this.MEMBER_TYPES.FUNCTION: serialized_value = 'r[' + skeleton[name].index + ']'; uses_references = true; break; case this.MEMBER_TYPES.EMPTY_ARRAY: serialized_value = "[]"; break; case this.MEMBER_TYPES.INLINE_ARRAY: serialized_value = this._serializeInlineArray(skeleton[name].value); break; case this.MEMBER_TYPES.SLICE_ARRAY: serialized_value = 'r[' + skeleton[name].index + '].slice()'; uses_references = true; break; case this.MEMBER_TYPES.OBJECT: object_properties = []; if (this._serializeSkeleton(skeleton[name].skeleton, class_data, padding + "\t", object_properties)) { uses_references = true; } serialized_value = object_properties.length ? "{\n\t" + padding + object_properties.join(",\n\t" + padding) + "\n" + padding + "}" : "{}"; break; default: Lava.t("[_serializeSkeleton] unknown property descriptor type: " + skeleton[name].type); } if (Lava.VALID_PROPERTY_NAME_REGEX.test(name) && Lava.JS_KEYWORDS.indexOf(name) == -1) { serialized_properties.push(name + ': ' + serialized_value); } else { serialized_properties.push(Firestorm.String.quote(name) + ': ' + serialized_value); } } return uses_references; }
javascript
function(skeleton, class_data, padding, serialized_properties) { var name, serialized_value, uses_references = false, object_properties; for (name in skeleton) { switch (skeleton[name].type) { case this.MEMBER_TYPES.STRING: serialized_value = Firestorm.String.quote(skeleton[name].value); break; case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number serialized_value = skeleton[name].value + ''; break; case this.MEMBER_TYPES.REGEXP: case this.MEMBER_TYPES.FUNCTION: serialized_value = 'r[' + skeleton[name].index + ']'; uses_references = true; break; case this.MEMBER_TYPES.EMPTY_ARRAY: serialized_value = "[]"; break; case this.MEMBER_TYPES.INLINE_ARRAY: serialized_value = this._serializeInlineArray(skeleton[name].value); break; case this.MEMBER_TYPES.SLICE_ARRAY: serialized_value = 'r[' + skeleton[name].index + '].slice()'; uses_references = true; break; case this.MEMBER_TYPES.OBJECT: object_properties = []; if (this._serializeSkeleton(skeleton[name].skeleton, class_data, padding + "\t", object_properties)) { uses_references = true; } serialized_value = object_properties.length ? "{\n\t" + padding + object_properties.join(",\n\t" + padding) + "\n" + padding + "}" : "{}"; break; default: Lava.t("[_serializeSkeleton] unknown property descriptor type: " + skeleton[name].type); } if (Lava.VALID_PROPERTY_NAME_REGEX.test(name) && Lava.JS_KEYWORDS.indexOf(name) == -1) { serialized_properties.push(name + ': ' + serialized_value); } else { serialized_properties.push(Firestorm.String.quote(name) + ': ' + serialized_value); } } return uses_references; }
[ "function", "(", "skeleton", ",", "class_data", ",", "padding", ",", "serialized_properties", ")", "{", "var", "name", ",", "serialized_value", ",", "uses_references", "=", "false", ",", "object_properties", ";", "for", "(", "name", "in", "skeleton", ")", "{", "switch", "(", "skeleton", "[", "name", "]", ".", "type", ")", "{", "case", "this", ".", "MEMBER_TYPES", ".", "STRING", ":", "serialized_value", "=", "Firestorm", ".", "String", ".", "quote", "(", "skeleton", "[", "name", "]", ".", "value", ")", ";", "break", ";", "case", "this", ".", "MEMBER_TYPES", ".", "PRIMITIVE", ":", "serialized_value", "=", "skeleton", "[", "name", "]", ".", "value", "+", "''", ";", "break", ";", "case", "this", ".", "MEMBER_TYPES", ".", "REGEXP", ":", "case", "this", ".", "MEMBER_TYPES", ".", "FUNCTION", ":", "serialized_value", "=", "'r['", "+", "skeleton", "[", "name", "]", ".", "index", "+", "']'", ";", "uses_references", "=", "true", ";", "break", ";", "case", "this", ".", "MEMBER_TYPES", ".", "EMPTY_ARRAY", ":", "serialized_value", "=", "\"[]\"", ";", "break", ";", "case", "this", ".", "MEMBER_TYPES", ".", "INLINE_ARRAY", ":", "serialized_value", "=", "this", ".", "_serializeInlineArray", "(", "skeleton", "[", "name", "]", ".", "value", ")", ";", "break", ";", "case", "this", ".", "MEMBER_TYPES", ".", "SLICE_ARRAY", ":", "serialized_value", "=", "'r['", "+", "skeleton", "[", "name", "]", ".", "index", "+", "'].slice()'", ";", "uses_references", "=", "true", ";", "break", ";", "case", "this", ".", "MEMBER_TYPES", ".", "OBJECT", ":", "object_properties", "=", "[", "]", ";", "if", "(", "this", ".", "_serializeSkeleton", "(", "skeleton", "[", "name", "]", ".", "skeleton", ",", "class_data", ",", "padding", "+", "\"\\t\"", ",", "\\t", ")", ")", "object_properties", "{", "uses_references", "=", "true", ";", "}", "serialized_value", "=", "object_properties", ".", "length", "?", "\"{\\n\\t\"", "+", "\\n", "+", "\\t", "+", "padding", "+", "object_properties", ".", "join", "(", "\",\\n\\t\"", "+", "\\n", ")", "+", "\\t", ":", "padding", ";", "\"\\n\"", "}", "\\n", "}", "padding", "}" ]
Perform special class serialization, that takes functions and resources from class data and can be used in constructors @param {Object} skeleton @param {_cClassData} class_data @param {string} padding @param {Array} serialized_properties @returns {boolean} <kw>true</kw>, if object uses {@link _cClassData#references}
[ "Perform", "special", "class", "serialization", "that", "takes", "functions", "and", "resources", "from", "class", "data", "and", "can", "be", "used", "in", "constructors" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L706-L763
train
kogarashisan/ClassManager
lib/class_manager.js
function(path_segments) { var namespace, segment_name, count = path_segments.length, i = 1; if (!count) Lava.t("ClassManager: class names must include a namespace, even for global classes."); if (!(path_segments[0] in this._root)) Lava.t("[ClassManager] namespace is not registered: " + path_segments[0]); namespace = this._root[path_segments[0]]; for (; i < count; i++) { segment_name = path_segments[i]; if (!(segment_name in namespace)) { namespace[segment_name] = {}; } namespace = namespace[segment_name]; } return namespace; }
javascript
function(path_segments) { var namespace, segment_name, count = path_segments.length, i = 1; if (!count) Lava.t("ClassManager: class names must include a namespace, even for global classes."); if (!(path_segments[0] in this._root)) Lava.t("[ClassManager] namespace is not registered: " + path_segments[0]); namespace = this._root[path_segments[0]]; for (; i < count; i++) { segment_name = path_segments[i]; if (!(segment_name in namespace)) { namespace[segment_name] = {}; } namespace = namespace[segment_name]; } return namespace; }
[ "function", "(", "path_segments", ")", "{", "var", "namespace", ",", "segment_name", ",", "count", "=", "path_segments", ".", "length", ",", "i", "=", "1", ";", "if", "(", "!", "count", ")", "Lava", ".", "t", "(", "\"ClassManager: class names must include a namespace, even for global classes.\"", ")", ";", "if", "(", "!", "(", "path_segments", "[", "0", "]", "in", "this", ".", "_root", ")", ")", "Lava", ".", "t", "(", "\"[ClassManager] namespace is not registered: \"", "+", "path_segments", "[", "0", "]", ")", ";", "namespace", "=", "this", ".", "_root", "[", "path_segments", "[", "0", "]", "]", ";", "for", "(", ";", "i", "<", "count", ";", "i", "++", ")", "{", "segment_name", "=", "path_segments", "[", "i", "]", ";", "if", "(", "!", "(", "segment_name", "in", "namespace", ")", ")", "{", "namespace", "[", "segment_name", "]", "=", "{", "}", ";", "}", "namespace", "=", "namespace", "[", "segment_name", "]", ";", "}", "return", "namespace", ";", "}" ]
Get namespace for a class constructor @param {Array.<string>} path_segments Path to the namespace of a class. Must start with one of registered roots @returns {Object}
[ "Get", "namespace", "for", "a", "class", "constructor" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L770-L797
train
kogarashisan/ClassManager
lib/class_manager.js
function(class_path, default_namespace) { if (!(class_path in this.constructors) && default_namespace) { class_path = default_namespace + '.' + class_path; } return this.constructors[class_path]; }
javascript
function(class_path, default_namespace) { if (!(class_path in this.constructors) && default_namespace) { class_path = default_namespace + '.' + class_path; } return this.constructors[class_path]; }
[ "function", "(", "class_path", ",", "default_namespace", ")", "{", "if", "(", "!", "(", "class_path", "in", "this", ".", "constructors", ")", "&&", "default_namespace", ")", "{", "class_path", "=", "default_namespace", "+", "'.'", "+", "class_path", ";", "}", "return", "this", ".", "constructors", "[", "class_path", "]", ";", "}" ]
Get class constructor @param {string} class_path Full name of a class, or a short name (if namespace is provided) @param {string} [default_namespace] The default prefix where to search for the class, like <str>"Lava.widget"</str> @returns {function}
[ "Get", "class", "constructor" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L805-L815
train
kogarashisan/ClassManager
lib/class_manager.js
function(data) { var tempResult = [], i = 0, count = data.length, type, value; for (; i < count; i++) { type = Firestorm.getType(data[i]); switch (type) { case 'string': value = Firestorm.String.quote(data[i]); break; case 'null': case 'undefined': case 'boolean': case 'number': value = data[i] + ''; break; default: Lava.t(); } tempResult.push(value); } return '[' + tempResult.join(", ") + ']'; }
javascript
function(data) { var tempResult = [], i = 0, count = data.length, type, value; for (; i < count; i++) { type = Firestorm.getType(data[i]); switch (type) { case 'string': value = Firestorm.String.quote(data[i]); break; case 'null': case 'undefined': case 'boolean': case 'number': value = data[i] + ''; break; default: Lava.t(); } tempResult.push(value); } return '[' + tempResult.join(", ") + ']'; }
[ "function", "(", "data", ")", "{", "var", "tempResult", "=", "[", "]", ",", "i", "=", "0", ",", "count", "=", "data", ".", "length", ",", "type", ",", "value", ";", "for", "(", ";", "i", "<", "count", ";", "i", "++", ")", "{", "type", "=", "Firestorm", ".", "getType", "(", "data", "[", "i", "]", ")", ";", "switch", "(", "type", ")", "{", "case", "'string'", ":", "value", "=", "Firestorm", ".", "String", ".", "quote", "(", "data", "[", "i", "]", ")", ";", "break", ";", "case", "'null'", ":", "case", "'undefined'", ":", "case", "'boolean'", ":", "case", "'number'", ":", "value", "=", "data", "[", "i", "]", "+", "''", ";", "break", ";", "default", ":", "Lava", ".", "t", "(", ")", ";", "}", "tempResult", ".", "push", "(", "value", ")", ";", "}", "return", "'['", "+", "tempResult", ".", "join", "(", "\", \"", ")", "+", "']'", ";", "}" ]
Serialize an array which contains only certain primitive types from `SIMPLE_TYPES` property @param {Array} data @returns {string}
[ "Serialize", "an", "array", "which", "contains", "only", "certain", "primitive", "types", "from", "SIMPLE_TYPES", "property" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L847-L877
train
kogarashisan/ClassManager
lib/class_manager.js
function(class_data) { var skeleton = class_data.skeleton, name, serialized_value, serialized_actions = [], is_polymorphic = !class_data.is_monomorphic; for (name in skeleton) { switch (skeleton[name].type) { case this.MEMBER_TYPES.REGEXP: case this.MEMBER_TYPES.FUNCTION: serialized_value = 'r[' + skeleton[name].index + ']'; break; //case 'undefined': case this.MEMBER_TYPES.STRING: if (is_polymorphic) { serialized_value = '"' + skeleton[name].value.replace(/\"/g, "\\\"") + '"'; } break; case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number if (is_polymorphic) { serialized_value = skeleton[name].value + ''; } break; } if (serialized_value) { if (Lava.VALID_PROPERTY_NAME_REGEX.test(name)) { serialized_actions.push('p.' + name + ' = ' + serialized_value + ';'); } else { serialized_actions.push('p[' + Firestorm.String.quote(name) + '] = ' + serialized_value + ';'); } serialized_value = null; } } for (name in class_data.shared) { serialized_actions.push('p.' + name + ' = s.' + name + ';'); } return serialized_actions.length ? new Function('cd,p', "\tvar r=cd.references,\n\t\ts=cd.shared;\n\n\t" + serialized_actions.join('\n\t') + "\n") : null; }
javascript
function(class_data) { var skeleton = class_data.skeleton, name, serialized_value, serialized_actions = [], is_polymorphic = !class_data.is_monomorphic; for (name in skeleton) { switch (skeleton[name].type) { case this.MEMBER_TYPES.REGEXP: case this.MEMBER_TYPES.FUNCTION: serialized_value = 'r[' + skeleton[name].index + ']'; break; //case 'undefined': case this.MEMBER_TYPES.STRING: if (is_polymorphic) { serialized_value = '"' + skeleton[name].value.replace(/\"/g, "\\\"") + '"'; } break; case this.MEMBER_TYPES.PRIMITIVE: // null, boolean, number if (is_polymorphic) { serialized_value = skeleton[name].value + ''; } break; } if (serialized_value) { if (Lava.VALID_PROPERTY_NAME_REGEX.test(name)) { serialized_actions.push('p.' + name + ' = ' + serialized_value + ';'); } else { serialized_actions.push('p[' + Firestorm.String.quote(name) + '] = ' + serialized_value + ';'); } serialized_value = null; } } for (name in class_data.shared) { serialized_actions.push('p.' + name + ' = s.' + name + ';'); } return serialized_actions.length ? new Function('cd,p', "\tvar r=cd.references,\n\t\ts=cd.shared;\n\n\t" + serialized_actions.join('\n\t') + "\n") : null; }
[ "function", "(", "class_data", ")", "{", "var", "skeleton", "=", "class_data", ".", "skeleton", ",", "name", ",", "serialized_value", ",", "serialized_actions", "=", "[", "]", ",", "is_polymorphic", "=", "!", "class_data", ".", "is_monomorphic", ";", "for", "(", "name", "in", "skeleton", ")", "{", "switch", "(", "skeleton", "[", "name", "]", ".", "type", ")", "{", "case", "this", ".", "MEMBER_TYPES", ".", "REGEXP", ":", "case", "this", ".", "MEMBER_TYPES", ".", "FUNCTION", ":", "serialized_value", "=", "'r['", "+", "skeleton", "[", "name", "]", ".", "index", "+", "']'", ";", "break", ";", "case", "this", ".", "MEMBER_TYPES", ".", "STRING", ":", "if", "(", "is_polymorphic", ")", "{", "serialized_value", "=", "'\"'", "+", "skeleton", "[", "name", "]", ".", "value", ".", "replace", "(", "/", "\\\"", "/", "g", ",", "\"\\\\\\\"\"", ")", "+", "\\\\", ";", "}", "\\\"", "'\"'", "}", "break", ";", "}", "case", "this", ".", "MEMBER_TYPES", ".", "PRIMITIVE", ":", "if", "(", "is_polymorphic", ")", "{", "serialized_value", "=", "skeleton", "[", "name", "]", ".", "value", "+", "''", ";", "}", "break", ";", "if", "(", "serialized_value", ")", "{", "if", "(", "Lava", ".", "VALID_PROPERTY_NAME_REGEX", ".", "test", "(", "name", ")", ")", "{", "serialized_actions", ".", "push", "(", "'p.'", "+", "name", "+", "' = '", "+", "serialized_value", "+", "';'", ")", ";", "}", "else", "{", "serialized_actions", ".", "push", "(", "'p['", "+", "Firestorm", ".", "String", ".", "quote", "(", "name", ")", "+", "'] = '", "+", "serialized_value", "+", "';'", ")", ";", "}", "serialized_value", "=", "null", ";", "}", "}" ]
Build a function that creates class constructor's prototype. Used in export @param {_cClassData} class_data @returns {function}
[ "Build", "a", "function", "that", "creates", "class", "constructor", "s", "prototype", ".", "Used", "in", "export" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L918-L974
train
kogarashisan/ClassManager
lib/class_manager.js
function(class_datas) { for (var i = 0, count = class_datas.length; i <count; i++) { this.loadClass(class_datas[i]); } }
javascript
function(class_datas) { for (var i = 0, count = class_datas.length; i <count; i++) { this.loadClass(class_datas[i]); } }
[ "function", "(", "class_datas", ")", "{", "for", "(", "var", "i", "=", "0", ",", "count", "=", "class_datas", ".", "length", ";", "i", "<", "count", ";", "i", "++", ")", "{", "this", ".", "loadClass", "(", "class_datas", "[", "i", "]", ")", ";", "}", "}" ]
Batch load exported classes. Constructors, references and skeletons can be provided as separate arrays @param {Array.<_cClassData>} class_datas
[ "Batch", "load", "exported", "classes", ".", "Constructors", "references", "and", "skeletons", "can", "be", "provided", "as", "separate", "arrays" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L1122-L1130
train
kogarashisan/ClassManager
lib/class_manager.js
function(class_data) { var class_path = class_data.path, namespace_path, class_name, namespace; if ((class_path in this._sources) || (class_path in this.constructors)) Lava.t("Class is already defined: " + class_path); this._sources[class_path] = class_data; if (class_data.constructor) { namespace_path = class_path.split('.'); class_name = namespace_path.pop(); namespace = this._getNamespace(namespace_path); if ((class_name in namespace) && namespace[class_name] != null) Lava.t("Class name conflict: '" + class_path + "' property is already defined in namespace path"); this.constructors[class_path] = class_data.constructor; namespace[class_name] = class_data.constructor; } }
javascript
function(class_data) { var class_path = class_data.path, namespace_path, class_name, namespace; if ((class_path in this._sources) || (class_path in this.constructors)) Lava.t("Class is already defined: " + class_path); this._sources[class_path] = class_data; if (class_data.constructor) { namespace_path = class_path.split('.'); class_name = namespace_path.pop(); namespace = this._getNamespace(namespace_path); if ((class_name in namespace) && namespace[class_name] != null) Lava.t("Class name conflict: '" + class_path + "' property is already defined in namespace path"); this.constructors[class_path] = class_data.constructor; namespace[class_name] = class_data.constructor; } }
[ "function", "(", "class_data", ")", "{", "var", "class_path", "=", "class_data", ".", "path", ",", "namespace_path", ",", "class_name", ",", "namespace", ";", "if", "(", "(", "class_path", "in", "this", ".", "_sources", ")", "||", "(", "class_path", "in", "this", ".", "constructors", ")", ")", "Lava", ".", "t", "(", "\"Class is already defined: \"", "+", "class_path", ")", ";", "this", ".", "_sources", "[", "class_path", "]", "=", "class_data", ";", "if", "(", "class_data", ".", "constructor", ")", "{", "namespace_path", "=", "class_path", ".", "split", "(", "'.'", ")", ";", "class_name", "=", "namespace_path", ".", "pop", "(", ")", ";", "namespace", "=", "this", ".", "_getNamespace", "(", "namespace_path", ")", ";", "if", "(", "(", "class_name", "in", "namespace", ")", "&&", "namespace", "[", "class_name", "]", "!=", "null", ")", "Lava", ".", "t", "(", "\"Class name conflict: '\"", "+", "class_path", "+", "\"' property is already defined in namespace path\"", ")", ";", "this", ".", "constructors", "[", "class_path", "]", "=", "class_data", ".", "constructor", ";", "namespace", "[", "class_name", "]", "=", "class_data", ".", "constructor", ";", "}", "}" ]
Put a newly built class constructor into it's namespace @param {_cClassData} class_data
[ "Put", "a", "newly", "built", "class", "constructor", "into", "it", "s", "namespace" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L1148-L1171
train
kogarashisan/ClassManager
lib/class_manager.js
function(base_path, suffix) { if (Lava.schema.DEBUG && !(base_path in this._sources)) Lava.t("[getPackageConstructor] Class not found: " + base_path); var path, current_class = this._sources[base_path], result = null; do { path = current_class.path + suffix; if (path in this.constructors) { result = this.constructors[path]; break; } current_class = current_class.parent_class_data; } while (current_class); return result; }
javascript
function(base_path, suffix) { if (Lava.schema.DEBUG && !(base_path in this._sources)) Lava.t("[getPackageConstructor] Class not found: " + base_path); var path, current_class = this._sources[base_path], result = null; do { path = current_class.path + suffix; if (path in this.constructors) { result = this.constructors[path]; break; } current_class = current_class.parent_class_data; } while (current_class); return result; }
[ "function", "(", "base_path", ",", "suffix", ")", "{", "if", "(", "Lava", ".", "schema", ".", "DEBUG", "&&", "!", "(", "base_path", "in", "this", ".", "_sources", ")", ")", "Lava", ".", "t", "(", "\"[getPackageConstructor] Class not found: \"", "+", "base_path", ")", ";", "var", "path", ",", "current_class", "=", "this", ".", "_sources", "[", "base_path", "]", ",", "result", "=", "null", ";", "do", "{", "path", "=", "current_class", ".", "path", "+", "suffix", ";", "if", "(", "path", "in", "this", ".", "constructors", ")", "{", "result", "=", "this", ".", "constructors", "[", "path", "]", ";", "break", ";", "}", "current_class", "=", "current_class", ".", "parent_class_data", ";", "}", "while", "(", "current_class", ")", ";", "return", "result", ";", "}" ]
Find a class that begins with `base_path` or names of it's parents, and ends with `suffix` @param {string} base_path @param {string} suffix @returns {function}
[ "Find", "a", "class", "that", "begins", "with", "base_path", "or", "names", "of", "it", "s", "parents", "and", "ends", "with", "suffix" ]
75d6e0262b1bd74359e41c6c51bf8b174b38e8ca
https://github.com/kogarashisan/ClassManager/blob/75d6e0262b1bd74359e41c6c51bf8b174b38e8ca/lib/class_manager.js#L1179-L1203
train
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$ResolveLocale
function /* 9.2.5 */$$core$$ResolveLocale (availableLocales, requestedLocales, options, relevantExtensionKeys, localeData) { if (availableLocales.length === 0) { throw new ReferenceError('No locale data has been provided for this object yet.'); } // The following steps are taken: var // 1. Let matcher be the value of options.[[localeMatcher]]. matcher = options['[[localeMatcher]]']; // 2. If matcher is "lookup", then if (matcher === 'lookup') var // a. Let r be the result of calling the LookupMatcher abstract operation // (defined in 9.2.3) with arguments availableLocales and // requestedLocales. r = $$core$$LookupMatcher(availableLocales, requestedLocales); // 3. Else else var // a. Let r be the result of calling the BestFitMatcher abstract // operation (defined in 9.2.4) with arguments availableLocales and // requestedLocales. r = $$core$$BestFitMatcher(availableLocales, requestedLocales); var // 4. Let foundLocale be the value of r.[[locale]]. foundLocale = r['[[locale]]']; // 5. If r has an [[extension]] field, then if ($$core$$hop.call(r, '[[extension]]')) var // a. Let extension be the value of r.[[extension]]. extension = r['[[extension]]'], // b. Let extensionIndex be the value of r.[[extensionIndex]]. extensionIndex = r['[[extensionIndex]]'], // c. Let split be the standard built-in function object defined in ES5, // 15.5.4.14. split = String.prototype.split, // d. Let extensionSubtags be the result of calling the [[Call]] internal // method of split with extension as the this value and an argument // list containing the single item "-". extensionSubtags = split.call(extension, '-'), // e. Let extensionSubtagsLength be the result of calling the [[Get]] // internal method of extensionSubtags with argument "length". extensionSubtagsLength = extensionSubtags.length; var // 6. Let result be a new Record. result = new $$core$$Record(); // 7. Set result.[[dataLocale]] to foundLocale. result['[[dataLocale]]'] = foundLocale; var // 8. Let supportedExtension be "-u". supportedExtension = '-u', // 9. Let i be 0. i = 0, // 10. Let len be the result of calling the [[Get]] internal method of // relevantExtensionKeys with argument "length". len = relevantExtensionKeys.length; // 11 Repeat while i < len: while (i < len) { var // a. Let key be the result of calling the [[Get]] internal method of // relevantExtensionKeys with argument ToString(i). key = relevantExtensionKeys[i], // b. Let foundLocaleData be the result of calling the [[Get]] internal // method of localeData with the argument foundLocale. foundLocaleData = localeData[foundLocale], // c. Let keyLocaleData be the result of calling the [[Get]] internal // method of foundLocaleData with the argument key. keyLocaleData = foundLocaleData[key], // d. Let value be the result of calling the [[Get]] internal method of // keyLocaleData with argument "0". value = keyLocaleData['0'], // e. Let supportedExtensionAddition be "". supportedExtensionAddition = '', // f. Let indexOf be the standard built-in function object defined in // ES5, 15.4.4.14. indexOf = $$core$$arrIndexOf; // g. If extensionSubtags is not undefined, then if (extensionSubtags !== undefined) { var // i. Let keyPos be the result of calling the [[Call]] internal // method of indexOf with extensionSubtags as the this value and // an argument list containing the single item key. keyPos = indexOf.call(extensionSubtags, key); // ii. If keyPos ≠ -1, then if (keyPos !== -1) { // 1. If keyPos + 1 < extensionSubtagsLength and the length of the // result of calling the [[Get]] internal method of // extensionSubtags with argument ToString(keyPos +1) is greater // than 2, then if (keyPos + 1 < extensionSubtagsLength && extensionSubtags[keyPos + 1].length > 2) { var // a. Let requestedValue be the result of calling the [[Get]] // internal method of extensionSubtags with argument // ToString(keyPos + 1). requestedValue = extensionSubtags[keyPos + 1], // b. Let valuePos be the result of calling the [[Call]] // internal method of indexOf with keyLocaleData as the // this value and an argument list containing the single // item requestedValue. valuePos = indexOf.call(keyLocaleData, requestedValue); // c. If valuePos ≠ -1, then if (valuePos !== -1) var // i. Let value be requestedValue. value = requestedValue, // ii. Let supportedExtensionAddition be the // concatenation of "-", key, "-", and value. supportedExtensionAddition = '-' + key + '-' + value; } // 2. Else else { var // a. Let valuePos be the result of calling the [[Call]] // internal method of indexOf with keyLocaleData as the this // value and an argument list containing the single item // "true". valuePos = indexOf(keyLocaleData, 'true'); // b. If valuePos ≠ -1, then if (valuePos !== -1) var // i. Let value be "true". value = 'true'; } } } // h. If options has a field [[<key>]], then if ($$core$$hop.call(options, '[[' + key + ']]')) { var // i. Let optionsValue be the value of options.[[<key>]]. optionsValue = options['[[' + key + ']]']; // ii. If the result of calling the [[Call]] internal method of indexOf // with keyLocaleData as the this value and an argument list // containing the single item optionsValue is not -1, then if (indexOf.call(keyLocaleData, optionsValue) !== -1) { // 1. If optionsValue is not equal to value, then if (optionsValue !== value) { // a. Let value be optionsValue. value = optionsValue; // b. Let supportedExtensionAddition be "". supportedExtensionAddition = ''; } } } // i. Set result.[[<key>]] to value. result['[[' + key + ']]'] = value; // j. Append supportedExtensionAddition to supportedExtension. supportedExtension += supportedExtensionAddition; // k. Increase i by 1. i++; } // 12. If the length of supportedExtension is greater than 2, then if (supportedExtension.length > 2) { var // a. Let preExtension be the substring of foundLocale from position 0, // inclusive, to position extensionIndex, exclusive. preExtension = foundLocale.substring(0, extensionIndex), // b. Let postExtension be the substring of foundLocale from position // extensionIndex to the end of the string. postExtension = foundLocale.substring(extensionIndex), // c. Let foundLocale be the concatenation of preExtension, // supportedExtension, and postExtension. foundLocale = preExtension + supportedExtension + postExtension; } // 13. Set result.[[locale]] to foundLocale. result['[[locale]]'] = foundLocale; // 14. Return result. return result; }
javascript
function /* 9.2.5 */$$core$$ResolveLocale (availableLocales, requestedLocales, options, relevantExtensionKeys, localeData) { if (availableLocales.length === 0) { throw new ReferenceError('No locale data has been provided for this object yet.'); } // The following steps are taken: var // 1. Let matcher be the value of options.[[localeMatcher]]. matcher = options['[[localeMatcher]]']; // 2. If matcher is "lookup", then if (matcher === 'lookup') var // a. Let r be the result of calling the LookupMatcher abstract operation // (defined in 9.2.3) with arguments availableLocales and // requestedLocales. r = $$core$$LookupMatcher(availableLocales, requestedLocales); // 3. Else else var // a. Let r be the result of calling the BestFitMatcher abstract // operation (defined in 9.2.4) with arguments availableLocales and // requestedLocales. r = $$core$$BestFitMatcher(availableLocales, requestedLocales); var // 4. Let foundLocale be the value of r.[[locale]]. foundLocale = r['[[locale]]']; // 5. If r has an [[extension]] field, then if ($$core$$hop.call(r, '[[extension]]')) var // a. Let extension be the value of r.[[extension]]. extension = r['[[extension]]'], // b. Let extensionIndex be the value of r.[[extensionIndex]]. extensionIndex = r['[[extensionIndex]]'], // c. Let split be the standard built-in function object defined in ES5, // 15.5.4.14. split = String.prototype.split, // d. Let extensionSubtags be the result of calling the [[Call]] internal // method of split with extension as the this value and an argument // list containing the single item "-". extensionSubtags = split.call(extension, '-'), // e. Let extensionSubtagsLength be the result of calling the [[Get]] // internal method of extensionSubtags with argument "length". extensionSubtagsLength = extensionSubtags.length; var // 6. Let result be a new Record. result = new $$core$$Record(); // 7. Set result.[[dataLocale]] to foundLocale. result['[[dataLocale]]'] = foundLocale; var // 8. Let supportedExtension be "-u". supportedExtension = '-u', // 9. Let i be 0. i = 0, // 10. Let len be the result of calling the [[Get]] internal method of // relevantExtensionKeys with argument "length". len = relevantExtensionKeys.length; // 11 Repeat while i < len: while (i < len) { var // a. Let key be the result of calling the [[Get]] internal method of // relevantExtensionKeys with argument ToString(i). key = relevantExtensionKeys[i], // b. Let foundLocaleData be the result of calling the [[Get]] internal // method of localeData with the argument foundLocale. foundLocaleData = localeData[foundLocale], // c. Let keyLocaleData be the result of calling the [[Get]] internal // method of foundLocaleData with the argument key. keyLocaleData = foundLocaleData[key], // d. Let value be the result of calling the [[Get]] internal method of // keyLocaleData with argument "0". value = keyLocaleData['0'], // e. Let supportedExtensionAddition be "". supportedExtensionAddition = '', // f. Let indexOf be the standard built-in function object defined in // ES5, 15.4.4.14. indexOf = $$core$$arrIndexOf; // g. If extensionSubtags is not undefined, then if (extensionSubtags !== undefined) { var // i. Let keyPos be the result of calling the [[Call]] internal // method of indexOf with extensionSubtags as the this value and // an argument list containing the single item key. keyPos = indexOf.call(extensionSubtags, key); // ii. If keyPos ≠ -1, then if (keyPos !== -1) { // 1. If keyPos + 1 < extensionSubtagsLength and the length of the // result of calling the [[Get]] internal method of // extensionSubtags with argument ToString(keyPos +1) is greater // than 2, then if (keyPos + 1 < extensionSubtagsLength && extensionSubtags[keyPos + 1].length > 2) { var // a. Let requestedValue be the result of calling the [[Get]] // internal method of extensionSubtags with argument // ToString(keyPos + 1). requestedValue = extensionSubtags[keyPos + 1], // b. Let valuePos be the result of calling the [[Call]] // internal method of indexOf with keyLocaleData as the // this value and an argument list containing the single // item requestedValue. valuePos = indexOf.call(keyLocaleData, requestedValue); // c. If valuePos ≠ -1, then if (valuePos !== -1) var // i. Let value be requestedValue. value = requestedValue, // ii. Let supportedExtensionAddition be the // concatenation of "-", key, "-", and value. supportedExtensionAddition = '-' + key + '-' + value; } // 2. Else else { var // a. Let valuePos be the result of calling the [[Call]] // internal method of indexOf with keyLocaleData as the this // value and an argument list containing the single item // "true". valuePos = indexOf(keyLocaleData, 'true'); // b. If valuePos ≠ -1, then if (valuePos !== -1) var // i. Let value be "true". value = 'true'; } } } // h. If options has a field [[<key>]], then if ($$core$$hop.call(options, '[[' + key + ']]')) { var // i. Let optionsValue be the value of options.[[<key>]]. optionsValue = options['[[' + key + ']]']; // ii. If the result of calling the [[Call]] internal method of indexOf // with keyLocaleData as the this value and an argument list // containing the single item optionsValue is not -1, then if (indexOf.call(keyLocaleData, optionsValue) !== -1) { // 1. If optionsValue is not equal to value, then if (optionsValue !== value) { // a. Let value be optionsValue. value = optionsValue; // b. Let supportedExtensionAddition be "". supportedExtensionAddition = ''; } } } // i. Set result.[[<key>]] to value. result['[[' + key + ']]'] = value; // j. Append supportedExtensionAddition to supportedExtension. supportedExtension += supportedExtensionAddition; // k. Increase i by 1. i++; } // 12. If the length of supportedExtension is greater than 2, then if (supportedExtension.length > 2) { var // a. Let preExtension be the substring of foundLocale from position 0, // inclusive, to position extensionIndex, exclusive. preExtension = foundLocale.substring(0, extensionIndex), // b. Let postExtension be the substring of foundLocale from position // extensionIndex to the end of the string. postExtension = foundLocale.substring(extensionIndex), // c. Let foundLocale be the concatenation of preExtension, // supportedExtension, and postExtension. foundLocale = preExtension + supportedExtension + postExtension; } // 13. Set result.[[locale]] to foundLocale. result['[[locale]]'] = foundLocale; // 14. Return result. return result; }
[ "function", "$$core$$ResolveLocale", "(", "availableLocales", ",", "requestedLocales", ",", "options", ",", "relevantExtensionKeys", ",", "localeData", ")", "{", "if", "(", "availableLocales", ".", "length", "===", "0", ")", "{", "throw", "new", "ReferenceError", "(", "'No locale data has been provided for this object yet.'", ")", ";", "}", "var", "matcher", "=", "options", "[", "'[[localeMatcher]]'", "]", ";", "if", "(", "matcher", "===", "'lookup'", ")", "var", "r", "=", "$$core$$LookupMatcher", "(", "availableLocales", ",", "requestedLocales", ")", ";", "else", "var", "r", "=", "$$core$$BestFitMatcher", "(", "availableLocales", ",", "requestedLocales", ")", ";", "var", "foundLocale", "=", "r", "[", "'[[locale]]'", "]", ";", "if", "(", "$$core$$hop", ".", "call", "(", "r", ",", "'[[extension]]'", ")", ")", "var", "extension", "=", "r", "[", "'[[extension]]'", "]", ",", "extensionIndex", "=", "r", "[", "'[[extensionIndex]]'", "]", ",", "split", "=", "String", ".", "prototype", ".", "split", ",", "extensionSubtags", "=", "split", ".", "call", "(", "extension", ",", "'-'", ")", ",", "extensionSubtagsLength", "=", "extensionSubtags", ".", "length", ";", "var", "result", "=", "new", "$$core$$Record", "(", ")", ";", "result", "[", "'[[dataLocale]]'", "]", "=", "foundLocale", ";", "var", "supportedExtension", "=", "'-u'", ",", "i", "=", "0", ",", "len", "=", "relevantExtensionKeys", ".", "length", ";", "while", "(", "i", "<", "len", ")", "{", "var", "key", "=", "relevantExtensionKeys", "[", "i", "]", ",", "foundLocaleData", "=", "localeData", "[", "foundLocale", "]", ",", "keyLocaleData", "=", "foundLocaleData", "[", "key", "]", ",", "value", "=", "keyLocaleData", "[", "'0'", "]", ",", "supportedExtensionAddition", "=", "''", ",", "indexOf", "=", "$$core$$arrIndexOf", ";", "if", "(", "extensionSubtags", "!==", "undefined", ")", "{", "var", "keyPos", "=", "indexOf", ".", "call", "(", "extensionSubtags", ",", "key", ")", ";", "if", "(", "keyPos", "!==", "-", "1", ")", "{", "if", "(", "keyPos", "+", "1", "<", "extensionSubtagsLength", "&&", "extensionSubtags", "[", "keyPos", "+", "1", "]", ".", "length", ">", "2", ")", "{", "var", "requestedValue", "=", "extensionSubtags", "[", "keyPos", "+", "1", "]", ",", "valuePos", "=", "indexOf", ".", "call", "(", "keyLocaleData", ",", "requestedValue", ")", ";", "if", "(", "valuePos", "!==", "-", "1", ")", "var", "value", "=", "requestedValue", ",", "supportedExtensionAddition", "=", "'-'", "+", "key", "+", "'-'", "+", "value", ";", "}", "else", "{", "var", "valuePos", "=", "indexOf", "(", "keyLocaleData", ",", "'true'", ")", ";", "if", "(", "valuePos", "!==", "-", "1", ")", "var", "value", "=", "'true'", ";", "}", "}", "}", "if", "(", "$$core$$hop", ".", "call", "(", "options", ",", "'[['", "+", "key", "+", "']]'", ")", ")", "{", "var", "optionsValue", "=", "options", "[", "'[['", "+", "key", "+", "']]'", "]", ";", "if", "(", "indexOf", ".", "call", "(", "keyLocaleData", ",", "optionsValue", ")", "!==", "-", "1", ")", "{", "if", "(", "optionsValue", "!==", "value", ")", "{", "value", "=", "optionsValue", ";", "supportedExtensionAddition", "=", "''", ";", "}", "}", "}", "result", "[", "'[['", "+", "key", "+", "']]'", "]", "=", "value", ";", "supportedExtension", "+=", "supportedExtensionAddition", ";", "i", "++", ";", "}", "if", "(", "supportedExtension", ".", "length", ">", "2", ")", "{", "var", "preExtension", "=", "foundLocale", ".", "substring", "(", "0", ",", "extensionIndex", ")", ",", "postExtension", "=", "foundLocale", ".", "substring", "(", "extensionIndex", ")", ",", "foundLocale", "=", "preExtension", "+", "supportedExtension", "+", "postExtension", ";", "}", "result", "[", "'[[locale]]'", "]", "=", "foundLocale", ";", "return", "result", ";", "}" ]
The ResolveLocale abstract operation compares a BCP 47 language priority list requestedLocales against the locales in availableLocales and determines the best available language to meet the request. availableLocales and requestedLocales must be provided as List values, options as a Record.
[ "The", "ResolveLocale", "abstract", "operation", "compares", "a", "BCP", "47", "language", "priority", "list", "requestedLocales", "against", "the", "locales", "in", "availableLocales", "and", "determines", "the", "best", "available", "language", "to", "meet", "the", "request", ".", "availableLocales", "and", "requestedLocales", "must", "be", "provided", "as", "List", "values", "options", "as", "a", "Record", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L875-L1059
train
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$GetOption
function /*9.2.9 */$$core$$GetOption (options, property, type, values, fallback) { var // 1. Let value be the result of calling the [[Get]] internal method of // options with argument property. value = options[property]; // 2. If value is not undefined, then if (value !== undefined) { // a. Assert: type is "boolean" or "string". // b. If type is "boolean", then let value be ToBoolean(value). // c. If type is "string", then let value be ToString(value). value = type === 'boolean' ? Boolean(value) : (type === 'string' ? String(value) : value); // d. If values is not undefined, then if (values !== undefined) { // i. If values does not contain an element equal to value, then throw a // RangeError exception. if ($$core$$arrIndexOf.call(values, value) === -1) throw new RangeError("'" + value + "' is not an allowed value for `" + property +'`'); } // e. Return value. return value; } // Else return fallback. return fallback; }
javascript
function /*9.2.9 */$$core$$GetOption (options, property, type, values, fallback) { var // 1. Let value be the result of calling the [[Get]] internal method of // options with argument property. value = options[property]; // 2. If value is not undefined, then if (value !== undefined) { // a. Assert: type is "boolean" or "string". // b. If type is "boolean", then let value be ToBoolean(value). // c. If type is "string", then let value be ToString(value). value = type === 'boolean' ? Boolean(value) : (type === 'string' ? String(value) : value); // d. If values is not undefined, then if (values !== undefined) { // i. If values does not contain an element equal to value, then throw a // RangeError exception. if ($$core$$arrIndexOf.call(values, value) === -1) throw new RangeError("'" + value + "' is not an allowed value for `" + property +'`'); } // e. Return value. return value; } // Else return fallback. return fallback; }
[ "function", "$$core$$GetOption", "(", "options", ",", "property", ",", "type", ",", "values", ",", "fallback", ")", "{", "var", "value", "=", "options", "[", "property", "]", ";", "if", "(", "value", "!==", "undefined", ")", "{", "value", "=", "type", "===", "'boolean'", "?", "Boolean", "(", "value", ")", ":", "(", "type", "===", "'string'", "?", "String", "(", "value", ")", ":", "value", ")", ";", "if", "(", "values", "!==", "undefined", ")", "{", "if", "(", "$$core$$arrIndexOf", ".", "call", "(", "values", ",", "value", ")", "===", "-", "1", ")", "throw", "new", "RangeError", "(", "\"'\"", "+", "value", "+", "\"' is not an allowed value for `\"", "+", "property", "+", "'`'", ")", ";", "}", "return", "value", ";", "}", "return", "fallback", ";", "}" ]
The GetOption abstract operation extracts the value of the property named property from the provided options object, converts it to the required type, checks whether it is one of a List of allowed values, and fills in a fallback value if necessary.
[ "The", "GetOption", "abstract", "operation", "extracts", "the", "value", "of", "the", "property", "named", "property", "from", "the", "provided", "options", "object", "converts", "it", "to", "the", "required", "type", "checks", "whether", "it", "is", "one", "of", "a", "List", "of", "allowed", "values", "and", "fills", "in", "a", "fallback", "value", "if", "necessary", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L1193-L1220
train
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$GetNumberOption
function /* 9.2.10 */$$core$$GetNumberOption (options, property, minimum, maximum, fallback) { var // 1. Let value be the result of calling the [[Get]] internal method of // options with argument property. value = options[property]; // 2. If value is not undefined, then if (value !== undefined) { // a. Let value be ToNumber(value). value = Number(value); // b. If value is NaN or less than minimum or greater than maximum, throw a // RangeError exception. if (isNaN(value) || value < minimum || value > maximum) throw new RangeError('Value is not a number or outside accepted range'); // c. Return floor(value). return Math.floor(value); } // 3. Else return fallback. return fallback; }
javascript
function /* 9.2.10 */$$core$$GetNumberOption (options, property, minimum, maximum, fallback) { var // 1. Let value be the result of calling the [[Get]] internal method of // options with argument property. value = options[property]; // 2. If value is not undefined, then if (value !== undefined) { // a. Let value be ToNumber(value). value = Number(value); // b. If value is NaN or less than minimum or greater than maximum, throw a // RangeError exception. if (isNaN(value) || value < minimum || value > maximum) throw new RangeError('Value is not a number or outside accepted range'); // c. Return floor(value). return Math.floor(value); } // 3. Else return fallback. return fallback; }
[ "function", "$$core$$GetNumberOption", "(", "options", ",", "property", ",", "minimum", ",", "maximum", ",", "fallback", ")", "{", "var", "value", "=", "options", "[", "property", "]", ";", "if", "(", "value", "!==", "undefined", ")", "{", "value", "=", "Number", "(", "value", ")", ";", "if", "(", "isNaN", "(", "value", ")", "||", "value", "<", "minimum", "||", "value", ">", "maximum", ")", "throw", "new", "RangeError", "(", "'Value is not a number or outside accepted range'", ")", ";", "return", "Math", ".", "floor", "(", "value", ")", ";", "}", "return", "fallback", ";", "}" ]
The GetNumberOption abstract operation extracts a property value from the provided options object, converts it to a Number value, checks whether it is in the allowed range, and fills in a fallback value if necessary.
[ "The", "GetNumberOption", "abstract", "operation", "extracts", "a", "property", "value", "from", "the", "provided", "options", "object", "converts", "it", "to", "a", "Number", "value", "checks", "whether", "it", "is", "in", "the", "allowed", "range", "and", "fills", "in", "a", "fallback", "value", "if", "necessary", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L1227-L1248
train
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$calculateScore
function $$core$$calculateScore (options, formats, bestFit) { var // Additional penalty type when bestFit === true diffDataTypePenalty = 8, // 1. Let removalPenalty be 120. removalPenalty = 120, // 2. Let additionPenalty be 20. additionPenalty = 20, // 3. Let longLessPenalty be 8. longLessPenalty = 8, // 4. Let longMorePenalty be 6. longMorePenalty = 6, // 5. Let shortLessPenalty be 6. shortLessPenalty = 6, // 6. Let shortMorePenalty be 3. shortMorePenalty = 3, // 7. Let bestScore be -Infinity. bestScore = -Infinity, // 8. Let bestFormat be undefined. bestFormat, // 9. Let i be 0. i = 0, // 10. Let len be the result of calling the [[Get]] internal method of formats with argument "length". len = formats.length; // 11. Repeat while i < len: while (i < len) { var // a. Let format be the result of calling the [[Get]] internal method of formats with argument ToString(i). format = formats[i], // b. Let score be 0. score = 0; // c. For each property shown in Table 3: for (var property in $$core$$dateTimeComponents) { if (!$$core$$hop.call($$core$$dateTimeComponents, property)) continue; var // i. Let optionsProp be options.[[<property>]]. optionsProp = options['[['+ property +']]'], // ii. Let formatPropDesc be the result of calling the [[GetOwnProperty]] internal method of format // with argument property. // iii. If formatPropDesc is not undefined, then // 1. Let formatProp be the result of calling the [[Get]] internal method of format with argument property. formatProp = $$core$$hop.call(format, property) ? format[property] : undefined; // iv. If optionsProp is undefined and formatProp is not undefined, then decrease score by // additionPenalty. if (optionsProp === undefined && formatProp !== undefined) score -= additionPenalty; // v. Else if optionsProp is not undefined and formatProp is undefined, then decrease score by // removalPenalty. else if (optionsProp !== undefined && formatProp === undefined) score -= removalPenalty; // vi. Else else { var // 1. Let values be the array ["2-digit", "numeric", "narrow", "short", // "long"]. values = [ '2-digit', 'numeric', 'narrow', 'short', 'long' ], // 2. Let optionsPropIndex be the index of optionsProp within values. optionsPropIndex = $$core$$arrIndexOf.call(values, optionsProp), // 3. Let formatPropIndex be the index of formatProp within values. formatPropIndex = $$core$$arrIndexOf.call(values, formatProp), // 4. Let delta be max(min(formatPropIndex - optionsPropIndex, 2), -2). delta = Math.max(Math.min(formatPropIndex - optionsPropIndex, 2), -2); // When the bestFit argument is true, subtract additional penalty where data types are not the same if (bestFit && ( ((optionsProp === 'numeric' || optionsProp === '2-digit') && (formatProp !== 'numeric' && formatProp !== '2-digit') || (optionsProp !== 'numeric' && optionsProp !== '2-digit') && (formatProp === '2-digit' || formatProp === 'numeric')) )) score -= diffDataTypePenalty; // 5. If delta = 2, decrease score by longMorePenalty. if (delta === 2) score -= longMorePenalty; // 6. Else if delta = 1, decrease score by shortMorePenalty. else if (delta === 1) score -= shortMorePenalty; // 7. Else if delta = -1, decrease score by shortLessPenalty. else if (delta === -1) score -= shortLessPenalty; // 8. Else if delta = -2, decrease score by longLessPenalty. else if (delta === -2) score -= longLessPenalty; } } // d. If score > bestScore, then if (score > bestScore) { // i. Let bestScore be score. bestScore = score; // ii. Let bestFormat be format. bestFormat = format; } // e. Increase i by 1. i++; } // 12. Return bestFormat. return bestFormat; }
javascript
function $$core$$calculateScore (options, formats, bestFit) { var // Additional penalty type when bestFit === true diffDataTypePenalty = 8, // 1. Let removalPenalty be 120. removalPenalty = 120, // 2. Let additionPenalty be 20. additionPenalty = 20, // 3. Let longLessPenalty be 8. longLessPenalty = 8, // 4. Let longMorePenalty be 6. longMorePenalty = 6, // 5. Let shortLessPenalty be 6. shortLessPenalty = 6, // 6. Let shortMorePenalty be 3. shortMorePenalty = 3, // 7. Let bestScore be -Infinity. bestScore = -Infinity, // 8. Let bestFormat be undefined. bestFormat, // 9. Let i be 0. i = 0, // 10. Let len be the result of calling the [[Get]] internal method of formats with argument "length". len = formats.length; // 11. Repeat while i < len: while (i < len) { var // a. Let format be the result of calling the [[Get]] internal method of formats with argument ToString(i). format = formats[i], // b. Let score be 0. score = 0; // c. For each property shown in Table 3: for (var property in $$core$$dateTimeComponents) { if (!$$core$$hop.call($$core$$dateTimeComponents, property)) continue; var // i. Let optionsProp be options.[[<property>]]. optionsProp = options['[['+ property +']]'], // ii. Let formatPropDesc be the result of calling the [[GetOwnProperty]] internal method of format // with argument property. // iii. If formatPropDesc is not undefined, then // 1. Let formatProp be the result of calling the [[Get]] internal method of format with argument property. formatProp = $$core$$hop.call(format, property) ? format[property] : undefined; // iv. If optionsProp is undefined and formatProp is not undefined, then decrease score by // additionPenalty. if (optionsProp === undefined && formatProp !== undefined) score -= additionPenalty; // v. Else if optionsProp is not undefined and formatProp is undefined, then decrease score by // removalPenalty. else if (optionsProp !== undefined && formatProp === undefined) score -= removalPenalty; // vi. Else else { var // 1. Let values be the array ["2-digit", "numeric", "narrow", "short", // "long"]. values = [ '2-digit', 'numeric', 'narrow', 'short', 'long' ], // 2. Let optionsPropIndex be the index of optionsProp within values. optionsPropIndex = $$core$$arrIndexOf.call(values, optionsProp), // 3. Let formatPropIndex be the index of formatProp within values. formatPropIndex = $$core$$arrIndexOf.call(values, formatProp), // 4. Let delta be max(min(formatPropIndex - optionsPropIndex, 2), -2). delta = Math.max(Math.min(formatPropIndex - optionsPropIndex, 2), -2); // When the bestFit argument is true, subtract additional penalty where data types are not the same if (bestFit && ( ((optionsProp === 'numeric' || optionsProp === '2-digit') && (formatProp !== 'numeric' && formatProp !== '2-digit') || (optionsProp !== 'numeric' && optionsProp !== '2-digit') && (formatProp === '2-digit' || formatProp === 'numeric')) )) score -= diffDataTypePenalty; // 5. If delta = 2, decrease score by longMorePenalty. if (delta === 2) score -= longMorePenalty; // 6. Else if delta = 1, decrease score by shortMorePenalty. else if (delta === 1) score -= shortMorePenalty; // 7. Else if delta = -1, decrease score by shortLessPenalty. else if (delta === -1) score -= shortLessPenalty; // 8. Else if delta = -2, decrease score by longLessPenalty. else if (delta === -2) score -= longLessPenalty; } } // d. If score > bestScore, then if (score > bestScore) { // i. Let bestScore be score. bestScore = score; // ii. Let bestFormat be format. bestFormat = format; } // e. Increase i by 1. i++; } // 12. Return bestFormat. return bestFormat; }
[ "function", "$$core$$calculateScore", "(", "options", ",", "formats", ",", "bestFit", ")", "{", "var", "diffDataTypePenalty", "=", "8", ",", "removalPenalty", "=", "120", ",", "additionPenalty", "=", "20", ",", "longLessPenalty", "=", "8", ",", "longMorePenalty", "=", "6", ",", "shortLessPenalty", "=", "6", ",", "shortMorePenalty", "=", "3", ",", "bestScore", "=", "-", "Infinity", ",", "bestFormat", ",", "i", "=", "0", ",", "len", "=", "formats", ".", "length", ";", "while", "(", "i", "<", "len", ")", "{", "var", "format", "=", "formats", "[", "i", "]", ",", "score", "=", "0", ";", "for", "(", "var", "property", "in", "$$core$$dateTimeComponents", ")", "{", "if", "(", "!", "$$core$$hop", ".", "call", "(", "$$core$$dateTimeComponents", ",", "property", ")", ")", "continue", ";", "var", "optionsProp", "=", "options", "[", "'[['", "+", "property", "+", "']]'", "]", ",", "formatProp", "=", "$$core$$hop", ".", "call", "(", "format", ",", "property", ")", "?", "format", "[", "property", "]", ":", "undefined", ";", "if", "(", "optionsProp", "===", "undefined", "&&", "formatProp", "!==", "undefined", ")", "score", "-=", "additionPenalty", ";", "else", "if", "(", "optionsProp", "!==", "undefined", "&&", "formatProp", "===", "undefined", ")", "score", "-=", "removalPenalty", ";", "else", "{", "var", "values", "=", "[", "'2-digit'", ",", "'numeric'", ",", "'narrow'", ",", "'short'", ",", "'long'", "]", ",", "optionsPropIndex", "=", "$$core$$arrIndexOf", ".", "call", "(", "values", ",", "optionsProp", ")", ",", "formatPropIndex", "=", "$$core$$arrIndexOf", ".", "call", "(", "values", ",", "formatProp", ")", ",", "delta", "=", "Math", ".", "max", "(", "Math", ".", "min", "(", "formatPropIndex", "-", "optionsPropIndex", ",", "2", ")", ",", "-", "2", ")", ";", "if", "(", "bestFit", "&&", "(", "(", "(", "optionsProp", "===", "'numeric'", "||", "optionsProp", "===", "'2-digit'", ")", "&&", "(", "formatProp", "!==", "'numeric'", "&&", "formatProp", "!==", "'2-digit'", ")", "||", "(", "optionsProp", "!==", "'numeric'", "&&", "optionsProp", "!==", "'2-digit'", ")", "&&", "(", "formatProp", "===", "'2-digit'", "||", "formatProp", "===", "'numeric'", ")", ")", ")", ")", "score", "-=", "diffDataTypePenalty", ";", "if", "(", "delta", "===", "2", ")", "score", "-=", "longMorePenalty", ";", "else", "if", "(", "delta", "===", "1", ")", "score", "-=", "shortMorePenalty", ";", "else", "if", "(", "delta", "===", "-", "1", ")", "score", "-=", "shortLessPenalty", ";", "else", "if", "(", "delta", "===", "-", "2", ")", "score", "-=", "longLessPenalty", ";", "}", "}", "if", "(", "score", ">", "bestScore", ")", "{", "bestScore", "=", "score", ";", "bestFormat", "=", "format", ";", "}", "i", "++", ";", "}", "return", "bestFormat", ";", "}" ]
Calculates score for BestFitFormatMatcher and BasicFormatMatcher. Abstracted from BasicFormatMatcher section.
[ "Calculates", "score", "for", "BestFitFormatMatcher", "and", "BasicFormatMatcher", ".", "Abstracted", "from", "BasicFormatMatcher", "section", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L2389-L2513
train
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$resolveDateString
function $$core$$resolveDateString(data, ca, component, width, key) { // From http://www.unicode.org/reports/tr35/tr35.html#Multiple_Inheritance: // 'In clearly specified instances, resources may inherit from within the same locale. // For example, ... the Buddhist calendar inherits from the Gregorian calendar.' var obj = data[ca] && data[ca][component] ? data[ca][component] : data.gregory[component], // "sideways" inheritance resolves strings when a key doesn't exist alts = { narrow: ['short', 'long'], short: ['long', 'narrow'], long: ['short', 'narrow'] }, // resolved = $$core$$hop.call(obj, width) ? obj[width] : $$core$$hop.call(obj, alts[width][0]) ? obj[alts[width][0]] : obj[alts[width][1]]; // `key` wouldn't be specified for components 'dayPeriods' return key != null ? resolved[key] : resolved; }
javascript
function $$core$$resolveDateString(data, ca, component, width, key) { // From http://www.unicode.org/reports/tr35/tr35.html#Multiple_Inheritance: // 'In clearly specified instances, resources may inherit from within the same locale. // For example, ... the Buddhist calendar inherits from the Gregorian calendar.' var obj = data[ca] && data[ca][component] ? data[ca][component] : data.gregory[component], // "sideways" inheritance resolves strings when a key doesn't exist alts = { narrow: ['short', 'long'], short: ['long', 'narrow'], long: ['short', 'narrow'] }, // resolved = $$core$$hop.call(obj, width) ? obj[width] : $$core$$hop.call(obj, alts[width][0]) ? obj[alts[width][0]] : obj[alts[width][1]]; // `key` wouldn't be specified for components 'dayPeriods' return key != null ? resolved[key] : resolved; }
[ "function", "$$core$$resolveDateString", "(", "data", ",", "ca", ",", "component", ",", "width", ",", "key", ")", "{", "var", "obj", "=", "data", "[", "ca", "]", "&&", "data", "[", "ca", "]", "[", "component", "]", "?", "data", "[", "ca", "]", "[", "component", "]", ":", "data", ".", "gregory", "[", "component", "]", ",", "alts", "=", "{", "narrow", ":", "[", "'short'", ",", "'long'", "]", ",", "short", ":", "[", "'long'", ",", "'narrow'", "]", ",", "long", ":", "[", "'short'", ",", "'narrow'", "]", "}", ",", "resolved", "=", "$$core$$hop", ".", "call", "(", "obj", ",", "width", ")", "?", "obj", "[", "width", "]", ":", "$$core$$hop", ".", "call", "(", "obj", ",", "alts", "[", "width", "]", "[", "0", "]", ")", "?", "obj", "[", "alts", "[", "width", "]", "[", "0", "]", "]", ":", "obj", "[", "alts", "[", "width", "]", "[", "1", "]", "]", ";", "return", "key", "!=", "null", "?", "resolved", "[", "key", "]", ":", "resolved", ";", "}" ]
Returns a string for a date component, resolved using multiple inheritance as specified as specified in the Unicode Technical Standard 35.
[ "Returns", "a", "string", "for", "a", "date", "component", "resolved", "using", "multiple", "inheritance", "as", "specified", "as", "specified", "in", "the", "Unicode", "Technical", "Standard", "35", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L3113-L3137
train
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$createRegExpRestore
function $$core$$createRegExpRestore () { var esc = /[.?*+^$[\]\\(){}|-]/g, lm = RegExp.lastMatch || '', ml = RegExp.multiline ? 'm' : '', ret = { input: RegExp.input }, reg = new $$core$$List(), has = false, cap = {}; // Create a snapshot of all the 'captured' properties for (var i = 1; i <= 9; i++) has = (cap['$'+i] = RegExp['$'+i]) || has; // Now we've snapshotted some properties, escape the lastMatch string lm = lm.replace(esc, '\\$&'); // If any of the captured strings were non-empty, iterate over them all if (has) { for (var i = 1; i <= 9; i++) { var m = cap['$'+i]; // If it's empty, add an empty capturing group if (!m) lm = '()' + lm; // Else find the string in lm and escape & wrap it to capture it else { m = m.replace(esc, '\\$&'); lm = lm.replace(m, '(' + m + ')'); } // Push it to the reg and chop lm to make sure further groups come after $$core$$arrPush.call(reg, lm.slice(0, lm.indexOf('(') + 1)); lm = lm.slice(lm.indexOf('(') + 1); } } // Create the regular expression that will reconstruct the RegExp properties ret.exp = new RegExp($$core$$arrJoin.call(reg, '') + lm, ml); return ret; }
javascript
function $$core$$createRegExpRestore () { var esc = /[.?*+^$[\]\\(){}|-]/g, lm = RegExp.lastMatch || '', ml = RegExp.multiline ? 'm' : '', ret = { input: RegExp.input }, reg = new $$core$$List(), has = false, cap = {}; // Create a snapshot of all the 'captured' properties for (var i = 1; i <= 9; i++) has = (cap['$'+i] = RegExp['$'+i]) || has; // Now we've snapshotted some properties, escape the lastMatch string lm = lm.replace(esc, '\\$&'); // If any of the captured strings were non-empty, iterate over them all if (has) { for (var i = 1; i <= 9; i++) { var m = cap['$'+i]; // If it's empty, add an empty capturing group if (!m) lm = '()' + lm; // Else find the string in lm and escape & wrap it to capture it else { m = m.replace(esc, '\\$&'); lm = lm.replace(m, '(' + m + ')'); } // Push it to the reg and chop lm to make sure further groups come after $$core$$arrPush.call(reg, lm.slice(0, lm.indexOf('(') + 1)); lm = lm.slice(lm.indexOf('(') + 1); } } // Create the regular expression that will reconstruct the RegExp properties ret.exp = new RegExp($$core$$arrJoin.call(reg, '') + lm, ml); return ret; }
[ "function", "$$core$$createRegExpRestore", "(", ")", "{", "var", "esc", "=", "/", "[.?*+^$[\\]\\\\(){}|-]", "/", "g", ",", "lm", "=", "RegExp", ".", "lastMatch", "||", "''", ",", "ml", "=", "RegExp", ".", "multiline", "?", "'m'", ":", "''", ",", "ret", "=", "{", "input", ":", "RegExp", ".", "input", "}", ",", "reg", "=", "new", "$$core$$List", "(", ")", ",", "has", "=", "false", ",", "cap", "=", "{", "}", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "9", ";", "i", "++", ")", "has", "=", "(", "cap", "[", "'$'", "+", "i", "]", "=", "RegExp", "[", "'$'", "+", "i", "]", ")", "||", "has", ";", "lm", "=", "lm", ".", "replace", "(", "esc", ",", "'\\\\$&'", ")", ";", "\\\\", "if", "(", "has", ")", "{", "for", "(", "var", "i", "=", "1", ";", "i", "<=", "9", ";", "i", "++", ")", "{", "var", "m", "=", "cap", "[", "'$'", "+", "i", "]", ";", "if", "(", "!", "m", ")", "lm", "=", "'()'", "+", "lm", ";", "else", "{", "m", "=", "m", ".", "replace", "(", "esc", ",", "'\\\\$&'", ")", ";", "\\\\", "}", "lm", "=", "lm", ".", "replace", "(", "m", ",", "'('", "+", "m", "+", "')'", ")", ";", "$$core$$arrPush", ".", "call", "(", "reg", ",", "lm", ".", "slice", "(", "0", ",", "lm", ".", "indexOf", "(", "'('", ")", "+", "1", ")", ")", ";", "}", "}", "lm", "=", "lm", ".", "slice", "(", "lm", ".", "indexOf", "(", "'('", ")", "+", "1", ")", ";", "}" ]
Constructs a regular expression to restore tainted RegExp properties
[ "Constructs", "a", "regular", "expression", "to", "restore", "tainted", "RegExp", "properties" ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L3165-L3206
train
mozilla/webmaker-core
src/static/js/Intl.js
$$core$$toLatinUpperCase
function $$core$$toLatinUpperCase (str) { var i = str.length; while (i--) { var ch = str.charAt(i); if (ch >= "a" && ch <= "z") str = str.slice(0, i) + ch.toUpperCase() + str.slice(i+1); } return str; }
javascript
function $$core$$toLatinUpperCase (str) { var i = str.length; while (i--) { var ch = str.charAt(i); if (ch >= "a" && ch <= "z") str = str.slice(0, i) + ch.toUpperCase() + str.slice(i+1); } return str; }
[ "function", "$$core$$toLatinUpperCase", "(", "str", ")", "{", "var", "i", "=", "str", ".", "length", ";", "while", "(", "i", "--", ")", "{", "var", "ch", "=", "str", ".", "charAt", "(", "i", ")", ";", "if", "(", "ch", ">=", "\"a\"", "&&", "ch", "<=", "\"z\"", ")", "str", "=", "str", ".", "slice", "(", "0", ",", "i", ")", "+", "ch", ".", "toUpperCase", "(", ")", "+", "str", ".", "slice", "(", "i", "+", "1", ")", ";", "}", "return", "str", ";", "}" ]
Convert only a-z to uppercase as per section 6.1 of the spec
[ "Convert", "only", "a", "-", "z", "to", "uppercase", "as", "per", "section", "6", ".", "1", "of", "the", "spec" ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/static/js/Intl.js#L3211-L3222
train
DeanCording/node-red-contrib-persist
persist.js
PersistInNode
function PersistInNode(n) { RED.nodes.createNode(this,n); var node = this; node.name = n.name; node.storageNode = RED.nodes.getNode(n.storageNode); node.on("input", function(msg) { node.storageNode.store(node.name, msg); }); }
javascript
function PersistInNode(n) { RED.nodes.createNode(this,n); var node = this; node.name = n.name; node.storageNode = RED.nodes.getNode(n.storageNode); node.on("input", function(msg) { node.storageNode.store(node.name, msg); }); }
[ "function", "PersistInNode", "(", "n", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "n", ")", ";", "var", "node", "=", "this", ";", "node", ".", "name", "=", "n", ".", "name", ";", "node", ".", "storageNode", "=", "RED", ".", "nodes", ".", "getNode", "(", "n", ".", "storageNode", ")", ";", "node", ".", "on", "(", "\"input\"", ",", "function", "(", "msg", ")", "{", "node", ".", "storageNode", ".", "store", "(", "node", ".", "name", ",", "msg", ")", ";", "}", ")", ";", "}" ]
Record data to persist
[ "Record", "data", "to", "persist" ]
8c6a70ffcc13b71ea6f533f1e475223d373c0d8d
https://github.com/DeanCording/node-red-contrib-persist/blob/8c6a70ffcc13b71ea6f533f1e475223d373c0d8d/persist.js#L137-L147
train
DeanCording/node-red-contrib-persist
persist.js
PersistOutNode
function PersistOutNode(n) { RED.nodes.createNode(this,n); var node = this; node.name = n.name; node.storageNode = RED.nodes.getNode(n.storageNode); node.restore = function() { var msg = node.storageNode.getMessage(node.name); node.send(msg); }; RED.events.on("nodes-started", node.restore); node.on("input", function(msg) { node.restore(); }); node.on('close', function(removed, done) { RED.events.removeListener("nodes-started", node.restore); done(); }); }
javascript
function PersistOutNode(n) { RED.nodes.createNode(this,n); var node = this; node.name = n.name; node.storageNode = RED.nodes.getNode(n.storageNode); node.restore = function() { var msg = node.storageNode.getMessage(node.name); node.send(msg); }; RED.events.on("nodes-started", node.restore); node.on("input", function(msg) { node.restore(); }); node.on('close', function(removed, done) { RED.events.removeListener("nodes-started", node.restore); done(); }); }
[ "function", "PersistOutNode", "(", "n", ")", "{", "RED", ".", "nodes", ".", "createNode", "(", "this", ",", "n", ")", ";", "var", "node", "=", "this", ";", "node", ".", "name", "=", "n", ".", "name", ";", "node", ".", "storageNode", "=", "RED", ".", "nodes", ".", "getNode", "(", "n", ".", "storageNode", ")", ";", "node", ".", "restore", "=", "function", "(", ")", "{", "var", "msg", "=", "node", ".", "storageNode", ".", "getMessage", "(", "node", ".", "name", ")", ";", "node", ".", "send", "(", "msg", ")", ";", "}", ";", "RED", ".", "events", ".", "on", "(", "\"nodes-started\"", ",", "node", ".", "restore", ")", ";", "node", ".", "on", "(", "\"input\"", ",", "function", "(", "msg", ")", "{", "node", ".", "restore", "(", ")", ";", "}", ")", ";", "node", ".", "on", "(", "'close'", ",", "function", "(", "removed", ",", "done", ")", "{", "RED", ".", "events", ".", "removeListener", "(", "\"nodes-started\"", ",", "node", ".", "restore", ")", ";", "done", "(", ")", ";", "}", ")", ";", "}" ]
Replay persisted data
[ "Replay", "persisted", "data" ]
8c6a70ffcc13b71ea6f533f1e475223d373c0d8d
https://github.com/DeanCording/node-red-contrib-persist/blob/8c6a70ffcc13b71ea6f533f1e475223d373c0d8d/persist.js#L151-L174
train
johnstonbl01/eslint-no-inferred-method-name
lib/rules/no-inferred-method-name.js
isMethodCall
function isMethodCall(node) { var nodeParentType = node.parent.type, nodeParentParentParentType = node.parent.parent.parent.type; if (nodeParentType === "CallExpression" && nodeParentParentParentType === "BlockStatement" && !variable) { return true; } else { return false; } }
javascript
function isMethodCall(node) { var nodeParentType = node.parent.type, nodeParentParentParentType = node.parent.parent.parent.type; if (nodeParentType === "CallExpression" && nodeParentParentParentType === "BlockStatement" && !variable) { return true; } else { return false; } }
[ "function", "isMethodCall", "(", "node", ")", "{", "var", "nodeParentType", "=", "node", ".", "parent", ".", "type", ",", "nodeParentParentParentType", "=", "node", ".", "parent", ".", "parent", ".", "parent", ".", "type", ";", "if", "(", "nodeParentType", "===", "\"CallExpression\"", "&&", "nodeParentParentParentType", "===", "\"BlockStatement\"", "&&", "!", "variable", ")", "{", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Checks for object literal method @param {ASTNode} node The AST node being checked. @returns true if parent node is a call expression and is part of an object literal
[ "Checks", "for", "object", "literal", "method" ]
427bca541b204e68a284070f51c6382c544dd200
https://github.com/johnstonbl01/eslint-no-inferred-method-name/blob/427bca541b204e68a284070f51c6382c544dd200/lib/rules/no-inferred-method-name.js#L77-L86
train
nullobject/bulb
packages/bulb/src/Signal.js
broadcast
function broadcast (subscriptions, type) { return value => { subscriptions.forEach(s => { if (typeof s.emit[type] === 'function') { s.emit[type](value) } }) } }
javascript
function broadcast (subscriptions, type) { return value => { subscriptions.forEach(s => { if (typeof s.emit[type] === 'function') { s.emit[type](value) } }) } }
[ "function", "broadcast", "(", "subscriptions", ",", "type", ")", "{", "return", "value", "=>", "{", "subscriptions", ".", "forEach", "(", "s", "=>", "{", "if", "(", "typeof", "s", ".", "emit", "[", "type", "]", "===", "'function'", ")", "{", "s", ".", "emit", "[", "type", "]", "(", "value", ")", "}", "}", ")", "}", "}" ]
Creates a callback function that emits values to a list of subscribers. @private @param {Array} subscriptions An array of subscriptions. @param {String} type The type of callback to create. @returns {Function} A function that emits a value to all of the subscriptions.
[ "Creates", "a", "callback", "function", "that", "emits", "values", "to", "a", "list", "of", "subscribers", "." ]
bf0768e42d972ebca51438e74927b0cac8dfbd8e
https://github.com/nullobject/bulb/blob/bf0768e42d972ebca51438e74927b0cac8dfbd8e/packages/bulb/src/Signal.js#L47-L55
train
datavis-tech/reactive-model
index.js
function (){ var outputPropertyName, callback, inputPropertyNames, inputs, output; if(arguments.length === 0){ return configurationProperty(); } else if(arguments.length === 1){ if(typeof arguments[0] === "object"){ // The invocation is of the form model(configuration) return setConfiguration(arguments[0]); } else { // The invocation is of the form model(propertyName) return addProperty(arguments[0]); } } else if(arguments.length === 2){ if(typeof arguments[0] === "function"){ // The invocation is of the form model(callback, inputPropertyNames) inputPropertyNames = arguments[1]; callback = arguments[0]; outputPropertyName = undefined; } else { // The invocation is of the form model(propertyName, defaultValue) return addProperty(arguments[0], arguments[1]); } } else if(arguments.length === 3){ outputPropertyName = arguments[0]; callback = arguments[1]; inputPropertyNames = arguments[2]; } // inputPropertyNames may be a string of comma-separated property names, // or an array of property names. if(typeof inputPropertyNames === "string"){ inputPropertyNames = inputPropertyNames.split(",").map(invoke("trim")); } inputs = inputPropertyNames.map(function (propertyName){ var property = getProperty(propertyName); if(typeof property === "undefined"){ throw new Error([ "The property \"", propertyName, "\" was referenced as a dependency for a reactive function before it was defined. ", "Please define each property first before referencing them in reactive functions." ].join("")); } return property; }); // Create a new reactive property for the output and assign it to the model. if(outputPropertyName){ addProperty(outputPropertyName); output = model[outputPropertyName]; } // If the number of arguments expected by the callback is one greater than the // number of inputs, then the last argument is the "done" callback, and this // reactive function will be set up to be asynchronous. The "done" callback should // be called with the new value of the output property asynchronously. var isAsynchronous = (callback.length === inputs.length + 1); if(isAsynchronous){ reactiveFunctions.push(ReactiveFunction({ inputs: inputs, callback: function (){ // Convert the arguments passed into this function into an array. var args = Array.prototype.slice.call(arguments); // Push the "done" callback onto the args array. // We are actally passing the output reactive property here, invoking it // as the "done" callback will set the value of the output property. args.push(output); // Wrap in setTimeout to guarantee that the output property is set // asynchronously, outside of the current digest. This is necessary // to ensure that if developers inadvertently invoke the "done" callback // synchronously, their code will still have the expected behavior. setTimeout(function (){ // Invoke the original callback with the args array as arguments. callback.apply(null, args); }); } })); } else { reactiveFunctions.push(ReactiveFunction({ inputs: inputs, output: output, // This may be undefined. callback: callback })); } return model; }
javascript
function (){ var outputPropertyName, callback, inputPropertyNames, inputs, output; if(arguments.length === 0){ return configurationProperty(); } else if(arguments.length === 1){ if(typeof arguments[0] === "object"){ // The invocation is of the form model(configuration) return setConfiguration(arguments[0]); } else { // The invocation is of the form model(propertyName) return addProperty(arguments[0]); } } else if(arguments.length === 2){ if(typeof arguments[0] === "function"){ // The invocation is of the form model(callback, inputPropertyNames) inputPropertyNames = arguments[1]; callback = arguments[0]; outputPropertyName = undefined; } else { // The invocation is of the form model(propertyName, defaultValue) return addProperty(arguments[0], arguments[1]); } } else if(arguments.length === 3){ outputPropertyName = arguments[0]; callback = arguments[1]; inputPropertyNames = arguments[2]; } // inputPropertyNames may be a string of comma-separated property names, // or an array of property names. if(typeof inputPropertyNames === "string"){ inputPropertyNames = inputPropertyNames.split(",").map(invoke("trim")); } inputs = inputPropertyNames.map(function (propertyName){ var property = getProperty(propertyName); if(typeof property === "undefined"){ throw new Error([ "The property \"", propertyName, "\" was referenced as a dependency for a reactive function before it was defined. ", "Please define each property first before referencing them in reactive functions." ].join("")); } return property; }); // Create a new reactive property for the output and assign it to the model. if(outputPropertyName){ addProperty(outputPropertyName); output = model[outputPropertyName]; } // If the number of arguments expected by the callback is one greater than the // number of inputs, then the last argument is the "done" callback, and this // reactive function will be set up to be asynchronous. The "done" callback should // be called with the new value of the output property asynchronously. var isAsynchronous = (callback.length === inputs.length + 1); if(isAsynchronous){ reactiveFunctions.push(ReactiveFunction({ inputs: inputs, callback: function (){ // Convert the arguments passed into this function into an array. var args = Array.prototype.slice.call(arguments); // Push the "done" callback onto the args array. // We are actally passing the output reactive property here, invoking it // as the "done" callback will set the value of the output property. args.push(output); // Wrap in setTimeout to guarantee that the output property is set // asynchronously, outside of the current digest. This is necessary // to ensure that if developers inadvertently invoke the "done" callback // synchronously, their code will still have the expected behavior. setTimeout(function (){ // Invoke the original callback with the args array as arguments. callback.apply(null, args); }); } })); } else { reactiveFunctions.push(ReactiveFunction({ inputs: inputs, output: output, // This may be undefined. callback: callback })); } return model; }
[ "function", "(", ")", "{", "var", "outputPropertyName", ",", "callback", ",", "inputPropertyNames", ",", "inputs", ",", "output", ";", "if", "(", "arguments", ".", "length", "===", "0", ")", "{", "return", "configurationProperty", "(", ")", ";", "}", "else", "if", "(", "arguments", ".", "length", "===", "1", ")", "{", "if", "(", "typeof", "arguments", "[", "0", "]", "===", "\"object\"", ")", "{", "return", "setConfiguration", "(", "arguments", "[", "0", "]", ")", ";", "}", "else", "{", "return", "addProperty", "(", "arguments", "[", "0", "]", ")", ";", "}", "}", "else", "if", "(", "arguments", ".", "length", "===", "2", ")", "{", "if", "(", "typeof", "arguments", "[", "0", "]", "===", "\"function\"", ")", "{", "inputPropertyNames", "=", "arguments", "[", "1", "]", ";", "callback", "=", "arguments", "[", "0", "]", ";", "outputPropertyName", "=", "undefined", ";", "}", "else", "{", "return", "addProperty", "(", "arguments", "[", "0", "]", ",", "arguments", "[", "1", "]", ")", ";", "}", "}", "else", "if", "(", "arguments", ".", "length", "===", "3", ")", "{", "outputPropertyName", "=", "arguments", "[", "0", "]", ";", "callback", "=", "arguments", "[", "1", "]", ";", "inputPropertyNames", "=", "arguments", "[", "2", "]", ";", "}", "if", "(", "typeof", "inputPropertyNames", "===", "\"string\"", ")", "{", "inputPropertyNames", "=", "inputPropertyNames", ".", "split", "(", "\",\"", ")", ".", "map", "(", "invoke", "(", "\"trim\"", ")", ")", ";", "}", "inputs", "=", "inputPropertyNames", ".", "map", "(", "function", "(", "propertyName", ")", "{", "var", "property", "=", "getProperty", "(", "propertyName", ")", ";", "if", "(", "typeof", "property", "===", "\"undefined\"", ")", "{", "throw", "new", "Error", "(", "[", "\"The property \\\"\"", ",", "\\\"", ",", "propertyName", ",", "\"\\\" was referenced as a dependency for a reactive function before it was defined. \"", "]", ".", "\\\"", "\"Please define each property first before referencing them in reactive functions.\"", ")", ";", "}", "join", "}", ")", ";", "(", "\"\"", ")", "return", "property", ";", "if", "(", "outputPropertyName", ")", "{", "addProperty", "(", "outputPropertyName", ")", ";", "output", "=", "model", "[", "outputPropertyName", "]", ";", "}", "var", "isAsynchronous", "=", "(", "callback", ".", "length", "===", "inputs", ".", "length", "+", "1", ")", ";", "}" ]
The model instance object. This is the value returned from the constructor.
[ "The", "model", "instance", "object", ".", "This", "is", "the", "value", "returned", "from", "the", "constructor", "." ]
c64c13c37216baa39cb7aafee5787a5a0a15e659
https://github.com/datavis-tech/reactive-model/blob/c64c13c37216baa39cb7aafee5787a5a0a15e659/index.js#L46-L146
train
datavis-tech/reactive-model
index.js
addProperty
function addProperty(propertyName, defaultValue){ if(model[propertyName]){ throw new Error("The property \"" + propertyName + "\" is already defined."); } var property = ReactiveProperty(defaultValue); property.propertyName = propertyName; model[propertyName] = property; lastPropertyAdded = propertyName; return model; }
javascript
function addProperty(propertyName, defaultValue){ if(model[propertyName]){ throw new Error("The property \"" + propertyName + "\" is already defined."); } var property = ReactiveProperty(defaultValue); property.propertyName = propertyName; model[propertyName] = property; lastPropertyAdded = propertyName; return model; }
[ "function", "addProperty", "(", "propertyName", ",", "defaultValue", ")", "{", "if", "(", "model", "[", "propertyName", "]", ")", "{", "throw", "new", "Error", "(", "\"The property \\\"\"", "+", "\\\"", "+", "propertyName", ")", ";", "}", "\"\\\" is already defined.\"", "\\\"", "var", "property", "=", "ReactiveProperty", "(", "defaultValue", ")", ";", "property", ".", "propertyName", "=", "propertyName", ";", "model", "[", "propertyName", "]", "=", "property", ";", "}" ]
Adds a property to the model that is not exposed, meaning that it is not included in the configuration object.
[ "Adds", "a", "property", "to", "the", "model", "that", "is", "not", "exposed", "meaning", "that", "it", "is", "not", "included", "in", "the", "configuration", "object", "." ]
c64c13c37216baa39cb7aafee5787a5a0a15e659
https://github.com/datavis-tech/reactive-model/blob/c64c13c37216baa39cb7aafee5787a5a0a15e659/index.js#L156-L167
train
datavis-tech/reactive-model
index.js
expose
function expose(){ // TODO test this // if(!isDefined(defaultValue)){ // throw new Error("model.addPublicProperty() is being " + // "invoked with an undefined default value. Default values for exposed properties " + // "must be defined, to guarantee predictable behavior. For exposed properties that " + // "are optional and should have the semantics of an undefined value, " + // "use null as the default value."); //} // TODO test this if(!lastPropertyAdded){ throw Error("Expose() was called without first adding a property."); } var propertyName = lastPropertyAdded; if(!exposedProperties){ exposedProperties = []; } exposedProperties.push(propertyName); // Destroy the previous reactive function that was listening for changes // in all exposed properties except the newly added one. // TODO think about how this might be done only once, at the same time isFinalized is set. if(configurationReactiveFunction){ configurationReactiveFunction.destroy(); } // Set up the new reactive function that will listen for changes // in all exposed properties including the newly added one. var inputPropertyNames = exposedProperties; //console.log(inputPropertyNames); configurationReactiveFunction = ReactiveFunction({ inputs: inputPropertyNames.map(getProperty), output: configurationProperty, callback: function (){ var configuration = {}; inputPropertyNames.forEach(function (propertyName){ var property = getProperty(propertyName); // Omit default values from the returned configuration object. if(property() !== property.default()){ configuration[propertyName] = property(); } }); return configuration; } }); // Support method chaining. return model; }
javascript
function expose(){ // TODO test this // if(!isDefined(defaultValue)){ // throw new Error("model.addPublicProperty() is being " + // "invoked with an undefined default value. Default values for exposed properties " + // "must be defined, to guarantee predictable behavior. For exposed properties that " + // "are optional and should have the semantics of an undefined value, " + // "use null as the default value."); //} // TODO test this if(!lastPropertyAdded){ throw Error("Expose() was called without first adding a property."); } var propertyName = lastPropertyAdded; if(!exposedProperties){ exposedProperties = []; } exposedProperties.push(propertyName); // Destroy the previous reactive function that was listening for changes // in all exposed properties except the newly added one. // TODO think about how this might be done only once, at the same time isFinalized is set. if(configurationReactiveFunction){ configurationReactiveFunction.destroy(); } // Set up the new reactive function that will listen for changes // in all exposed properties including the newly added one. var inputPropertyNames = exposedProperties; //console.log(inputPropertyNames); configurationReactiveFunction = ReactiveFunction({ inputs: inputPropertyNames.map(getProperty), output: configurationProperty, callback: function (){ var configuration = {}; inputPropertyNames.forEach(function (propertyName){ var property = getProperty(propertyName); // Omit default values from the returned configuration object. if(property() !== property.default()){ configuration[propertyName] = property(); } }); return configuration; } }); // Support method chaining. return model; }
[ "function", "expose", "(", ")", "{", "if", "(", "!", "lastPropertyAdded", ")", "{", "throw", "Error", "(", "\"Expose() was called without first adding a property.\"", ")", ";", "}", "var", "propertyName", "=", "lastPropertyAdded", ";", "if", "(", "!", "exposedProperties", ")", "{", "exposedProperties", "=", "[", "]", ";", "}", "exposedProperties", ".", "push", "(", "propertyName", ")", ";", "if", "(", "configurationReactiveFunction", ")", "{", "configurationReactiveFunction", ".", "destroy", "(", ")", ";", "}", "var", "inputPropertyNames", "=", "exposedProperties", ";", "configurationReactiveFunction", "=", "ReactiveFunction", "(", "{", "inputs", ":", "inputPropertyNames", ".", "map", "(", "getProperty", ")", ",", "output", ":", "configurationProperty", ",", "callback", ":", "function", "(", ")", "{", "var", "configuration", "=", "{", "}", ";", "inputPropertyNames", ".", "forEach", "(", "function", "(", "propertyName", ")", "{", "var", "property", "=", "getProperty", "(", "propertyName", ")", ";", "if", "(", "property", "(", ")", "!==", "property", ".", "default", "(", ")", ")", "{", "configuration", "[", "propertyName", "]", "=", "property", "(", ")", ";", "}", "}", ")", ";", "return", "configuration", ";", "}", "}", ")", ";", "return", "model", ";", "}" ]
Exposes the last added property to the configuration.
[ "Exposes", "the", "last", "added", "property", "to", "the", "configuration", "." ]
c64c13c37216baa39cb7aafee5787a5a0a15e659
https://github.com/datavis-tech/reactive-model/blob/c64c13c37216baa39cb7aafee5787a5a0a15e659/index.js#L170-L224
train
datavis-tech/reactive-model
index.js
destroy
function destroy(){ // Destroy reactive functions. reactiveFunctions.forEach(invoke("destroy")); if(configurationReactiveFunction){ configurationReactiveFunction.destroy(); } // Destroy properties (removes listeners). Object.keys(model).forEach(function (propertyName){ var property = model[propertyName]; if(property.destroy){ property.destroy(); } }); // Release references. reactiveFunctions = undefined; configurationReactiveFunction = undefined; }
javascript
function destroy(){ // Destroy reactive functions. reactiveFunctions.forEach(invoke("destroy")); if(configurationReactiveFunction){ configurationReactiveFunction.destroy(); } // Destroy properties (removes listeners). Object.keys(model).forEach(function (propertyName){ var property = model[propertyName]; if(property.destroy){ property.destroy(); } }); // Release references. reactiveFunctions = undefined; configurationReactiveFunction = undefined; }
[ "function", "destroy", "(", ")", "{", "reactiveFunctions", ".", "forEach", "(", "invoke", "(", "\"destroy\"", ")", ")", ";", "if", "(", "configurationReactiveFunction", ")", "{", "configurationReactiveFunction", ".", "destroy", "(", ")", ";", "}", "Object", ".", "keys", "(", "model", ")", ".", "forEach", "(", "function", "(", "propertyName", ")", "{", "var", "property", "=", "model", "[", "propertyName", "]", ";", "if", "(", "property", ".", "destroy", ")", "{", "property", ".", "destroy", "(", ")", ";", "}", "}", ")", ";", "reactiveFunctions", "=", "undefined", ";", "configurationReactiveFunction", "=", "undefined", ";", "}" ]
Destroys all reactive functions and properties that have been added to the model.
[ "Destroys", "all", "reactive", "functions", "and", "properties", "that", "have", "been", "added", "to", "the", "model", "." ]
c64c13c37216baa39cb7aafee5787a5a0a15e659
https://github.com/datavis-tech/reactive-model/blob/c64c13c37216baa39cb7aafee5787a5a0a15e659/index.js#L248-L267
train
fuzhenn/tiler-arcgis-bundle
index.js
tiler
function tiler(root, options) { this.root = root; options = options || {}; options.packSize = options.packSize || 128; if (!options.storageFormat) { options.storageFormat = guessStorageFormat(root); } this.options = options; }
javascript
function tiler(root, options) { this.root = root; options = options || {}; options.packSize = options.packSize || 128; if (!options.storageFormat) { options.storageFormat = guessStorageFormat(root); } this.options = options; }
[ "function", "tiler", "(", "root", ",", "options", ")", "{", "this", ".", "root", "=", "root", ";", "options", "=", "options", "||", "{", "}", ";", "options", ".", "packSize", "=", "options", ".", "packSize", "||", "128", ";", "if", "(", "!", "options", ".", "storageFormat", ")", "{", "options", ".", "storageFormat", "=", "guessStorageFormat", "(", "root", ")", ";", "}", "this", ".", "options", "=", "options", ";", "}" ]
Constructor for the tiler-arcgis-bundle @param {String} root - the root folder of ArcGIS bundle tiles, where the Conf.xml stands. @param {Object} options - options passed in. @param {integer} options.packSize - packet size. @param {String} options.storageFormat - bundle storage format. @class
[ "Constructor", "for", "the", "tiler", "-", "arcgis", "-", "bundle" ]
16643acc7d02dd095d184ff75b42f4169ffe6e03
https://github.com/fuzhenn/tiler-arcgis-bundle/blob/16643acc7d02dd095d184ff75b42f4169ffe6e03/index.js#L21-L29
train
mozilla/webmaker-core
src/pages/project/pageadmin.js
function (id, type) { if (this.state.sourcePageID !== id) { var selectedPage; this.state.pages.forEach(function (page) { if (parseInt(page.id, 10) === parseInt(id, 10)) { selectedPage = page; } }); if (!selectedPage) { console.warn('Page not found.'); return; } var currentZoom = this.state.matrix[0]; var {x, y} = this.cartesian.getFocusTransform(selectedPage.coords, this.state.matrix[0]); var newState = { matrix: [currentZoom, 0, 0, currentZoom, x, y] }; if (type === 'selected') { newState.selectedEl = id; } else if (type === 'source') { newState.sourcePageID = id; } this.setState(newState); } }
javascript
function (id, type) { if (this.state.sourcePageID !== id) { var selectedPage; this.state.pages.forEach(function (page) { if (parseInt(page.id, 10) === parseInt(id, 10)) { selectedPage = page; } }); if (!selectedPage) { console.warn('Page not found.'); return; } var currentZoom = this.state.matrix[0]; var {x, y} = this.cartesian.getFocusTransform(selectedPage.coords, this.state.matrix[0]); var newState = { matrix: [currentZoom, 0, 0, currentZoom, x, y] }; if (type === 'selected') { newState.selectedEl = id; } else if (type === 'source') { newState.sourcePageID = id; } this.setState(newState); } }
[ "function", "(", "id", ",", "type", ")", "{", "if", "(", "this", ".", "state", ".", "sourcePageID", "!==", "id", ")", "{", "var", "selectedPage", ";", "this", ".", "state", ".", "pages", ".", "forEach", "(", "function", "(", "page", ")", "{", "if", "(", "parseInt", "(", "page", ".", "id", ",", "10", ")", "===", "parseInt", "(", "id", ",", "10", ")", ")", "{", "selectedPage", "=", "page", ";", "}", "}", ")", ";", "if", "(", "!", "selectedPage", ")", "{", "console", ".", "warn", "(", "'Page not found.'", ")", ";", "return", ";", "}", "var", "currentZoom", "=", "this", ".", "state", ".", "matrix", "[", "0", "]", ";", "var", "{", "x", ",", "y", "}", "=", "this", ".", "cartesian", ".", "getFocusTransform", "(", "selectedPage", ".", "coords", ",", "this", ".", "state", ".", "matrix", "[", "0", "]", ")", ";", "var", "newState", "=", "{", "matrix", ":", "[", "currentZoom", ",", "0", ",", "0", ",", "currentZoom", ",", "x", ",", "y", "]", "}", ";", "if", "(", "type", "===", "'selected'", ")", "{", "newState", ".", "selectedEl", "=", "id", ";", "}", "else", "if", "(", "type", "===", "'source'", ")", "{", "newState", ".", "sourcePageID", "=", "id", ";", "}", "this", ".", "setState", "(", "newState", ")", ";", "}", "}" ]
Highlight a page in the UI and move camera to center it @param {Number|String} id ID of page @param {Number|String} type Type of highlight ("selected", "source")
[ "Highlight", "a", "page", "in", "the", "UI", "and", "move", "camera", "to", "center", "it" ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/pages/project/pageadmin.js#L19-L48
train
SnakeskinTpl/Snakeskin
src/parser/jadeLike.js
appendDirEnd
function appendDirEnd(str, struct) { if (!struct.block) { return str; } const [rightSpace] = rightWSRgxp.exec(str); str = str.replace(rightPartRgxp, ''); const s = alb + lb, e = rb; let tmp; if (needSpace) { tmp = `${struct.trim.right ? '' : eol}${endDirInit ? '' : `${s}__&+__${e}`}${struct.trim.right ? eol : ''}`; } else { tmp = eol + struct.space.slice(1); } endDirInit = true; str += `${tmp}${struct.adv + lb}__end__${e}${s}__cutLine__${e}`; if (rightSpace && needSpace) { str += `${s}__&-__${rb}`; } return str + rightSpace; }
javascript
function appendDirEnd(str, struct) { if (!struct.block) { return str; } const [rightSpace] = rightWSRgxp.exec(str); str = str.replace(rightPartRgxp, ''); const s = alb + lb, e = rb; let tmp; if (needSpace) { tmp = `${struct.trim.right ? '' : eol}${endDirInit ? '' : `${s}__&+__${e}`}${struct.trim.right ? eol : ''}`; } else { tmp = eol + struct.space.slice(1); } endDirInit = true; str += `${tmp}${struct.adv + lb}__end__${e}${s}__cutLine__${e}`; if (rightSpace && needSpace) { str += `${s}__&-__${rb}`; } return str + rightSpace; }
[ "function", "appendDirEnd", "(", "str", ",", "struct", ")", "{", "if", "(", "!", "struct", ".", "block", ")", "{", "return", "str", ";", "}", "const", "[", "rightSpace", "]", "=", "rightWSRgxp", ".", "exec", "(", "str", ")", ";", "str", "=", "str", ".", "replace", "(", "rightPartRgxp", ",", "''", ")", ";", "const", "s", "=", "alb", "+", "lb", ",", "e", "=", "rb", ";", "let", "tmp", ";", "if", "(", "needSpace", ")", "{", "tmp", "=", "`", "${", "struct", ".", "trim", ".", "right", "?", "''", ":", "eol", "}", "${", "endDirInit", "?", "''", ":", "`", "${", "s", "}", "${", "e", "}", "`", "}", "${", "struct", ".", "trim", ".", "right", "?", "eol", ":", "''", "}", "`", ";", "}", "else", "{", "tmp", "=", "eol", "+", "struct", ".", "space", ".", "slice", "(", "1", ")", ";", "}", "endDirInit", "=", "true", ";", "str", "+=", "`", "${", "tmp", "}", "${", "struct", ".", "adv", "+", "lb", "}", "${", "e", "}", "${", "s", "}", "${", "e", "}", "`", ";", "if", "(", "rightSpace", "&&", "needSpace", ")", "{", "str", "+=", "`", "${", "s", "}", "${", "rb", "}", "`", ";", "}", "return", "str", "+", "rightSpace", ";", "}" ]
Appends the directive end for a resulting string and returns a new string @param {string} str - resulting string @param {!Object} struct - structure object @return {string}
[ "Appends", "the", "directive", "end", "for", "a", "resulting", "string", "and", "returns", "a", "new", "string" ]
3e92aa6c5ae9f242ef80adb5e278e9054225205a
https://github.com/SnakeskinTpl/Snakeskin/blob/3e92aa6c5ae9f242ef80adb5e278e9054225205a/src/parser/jadeLike.js#L362-L390
train
mozilla/webmaker-core
src/pages/element/font-selector.js
function() { var fonts = ["Roboto", "Bitter", "Pacifico"]; var options = fonts.map(name => { // setting style on an <option> does not work in WebView... return <option key={name} value={name}>{name}</option>; }); return <select className="select" valueLink={this.linkState('fontFamily')}>{ options }</select>; }
javascript
function() { var fonts = ["Roboto", "Bitter", "Pacifico"]; var options = fonts.map(name => { // setting style on an <option> does not work in WebView... return <option key={name} value={name}>{name}</option>; }); return <select className="select" valueLink={this.linkState('fontFamily')}>{ options }</select>; }
[ "function", "(", ")", "{", "var", "fonts", "=", "[", "\"Roboto\"", ",", "\"Bitter\"", ",", "\"Pacifico\"", "]", ";", "var", "options", "=", "fonts", ".", "map", "(", "name", "=>", "{", "return", "<", "option", "key", "=", "{", "name", "}", "value", "=", "{", "name", "}", ">", "{", "name", "}", "<", "/", "option", ">", ";", "}", ")", ";", "return", "<", "select", "className", "=", "\"select\"", "valueLink", "=", "{", "this", ".", "linkState", "(", "'fontFamily'", ")", "}", ">", "{", "options", "}", "<", "/", "select", ">", ";", "}" ]
Generate the dropdown selector for fonts, with each font option styled in the appropriate font. @return {[type]}
[ "Generate", "the", "dropdown", "selector", "for", "fonts", "with", "each", "font", "option", "styled", "in", "the", "appropriate", "font", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/pages/element/font-selector.js#L14-L21
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
callback
function callback(fn, context, event) { //window.setTimeout(function(){ event.target = context; (typeof context[fn] === "function") && context[fn].apply(context, [event]); //}, 1); }
javascript
function callback(fn, context, event) { //window.setTimeout(function(){ event.target = context; (typeof context[fn] === "function") && context[fn].apply(context, [event]); //}, 1); }
[ "function", "callback", "(", "fn", ",", "context", ",", "event", ")", "{", "event", ".", "target", "=", "context", ";", "(", "typeof", "context", "[", "fn", "]", "===", "\"function\"", ")", "&&", "context", "[", "fn", "]", ".", "apply", "(", "context", ",", "[", "event", "]", ")", ";", "}" ]
A utility method to callback onsuccess, onerror, etc as soon as the calling function's context is over @param {Object} fn @param {Object} context @param {Object} argArray
[ "A", "utility", "method", "to", "callback", "onsuccess", "onerror", "etc", "as", "soon", "as", "the", "calling", "function", "s", "context", "is", "over" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L33-L38
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
polyfill
function polyfill() { if (navigator.userAgent.match(/MSIE/) || navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/Edge/)) { // Internet Explorer's native IndexedDB does not support compound keys compoundKeyPolyfill(); } }
javascript
function polyfill() { if (navigator.userAgent.match(/MSIE/) || navigator.userAgent.match(/Trident/) || navigator.userAgent.match(/Edge/)) { // Internet Explorer's native IndexedDB does not support compound keys compoundKeyPolyfill(); } }
[ "function", "polyfill", "(", ")", "{", "if", "(", "navigator", ".", "userAgent", ".", "match", "(", "/", "MSIE", "/", ")", "||", "navigator", ".", "userAgent", ".", "match", "(", "/", "Trident", "/", ")", "||", "navigator", ".", "userAgent", ".", "match", "(", "/", "Edge", "/", ")", ")", "{", "compoundKeyPolyfill", "(", ")", ";", "}", "}" ]
Polyfills missing features in the browser's native IndexedDB implementation. This is used for browsers that DON'T support WebSQL but DO support IndexedDB
[ "Polyfills", "missing", "features", "in", "the", "browser", "s", "native", "IndexedDB", "implementation", ".", "This", "is", "used", "for", "browsers", "that", "DON", "T", "support", "WebSQL", "but", "DO", "support", "IndexedDB" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L114-L121
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
readBlobAsDataURL
function readBlobAsDataURL(blob, path) { var reader = new FileReader(); reader.onloadend = function(loadedEvent) { var dataURL = loadedEvent.target.result; var blobtype = 'Blob'; if (blob instanceof File) { //blobtype = 'File'; } updateEncodedBlob(dataURL, path, blobtype); }; reader.readAsDataURL(blob); }
javascript
function readBlobAsDataURL(blob, path) { var reader = new FileReader(); reader.onloadend = function(loadedEvent) { var dataURL = loadedEvent.target.result; var blobtype = 'Blob'; if (blob instanceof File) { //blobtype = 'File'; } updateEncodedBlob(dataURL, path, blobtype); }; reader.readAsDataURL(blob); }
[ "function", "readBlobAsDataURL", "(", "blob", ",", "path", ")", "{", "var", "reader", "=", "new", "FileReader", "(", ")", ";", "reader", ".", "onloadend", "=", "function", "(", "loadedEvent", ")", "{", "var", "dataURL", "=", "loadedEvent", ".", "target", ".", "result", ";", "var", "blobtype", "=", "'Blob'", ";", "if", "(", "blob", "instanceof", "File", ")", "{", "}", "updateEncodedBlob", "(", "dataURL", ",", "path", ",", "blobtype", ")", ";", "}", ";", "reader", ".", "readAsDataURL", "(", "blob", ")", ";", "}" ]
Convert a blob to a data URL. @param {Blob} blob to convert. @param {String} path of blob in object being encoded.
[ "Convert", "a", "blob", "to", "a", "data", "URL", "." ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L519-L530
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
updateEncodedBlob
function updateEncodedBlob(dataURL, path, blobtype) { var encoded = queuedObjects.indexOf(path); path = path.replace('$','derezObj'); eval(path+'.$enc="'+dataURL+'"'); eval(path+'.$type="'+blobtype+'"'); queuedObjects.splice(encoded, 1); checkForCompletion(); }
javascript
function updateEncodedBlob(dataURL, path, blobtype) { var encoded = queuedObjects.indexOf(path); path = path.replace('$','derezObj'); eval(path+'.$enc="'+dataURL+'"'); eval(path+'.$type="'+blobtype+'"'); queuedObjects.splice(encoded, 1); checkForCompletion(); }
[ "function", "updateEncodedBlob", "(", "dataURL", ",", "path", ",", "blobtype", ")", "{", "var", "encoded", "=", "queuedObjects", ".", "indexOf", "(", "path", ")", ";", "path", "=", "path", ".", "replace", "(", "'$'", ",", "'derezObj'", ")", ";", "eval", "(", "path", "+", "'.$enc=\"'", "+", "dataURL", "+", "'\"'", ")", ";", "eval", "(", "path", "+", "'.$type=\"'", "+", "blobtype", "+", "'\"'", ")", ";", "queuedObjects", ".", "splice", "(", "encoded", ",", "1", ")", ";", "checkForCompletion", "(", ")", ";", "}" ]
Async handler to update a blob object to a data URL for encoding. @param {String} dataURL @param {String} path @param {String} blobtype - file if the blob is a file; blob otherwise
[ "Async", "handler", "to", "update", "a", "blob", "object", "to", "a", "data", "URL", "for", "encoding", "." ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L538-L545
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
dataURLToBlob
function dataURLToBlob(dataURL) { var BASE64_MARKER = ';base64,', contentType, parts, raw; if (dataURL.indexOf(BASE64_MARKER) === -1) { parts = dataURL.split(','); contentType = parts[0].split(':')[1]; raw = parts[1]; return new Blob([raw], {type: contentType}); } parts = dataURL.split(BASE64_MARKER); contentType = parts[0].split(':')[1]; raw = window.atob(parts[1]); var rawLength = raw.length; var uInt8Array = new Uint8Array(rawLength); for (var i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array.buffer], {type: contentType}); }
javascript
function dataURLToBlob(dataURL) { var BASE64_MARKER = ';base64,', contentType, parts, raw; if (dataURL.indexOf(BASE64_MARKER) === -1) { parts = dataURL.split(','); contentType = parts[0].split(':')[1]; raw = parts[1]; return new Blob([raw], {type: contentType}); } parts = dataURL.split(BASE64_MARKER); contentType = parts[0].split(':')[1]; raw = window.atob(parts[1]); var rawLength = raw.length; var uInt8Array = new Uint8Array(rawLength); for (var i = 0; i < rawLength; ++i) { uInt8Array[i] = raw.charCodeAt(i); } return new Blob([uInt8Array.buffer], {type: contentType}); }
[ "function", "dataURLToBlob", "(", "dataURL", ")", "{", "var", "BASE64_MARKER", "=", "';base64,'", ",", "contentType", ",", "parts", ",", "raw", ";", "if", "(", "dataURL", ".", "indexOf", "(", "BASE64_MARKER", ")", "===", "-", "1", ")", "{", "parts", "=", "dataURL", ".", "split", "(", "','", ")", ";", "contentType", "=", "parts", "[", "0", "]", ".", "split", "(", "':'", ")", "[", "1", "]", ";", "raw", "=", "parts", "[", "1", "]", ";", "return", "new", "Blob", "(", "[", "raw", "]", ",", "{", "type", ":", "contentType", "}", ")", ";", "}", "parts", "=", "dataURL", ".", "split", "(", "BASE64_MARKER", ")", ";", "contentType", "=", "parts", "[", "0", "]", ".", "split", "(", "':'", ")", "[", "1", "]", ";", "raw", "=", "window", ".", "atob", "(", "parts", "[", "1", "]", ")", ";", "var", "rawLength", "=", "raw", ".", "length", ";", "var", "uInt8Array", "=", "new", "Uint8Array", "(", "rawLength", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "rawLength", ";", "++", "i", ")", "{", "uInt8Array", "[", "i", "]", "=", "raw", ".", "charCodeAt", "(", "i", ")", ";", "}", "return", "new", "Blob", "(", "[", "uInt8Array", ".", "buffer", "]", ",", "{", "type", ":", "contentType", "}", ")", ";", "}" ]
Converts the specified data URL to a Blob object @param {String} dataURL to convert to a Blob @returns {Blob} the converted Blob object
[ "Converts", "the", "specified", "data", "URL", "to", "a", "Blob", "object" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L676-L699
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
function(key) { var key32 = Math.abs(key).toString(32); // Get the index of the decimal. var decimalIndex = key32.indexOf("."); // Remove the decimal. key32 = (decimalIndex !== -1) ? key32.replace(".", "") : key32; // Get the index of the first significant digit. var significantDigitIndex = key32.search(/[^0]/); // Truncate leading zeros. key32 = key32.slice(significantDigitIndex); var sign, exponent = zeros(2), mantissa = zeros(11); // Finite cases: if (isFinite(key)) { // Negative cases: if (key < 0) { // Negative exponent case: if (key > -1) { sign = signValues.indexOf("smallNegative"); exponent = padBase32Exponent(significantDigitIndex); mantissa = flipBase32(padBase32Mantissa(key32)); } // Non-negative exponent case: else { sign = signValues.indexOf("bigNegative"); exponent = flipBase32(padBase32Exponent( (decimalIndex !== -1) ? decimalIndex : key32.length )); mantissa = flipBase32(padBase32Mantissa(key32)); } } // Non-negative cases: else { // Negative exponent case: if (key < 1) { sign = signValues.indexOf("smallPositive"); exponent = flipBase32(padBase32Exponent(significantDigitIndex)); mantissa = padBase32Mantissa(key32); } // Non-negative exponent case: else { sign = signValues.indexOf("bigPositive"); exponent = padBase32Exponent( (decimalIndex !== -1) ? decimalIndex : key32.length ); mantissa = padBase32Mantissa(key32); } } } // Infinite cases: else { sign = signValues.indexOf( key > 0 ? "positiveInfinity" : "negativeInfinity" ); } return collations.indexOf("number") + "-" + sign + exponent + mantissa; }
javascript
function(key) { var key32 = Math.abs(key).toString(32); // Get the index of the decimal. var decimalIndex = key32.indexOf("."); // Remove the decimal. key32 = (decimalIndex !== -1) ? key32.replace(".", "") : key32; // Get the index of the first significant digit. var significantDigitIndex = key32.search(/[^0]/); // Truncate leading zeros. key32 = key32.slice(significantDigitIndex); var sign, exponent = zeros(2), mantissa = zeros(11); // Finite cases: if (isFinite(key)) { // Negative cases: if (key < 0) { // Negative exponent case: if (key > -1) { sign = signValues.indexOf("smallNegative"); exponent = padBase32Exponent(significantDigitIndex); mantissa = flipBase32(padBase32Mantissa(key32)); } // Non-negative exponent case: else { sign = signValues.indexOf("bigNegative"); exponent = flipBase32(padBase32Exponent( (decimalIndex !== -1) ? decimalIndex : key32.length )); mantissa = flipBase32(padBase32Mantissa(key32)); } } // Non-negative cases: else { // Negative exponent case: if (key < 1) { sign = signValues.indexOf("smallPositive"); exponent = flipBase32(padBase32Exponent(significantDigitIndex)); mantissa = padBase32Mantissa(key32); } // Non-negative exponent case: else { sign = signValues.indexOf("bigPositive"); exponent = padBase32Exponent( (decimalIndex !== -1) ? decimalIndex : key32.length ); mantissa = padBase32Mantissa(key32); } } } // Infinite cases: else { sign = signValues.indexOf( key > 0 ? "positiveInfinity" : "negativeInfinity" ); } return collations.indexOf("number") + "-" + sign + exponent + mantissa; }
[ "function", "(", "key", ")", "{", "var", "key32", "=", "Math", ".", "abs", "(", "key", ")", ".", "toString", "(", "32", ")", ";", "var", "decimalIndex", "=", "key32", ".", "indexOf", "(", "\".\"", ")", ";", "key32", "=", "(", "decimalIndex", "!==", "-", "1", ")", "?", "key32", ".", "replace", "(", "\".\"", ",", "\"\"", ")", ":", "key32", ";", "var", "significantDigitIndex", "=", "key32", ".", "search", "(", "/", "[^0]", "/", ")", ";", "key32", "=", "key32", ".", "slice", "(", "significantDigitIndex", ")", ";", "var", "sign", ",", "exponent", "=", "zeros", "(", "2", ")", ",", "mantissa", "=", "zeros", "(", "11", ")", ";", "if", "(", "isFinite", "(", "key", ")", ")", "{", "if", "(", "key", "<", "0", ")", "{", "if", "(", "key", ">", "-", "1", ")", "{", "sign", "=", "signValues", ".", "indexOf", "(", "\"smallNegative\"", ")", ";", "exponent", "=", "padBase32Exponent", "(", "significantDigitIndex", ")", ";", "mantissa", "=", "flipBase32", "(", "padBase32Mantissa", "(", "key32", ")", ")", ";", "}", "else", "{", "sign", "=", "signValues", ".", "indexOf", "(", "\"bigNegative\"", ")", ";", "exponent", "=", "flipBase32", "(", "padBase32Exponent", "(", "(", "decimalIndex", "!==", "-", "1", ")", "?", "decimalIndex", ":", "key32", ".", "length", ")", ")", ";", "mantissa", "=", "flipBase32", "(", "padBase32Mantissa", "(", "key32", ")", ")", ";", "}", "}", "else", "{", "if", "(", "key", "<", "1", ")", "{", "sign", "=", "signValues", ".", "indexOf", "(", "\"smallPositive\"", ")", ";", "exponent", "=", "flipBase32", "(", "padBase32Exponent", "(", "significantDigitIndex", ")", ")", ";", "mantissa", "=", "padBase32Mantissa", "(", "key32", ")", ";", "}", "else", "{", "sign", "=", "signValues", ".", "indexOf", "(", "\"bigPositive\"", ")", ";", "exponent", "=", "padBase32Exponent", "(", "(", "decimalIndex", "!==", "-", "1", ")", "?", "decimalIndex", ":", "key32", ".", "length", ")", ";", "mantissa", "=", "padBase32Mantissa", "(", "key32", ")", ";", "}", "}", "}", "else", "{", "sign", "=", "signValues", ".", "indexOf", "(", "key", ">", "0", "?", "\"positiveInfinity\"", ":", "\"negativeInfinity\"", ")", ";", "}", "return", "collations", ".", "indexOf", "(", "\"number\"", ")", "+", "\"-\"", "+", "sign", "+", "exponent", "+", "mantissa", ";", "}" ]
The encode step checks for six numeric cases and generates 14-digit encoded sign-exponent-mantissa strings.
[ "The", "encode", "step", "checks", "for", "six", "numeric", "cases", "and", "generates", "14", "-", "digit", "encoded", "sign", "-", "exponent", "-", "mantissa", "strings", "." ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L852-L909
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
function(key) { var sign = +key.substr(2, 1); var exponent = key.substr(3, 2); var mantissa = key.substr(5, 11); switch (signValues[sign]) { case "negativeInfinity": return -Infinity; case "positiveInfinity": return Infinity; case "bigPositive": return pow32(mantissa, exponent); case "smallPositive": exponent = negate(flipBase32(exponent)); return pow32(mantissa, exponent); case "smallNegative": exponent = negate(exponent); mantissa = flipBase32(mantissa); return -pow32(mantissa, exponent); case "bigNegative": exponent = flipBase32(exponent); mantissa = flipBase32(mantissa); return -pow32(mantissa, exponent); default: throw new Error("Invalid number."); } }
javascript
function(key) { var sign = +key.substr(2, 1); var exponent = key.substr(3, 2); var mantissa = key.substr(5, 11); switch (signValues[sign]) { case "negativeInfinity": return -Infinity; case "positiveInfinity": return Infinity; case "bigPositive": return pow32(mantissa, exponent); case "smallPositive": exponent = negate(flipBase32(exponent)); return pow32(mantissa, exponent); case "smallNegative": exponent = negate(exponent); mantissa = flipBase32(mantissa); return -pow32(mantissa, exponent); case "bigNegative": exponent = flipBase32(exponent); mantissa = flipBase32(mantissa); return -pow32(mantissa, exponent); default: throw new Error("Invalid number."); } }
[ "function", "(", "key", ")", "{", "var", "sign", "=", "+", "key", ".", "substr", "(", "2", ",", "1", ")", ";", "var", "exponent", "=", "key", ".", "substr", "(", "3", ",", "2", ")", ";", "var", "mantissa", "=", "key", ".", "substr", "(", "5", ",", "11", ")", ";", "switch", "(", "signValues", "[", "sign", "]", ")", "{", "case", "\"negativeInfinity\"", ":", "return", "-", "Infinity", ";", "case", "\"positiveInfinity\"", ":", "return", "Infinity", ";", "case", "\"bigPositive\"", ":", "return", "pow32", "(", "mantissa", ",", "exponent", ")", ";", "case", "\"smallPositive\"", ":", "exponent", "=", "negate", "(", "flipBase32", "(", "exponent", ")", ")", ";", "return", "pow32", "(", "mantissa", ",", "exponent", ")", ";", "case", "\"smallNegative\"", ":", "exponent", "=", "negate", "(", "exponent", ")", ";", "mantissa", "=", "flipBase32", "(", "mantissa", ")", ";", "return", "-", "pow32", "(", "mantissa", ",", "exponent", ")", ";", "case", "\"bigNegative\"", ":", "exponent", "=", "flipBase32", "(", "exponent", ")", ";", "mantissa", "=", "flipBase32", "(", "mantissa", ")", ";", "return", "-", "pow32", "(", "mantissa", ",", "exponent", ")", ";", "default", ":", "throw", "new", "Error", "(", "\"Invalid number.\"", ")", ";", "}", "}" ]
The decode step must interpret the sign, reflip values encoded as the 32's complements, apply signs to the exponent and mantissa, do the base-32 power operation, and return the original JavaScript number values.
[ "The", "decode", "step", "must", "interpret", "the", "sign", "reflip", "values", "encoded", "as", "the", "32", "s", "complements", "apply", "signs", "to", "the", "exponent", "and", "mantissa", "do", "the", "base", "-", "32", "power", "operation", "and", "return", "the", "original", "JavaScript", "number", "values", "." ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L913-L939
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
flipBase32
function flipBase32(encoded) { var flipped = ""; for (var i = 0; i < encoded.length; i++) { flipped += (31 - parseInt(encoded[i], 32)).toString(32); } return flipped; }
javascript
function flipBase32(encoded) { var flipped = ""; for (var i = 0; i < encoded.length; i++) { flipped += (31 - parseInt(encoded[i], 32)).toString(32); } return flipped; }
[ "function", "flipBase32", "(", "encoded", ")", "{", "var", "flipped", "=", "\"\"", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "encoded", ".", "length", ";", "i", "++", ")", "{", "flipped", "+=", "(", "31", "-", "parseInt", "(", "encoded", "[", "i", "]", ",", "32", ")", ")", ".", "toString", "(", "32", ")", ";", "}", "return", "flipped", ";", "}" ]
Flips each digit of a base-32 encoded string. @param {string} encoded
[ "Flips", "each", "digit", "of", "a", "base", "-", "32", "encoded", "string", "." ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1017-L1023
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
validate
function validate(key) { var type = getType(key); if (type === "array") { for (var i = 0; i < key.length; i++) { validate(key[i]); } } else if (!types[type] || (type !== "string" && isNaN(key))) { throw idbModules.util.createDOMException("DataError", "Not a valid key"); } }
javascript
function validate(key) { var type = getType(key); if (type === "array") { for (var i = 0; i < key.length; i++) { validate(key[i]); } } else if (!types[type] || (type !== "string" && isNaN(key))) { throw idbModules.util.createDOMException("DataError", "Not a valid key"); } }
[ "function", "validate", "(", "key", ")", "{", "var", "type", "=", "getType", "(", "key", ")", ";", "if", "(", "type", "===", "\"array\"", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "key", ".", "length", ";", "i", "++", ")", "{", "validate", "(", "key", "[", "i", "]", ")", ";", "}", "}", "else", "if", "(", "!", "types", "[", "type", "]", "||", "(", "type", "!==", "\"string\"", "&&", "isNaN", "(", "key", ")", ")", ")", "{", "throw", "idbModules", ".", "util", ".", "createDOMException", "(", "\"DataError\"", ",", "\"Not a valid key\"", ")", ";", "}", "}" ]
Keys must be strings, numbers, Dates, or Arrays
[ "Keys", "must", "be", "strings", "numbers", "Dates", "or", "Arrays" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1106-L1116
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
getValue
function getValue(source, keyPath) { try { if (keyPath instanceof Array) { var arrayValue = []; for (var i = 0; i < keyPath.length; i++) { arrayValue.push(eval("source." + keyPath[i])); } return arrayValue; } else { return eval("source." + keyPath); } } catch (e) { return undefined; } }
javascript
function getValue(source, keyPath) { try { if (keyPath instanceof Array) { var arrayValue = []; for (var i = 0; i < keyPath.length; i++) { arrayValue.push(eval("source." + keyPath[i])); } return arrayValue; } else { return eval("source." + keyPath); } } catch (e) { return undefined; } }
[ "function", "getValue", "(", "source", ",", "keyPath", ")", "{", "try", "{", "if", "(", "keyPath", "instanceof", "Array", ")", "{", "var", "arrayValue", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "keyPath", ".", "length", ";", "i", "++", ")", "{", "arrayValue", ".", "push", "(", "eval", "(", "\"source.\"", "+", "keyPath", "[", "i", "]", ")", ")", ";", "}", "return", "arrayValue", ";", "}", "else", "{", "return", "eval", "(", "\"source.\"", "+", "keyPath", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "return", "undefined", ";", "}", "}" ]
Returns the value of an inline key @param {object} source @param {string|array} keyPath
[ "Returns", "the", "value", "of", "an", "inline", "key" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1123-L1138
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
setValue
function setValue(source, keyPath, value) { var props = keyPath.split('.'); for (var i = 0; i < props.length - 1; i++) { var prop = props[i]; source = source[prop] = source[prop] || {}; } source[props[props.length - 1]] = value; }
javascript
function setValue(source, keyPath, value) { var props = keyPath.split('.'); for (var i = 0; i < props.length - 1; i++) { var prop = props[i]; source = source[prop] = source[prop] || {}; } source[props[props.length - 1]] = value; }
[ "function", "setValue", "(", "source", ",", "keyPath", ",", "value", ")", "{", "var", "props", "=", "keyPath", ".", "split", "(", "'.'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "props", ".", "length", "-", "1", ";", "i", "++", ")", "{", "var", "prop", "=", "props", "[", "i", "]", ";", "source", "=", "source", "[", "prop", "]", "=", "source", "[", "prop", "]", "||", "{", "}", ";", "}", "source", "[", "props", "[", "props", ".", "length", "-", "1", "]", "]", "=", "value", ";", "}" ]
Sets the inline key value @param {object} source @param {string} keyPath @param {*} value
[ "Sets", "the", "inline", "key", "value" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1146-L1153
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
isMultiEntryMatch
function isMultiEntryMatch(encodedEntry, encodedKey) { var keyType = collations[encodedKey.substring(0, 1)]; if (keyType === "array") { return encodedKey.indexOf(encodedEntry) > 1; } else { return encodedKey === encodedEntry; } }
javascript
function isMultiEntryMatch(encodedEntry, encodedKey) { var keyType = collations[encodedKey.substring(0, 1)]; if (keyType === "array") { return encodedKey.indexOf(encodedEntry) > 1; } else { return encodedKey === encodedEntry; } }
[ "function", "isMultiEntryMatch", "(", "encodedEntry", ",", "encodedKey", ")", "{", "var", "keyType", "=", "collations", "[", "encodedKey", ".", "substring", "(", "0", ",", "1", ")", "]", ";", "if", "(", "keyType", "===", "\"array\"", ")", "{", "return", "encodedKey", ".", "indexOf", "(", "encodedEntry", ")", ">", "1", ";", "}", "else", "{", "return", "encodedKey", "===", "encodedEntry", ";", "}", "}" ]
Determines whether an index entry matches a multi-entry key value. @param {string} encodedEntry The entry value (already encoded) @param {string} encodedKey The full index key (already encoded) @returns {boolean}
[ "Determines", "whether", "an", "index", "entry", "matches", "a", "multi", "-", "entry", "key", "value", "." ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1161-L1170
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
createNativeEvent
function createNativeEvent(type, debug) { var event = new Event(type); event.debug = debug; // Make the "target" writable Object.defineProperty(event, 'target', { writable: true }); return event; }
javascript
function createNativeEvent(type, debug) { var event = new Event(type); event.debug = debug; // Make the "target" writable Object.defineProperty(event, 'target', { writable: true }); return event; }
[ "function", "createNativeEvent", "(", "type", ",", "debug", ")", "{", "var", "event", "=", "new", "Event", "(", "type", ")", ";", "event", ".", "debug", "=", "debug", ";", "Object", ".", "defineProperty", "(", "event", ",", "'target'", ",", "{", "writable", ":", "true", "}", ")", ";", "return", "event", ";", "}" ]
Creates a native Event object, for browsers that support it @returns {Event}
[ "Creates", "a", "native", "Event", "object", "for", "browsers", "that", "support", "it" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1259-L1269
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
ShimEvent
function ShimEvent(type, debug) { this.type = type; this.debug = debug; this.bubbles = false; this.cancelable = false; this.eventPhase = 0; this.timeStamp = new Date().valueOf(); }
javascript
function ShimEvent(type, debug) { this.type = type; this.debug = debug; this.bubbles = false; this.cancelable = false; this.eventPhase = 0; this.timeStamp = new Date().valueOf(); }
[ "function", "ShimEvent", "(", "type", ",", "debug", ")", "{", "this", ".", "type", "=", "type", ";", "this", ".", "debug", "=", "debug", ";", "this", ".", "bubbles", "=", "false", ";", "this", ".", "cancelable", "=", "false", ";", "this", ".", "eventPhase", "=", "0", ";", "this", ".", "timeStamp", "=", "new", "Date", "(", ")", ".", "valueOf", "(", ")", ";", "}" ]
A shim Event class, for browsers that don't allow us to create native Event objects. @constructor
[ "A", "shim", "Event", "class", "for", "browsers", "that", "don", "t", "allow", "us", "to", "create", "native", "Event", "objects", "." ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1275-L1282
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
createNativeDOMException
function createNativeDOMException(name, message) { var e = new DOMException.prototype.constructor(0, message); e.name = name || 'DOMException'; e.message = message; return e; }
javascript
function createNativeDOMException(name, message) { var e = new DOMException.prototype.constructor(0, message); e.name = name || 'DOMException'; e.message = message; return e; }
[ "function", "createNativeDOMException", "(", "name", ",", "message", ")", "{", "var", "e", "=", "new", "DOMException", ".", "prototype", ".", "constructor", "(", "0", ",", "message", ")", ";", "e", ".", "name", "=", "name", "||", "'DOMException'", ";", "e", ".", "message", "=", "message", ";", "return", "e", ";", "}" ]
Creates a native DOMException, for browsers that support it @returns {DOMException}
[ "Creates", "a", "native", "DOMException", "for", "browsers", "that", "support", "it" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1319-L1324
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
createNativeDOMError
function createNativeDOMError(name, message) { name = name || 'DOMError'; var e = new DOMError(name, message); e.name === name || (e.name = name); e.message === message || (e.message = message); return e; }
javascript
function createNativeDOMError(name, message) { name = name || 'DOMError'; var e = new DOMError(name, message); e.name === name || (e.name = name); e.message === message || (e.message = message); return e; }
[ "function", "createNativeDOMError", "(", "name", ",", "message", ")", "{", "name", "=", "name", "||", "'DOMError'", ";", "var", "e", "=", "new", "DOMError", "(", "name", ",", "message", ")", ";", "e", ".", "name", "===", "name", "||", "(", "e", ".", "name", "=", "name", ")", ";", "e", ".", "message", "===", "message", "||", "(", "e", ".", "message", "=", "message", ")", ";", "return", "e", ";", "}" ]
Creates a native DOMError, for browsers that support it @returns {DOMError}
[ "Creates", "a", "native", "DOMError", "for", "browsers", "that", "support", "it" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1330-L1336
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
createError
function createError(name, message) { var e = new Error(message); e.name = name || 'DOMException'; e.message = message; return e; }
javascript
function createError(name, message) { var e = new Error(message); e.name = name || 'DOMException'; e.message = message; return e; }
[ "function", "createError", "(", "name", ",", "message", ")", "{", "var", "e", "=", "new", "Error", "(", "message", ")", ";", "e", ".", "name", "=", "name", "||", "'DOMException'", ";", "e", ".", "message", "=", "message", ";", "return", "e", ";", "}" ]
Creates a generic Error object @returns {Error}
[ "Creates", "a", "generic", "Error", "object" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L1342-L1347
train
ABB-Austin/cordova-plugin-indexeddb-async
www/indexeddbshim.min.js
createSysDB
function createSysDB(success, failure) { function sysDbCreateError(tx, err) { err = idbModules.util.findError(arguments); idbModules.DEBUG && console.log("Error in sysdb transaction - when creating dbVersions", err); failure(err); } if (sysdb) { success(); } else { sysdb = window.openDatabase("__sysdb__", 1, "System Database", DEFAULT_DB_SIZE); sysdb.transaction(function(tx) { tx.executeSql("CREATE TABLE IF NOT EXISTS dbVersions (name VARCHAR(255), version INT);", [], success, sysDbCreateError); }, sysDbCreateError); } }
javascript
function createSysDB(success, failure) { function sysDbCreateError(tx, err) { err = idbModules.util.findError(arguments); idbModules.DEBUG && console.log("Error in sysdb transaction - when creating dbVersions", err); failure(err); } if (sysdb) { success(); } else { sysdb = window.openDatabase("__sysdb__", 1, "System Database", DEFAULT_DB_SIZE); sysdb.transaction(function(tx) { tx.executeSql("CREATE TABLE IF NOT EXISTS dbVersions (name VARCHAR(255), version INT);", [], success, sysDbCreateError); }, sysDbCreateError); } }
[ "function", "createSysDB", "(", "success", ",", "failure", ")", "{", "function", "sysDbCreateError", "(", "tx", ",", "err", ")", "{", "err", "=", "idbModules", ".", "util", ".", "findError", "(", "arguments", ")", ";", "idbModules", ".", "DEBUG", "&&", "console", ".", "log", "(", "\"Error in sysdb transaction - when creating dbVersions\"", ",", "err", ")", ";", "failure", "(", "err", ")", ";", "}", "if", "(", "sysdb", ")", "{", "success", "(", ")", ";", "}", "else", "{", "sysdb", "=", "window", ".", "openDatabase", "(", "\"__sysdb__\"", ",", "1", ",", "\"System Database\"", ",", "DEFAULT_DB_SIZE", ")", ";", "sysdb", ".", "transaction", "(", "function", "(", "tx", ")", "{", "tx", ".", "executeSql", "(", "\"CREATE TABLE IF NOT EXISTS dbVersions (name VARCHAR(255), version INT);\"", ",", "[", "]", ",", "success", ",", "sysDbCreateError", ")", ";", "}", ",", "sysDbCreateError", ")", ";", "}", "}" ]
Craetes the sysDB to keep track of version numbers for databases
[ "Craetes", "the", "sysDB", "to", "keep", "track", "of", "version", "numbers", "for", "databases" ]
5a68d0463d0a87561662b2b794b3d40397536a01
https://github.com/ABB-Austin/cordova-plugin-indexeddb-async/blob/5a68d0463d0a87561662b2b794b3d40397536a01/www/indexeddbshim.min.js#L3027-L3043
train
tomterl/metalsmith-convert
lib/index.js
function(args) { if (!args.src) { ret = new Error('metalsmith-convert: "src" arg is required'); return; } if (!args.target) { // use source-format for target in convertFile args.target = '__source__'; } var ext = args.extension || '.' + args.target; if (!args.nameFormat) { if (args.resize) { args.nameFormat = '%b_%x_%y%e'; } else { args.nameFormat = '%b%e'; } } if (!!args.remove // don't remove source-files from build if && args.nameFormat === '%b%e' // the converted target has the && args.target === '__source__') { // same name args.remove = false; } Object.keys(files).forEach(function (file) { convertFile(file, ext, args, files, results); }); }
javascript
function(args) { if (!args.src) { ret = new Error('metalsmith-convert: "src" arg is required'); return; } if (!args.target) { // use source-format for target in convertFile args.target = '__source__'; } var ext = args.extension || '.' + args.target; if (!args.nameFormat) { if (args.resize) { args.nameFormat = '%b_%x_%y%e'; } else { args.nameFormat = '%b%e'; } } if (!!args.remove // don't remove source-files from build if && args.nameFormat === '%b%e' // the converted target has the && args.target === '__source__') { // same name args.remove = false; } Object.keys(files).forEach(function (file) { convertFile(file, ext, args, files, results); }); }
[ "function", "(", "args", ")", "{", "if", "(", "!", "args", ".", "src", ")", "{", "ret", "=", "new", "Error", "(", "'metalsmith-convert: \"src\" arg is required'", ")", ";", "return", ";", "}", "if", "(", "!", "args", ".", "target", ")", "{", "args", ".", "target", "=", "'__source__'", ";", "}", "var", "ext", "=", "args", ".", "extension", "||", "'.'", "+", "args", ".", "target", ";", "if", "(", "!", "args", ".", "nameFormat", ")", "{", "if", "(", "args", ".", "resize", ")", "{", "args", ".", "nameFormat", "=", "'%b_%x_%y%e'", ";", "}", "else", "{", "args", ".", "nameFormat", "=", "'%b%e'", ";", "}", "}", "if", "(", "!", "!", "args", ".", "remove", "&&", "args", ".", "nameFormat", "===", "'%b%e'", "&&", "args", ".", "target", "===", "'__source__'", ")", "{", "args", ".", "remove", "=", "false", ";", "}", "Object", ".", "keys", "(", "files", ")", ".", "forEach", "(", "function", "(", "file", ")", "{", "convertFile", "(", "file", ",", "ext", ",", "args", ",", "files", ",", "results", ")", ";", "}", ")", ";", "}" ]
what to return;
[ "what", "to", "return", ";" ]
0370a6dc268d6288be8620faa620820843b538e7
https://github.com/tomterl/metalsmith-convert/blob/0370a6dc268d6288be8620faa620820843b538e7/lib/index.js#L13-L39
train
mozilla/webmaker-core
src/lib/touchhandler.js
timedLog
function timedLog(msg) { console.log(Date.now() + ":" + window.performance.now() + ": " + msg); }
javascript
function timedLog(msg) { console.log(Date.now() + ":" + window.performance.now() + ": " + msg); }
[ "function", "timedLog", "(", "msg", ")", "{", "console", ".", "log", "(", "Date", ".", "now", "(", ")", "+", "\":\"", "+", "window", ".", "performance", ".", "now", "(", ")", "+", "\": \"", "+", "msg", ")", ";", "}" ]
A timed logging function for tracing touch calls during debug
[ "A", "timed", "logging", "function", "for", "tracing", "touch", "calls", "during", "debug" ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/lib/touchhandler.js#L10-L12
train
mozilla/webmaker-core
src/lib/touchhandler.js
function(evt) { evt.preventDefault(); evt.stopPropagation(); // Calculate actual height of element so we can calculate bounds properly positionable.rect = positionable.refs.styleWrapper.getBoundingClientRect(); if (debug) { timedLog("startmark"); } if(!evt.touches || evt.touches.length === 1) { if (debug) { timedLog("startmark - continued"); } mark = copy(positionable.state); transform.x1 = evt.clientX || evt.touches[0].pageX; transform.y1 = evt.clientY || evt.touches[0].pageY; positionable.setState({ touchactive: true }); } else { handlers.secondFinger(evt); } var timeStart = new Date(); //For detecting taps tapStart = { x1: evt.touches[0].pageX, y1: evt.touches[0].pageY, timeStart: timeStart }; }
javascript
function(evt) { evt.preventDefault(); evt.stopPropagation(); // Calculate actual height of element so we can calculate bounds properly positionable.rect = positionable.refs.styleWrapper.getBoundingClientRect(); if (debug) { timedLog("startmark"); } if(!evt.touches || evt.touches.length === 1) { if (debug) { timedLog("startmark - continued"); } mark = copy(positionable.state); transform.x1 = evt.clientX || evt.touches[0].pageX; transform.y1 = evt.clientY || evt.touches[0].pageY; positionable.setState({ touchactive: true }); } else { handlers.secondFinger(evt); } var timeStart = new Date(); //For detecting taps tapStart = { x1: evt.touches[0].pageX, y1: evt.touches[0].pageY, timeStart: timeStart }; }
[ "function", "(", "evt", ")", "{", "evt", ".", "preventDefault", "(", ")", ";", "evt", ".", "stopPropagation", "(", ")", ";", "positionable", ".", "rect", "=", "positionable", ".", "refs", ".", "styleWrapper", ".", "getBoundingClientRect", "(", ")", ";", "if", "(", "debug", ")", "{", "timedLog", "(", "\"startmark\"", ")", ";", "}", "if", "(", "!", "evt", ".", "touches", "||", "evt", ".", "touches", ".", "length", "===", "1", ")", "{", "if", "(", "debug", ")", "{", "timedLog", "(", "\"startmark - continued\"", ")", ";", "}", "mark", "=", "copy", "(", "positionable", ".", "state", ")", ";", "transform", ".", "x1", "=", "evt", ".", "clientX", "||", "evt", ".", "touches", "[", "0", "]", ".", "pageX", ";", "transform", ".", "y1", "=", "evt", ".", "clientY", "||", "evt", ".", "touches", "[", "0", "]", ".", "pageY", ";", "positionable", ".", "setState", "(", "{", "touchactive", ":", "true", "}", ")", ";", "}", "else", "{", "handlers", ".", "secondFinger", "(", "evt", ")", ";", "}", "var", "timeStart", "=", "new", "Date", "(", ")", ";", "tapStart", "=", "{", "x1", ":", "evt", ".", "touches", "[", "0", "]", ".", "pageX", ",", "y1", ":", "evt", ".", "touches", "[", "0", "]", ".", "pageY", ",", "timeStart", ":", "timeStart", "}", ";", "}" ]
mark the first touch event so we can perform computation relative to that coordinate.
[ "mark", "the", "first", "touch", "event", "so", "we", "can", "perform", "computation", "relative", "to", "that", "coordinate", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/lib/touchhandler.js#L41-L65
train
mozilla/webmaker-core
src/lib/touchhandler.js
function(evt) { if (debug) { timedLog("endmark"); } if(evt.touches && evt.touches.length > 0) { if (handlers.endSecondFinger(evt)) { return; } } if (debug) { timedLog("endmark - continued"); } mark = copy(positionable.state); var modified = transform.modified; transform = resetTransform(); // Only fire a tap if it's under the threshold if (tapDiff < MAX_TAP_THRESHOLD && (new Date() - tapStart.timeStart <= tapDuration) && positionable.onTap) { positionable.setState({touchactive: false}, function() { if(positionable.onTap){ positionable.onTap(); } }); return; } // Reset tapDiff = 0; positionable.setState({ touchactive: false }, function() { if (positionable.onTouchEnd) { positionable.onTouchEnd(modified); } }); }
javascript
function(evt) { if (debug) { timedLog("endmark"); } if(evt.touches && evt.touches.length > 0) { if (handlers.endSecondFinger(evt)) { return; } } if (debug) { timedLog("endmark - continued"); } mark = copy(positionable.state); var modified = transform.modified; transform = resetTransform(); // Only fire a tap if it's under the threshold if (tapDiff < MAX_TAP_THRESHOLD && (new Date() - tapStart.timeStart <= tapDuration) && positionable.onTap) { positionable.setState({touchactive: false}, function() { if(positionable.onTap){ positionable.onTap(); } }); return; } // Reset tapDiff = 0; positionable.setState({ touchactive: false }, function() { if (positionable.onTouchEnd) { positionable.onTouchEnd(modified); } }); }
[ "function", "(", "evt", ")", "{", "if", "(", "debug", ")", "{", "timedLog", "(", "\"endmark\"", ")", ";", "}", "if", "(", "evt", ".", "touches", "&&", "evt", ".", "touches", ".", "length", ">", "0", ")", "{", "if", "(", "handlers", ".", "endSecondFinger", "(", "evt", ")", ")", "{", "return", ";", "}", "}", "if", "(", "debug", ")", "{", "timedLog", "(", "\"endmark - continued\"", ")", ";", "}", "mark", "=", "copy", "(", "positionable", ".", "state", ")", ";", "var", "modified", "=", "transform", ".", "modified", ";", "transform", "=", "resetTransform", "(", ")", ";", "if", "(", "tapDiff", "<", "MAX_TAP_THRESHOLD", "&&", "(", "new", "Date", "(", ")", "-", "tapStart", ".", "timeStart", "<=", "tapDuration", ")", "&&", "positionable", ".", "onTap", ")", "{", "positionable", ".", "setState", "(", "{", "touchactive", ":", "false", "}", ",", "function", "(", ")", "{", "if", "(", "positionable", ".", "onTap", ")", "{", "positionable", ".", "onTap", "(", ")", ";", "}", "}", ")", ";", "return", ";", "}", "tapDiff", "=", "0", ";", "positionable", ".", "setState", "(", "{", "touchactive", ":", "false", "}", ",", "function", "(", ")", "{", "if", "(", "positionable", ".", "onTouchEnd", ")", "{", "positionable", ".", "onTouchEnd", "(", "modified", ")", ";", "}", "}", ")", ";", "}" ]
When all fingers are off the device, stop being in "touch mode"
[ "When", "all", "fingers", "are", "off", "the", "device", "stop", "being", "in", "touch", "mode" ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/lib/touchhandler.js#L106-L134
train
mozilla/webmaker-core
src/lib/touchhandler.js
function(evt) { evt.preventDefault(); evt.stopPropagation(); if (debug) { timedLog("secondFinger"); } if (evt.touches.length < 2) { return; } // we need to rebind finger 1, because it may have moved! transform.x1 = evt.touches[0].pageX; transform.y1 = evt.touches[0].pageY; transform.x2 = evt.touches[1].pageX; transform.y2 = evt.touches[1].pageY; var x1 = transform.x1, y1 = transform.y1, x2 = transform.x2, y2 = transform.y2, dx = x2 - x1, dy = y2 - y1, d = Math.sqrt(dx*dx + dy*dy), a = Math.atan2(dy,dx); transform.distance = d; transform.angle = a; }
javascript
function(evt) { evt.preventDefault(); evt.stopPropagation(); if (debug) { timedLog("secondFinger"); } if (evt.touches.length < 2) { return; } // we need to rebind finger 1, because it may have moved! transform.x1 = evt.touches[0].pageX; transform.y1 = evt.touches[0].pageY; transform.x2 = evt.touches[1].pageX; transform.y2 = evt.touches[1].pageY; var x1 = transform.x1, y1 = transform.y1, x2 = transform.x2, y2 = transform.y2, dx = x2 - x1, dy = y2 - y1, d = Math.sqrt(dx*dx + dy*dy), a = Math.atan2(dy,dx); transform.distance = d; transform.angle = a; }
[ "function", "(", "evt", ")", "{", "evt", ".", "preventDefault", "(", ")", ";", "evt", ".", "stopPropagation", "(", ")", ";", "if", "(", "debug", ")", "{", "timedLog", "(", "\"secondFinger\"", ")", ";", "}", "if", "(", "evt", ".", "touches", ".", "length", "<", "2", ")", "{", "return", ";", "}", "transform", ".", "x1", "=", "evt", ".", "touches", "[", "0", "]", ".", "pageX", ";", "transform", ".", "y1", "=", "evt", ".", "touches", "[", "0", "]", ".", "pageY", ";", "transform", ".", "x2", "=", "evt", ".", "touches", "[", "1", "]", ".", "pageX", ";", "transform", ".", "y2", "=", "evt", ".", "touches", "[", "1", "]", ".", "pageY", ";", "var", "x1", "=", "transform", ".", "x1", ",", "y1", "=", "transform", ".", "y1", ",", "x2", "=", "transform", ".", "x2", ",", "y2", "=", "transform", ".", "y2", ",", "dx", "=", "x2", "-", "x1", ",", "dy", "=", "y2", "-", "y1", ",", "d", "=", "Math", ".", "sqrt", "(", "dx", "*", "dx", "+", "dy", "*", "dy", ")", ",", "a", "=", "Math", ".", "atan2", "(", "dy", ",", "dx", ")", ";", "transform", ".", "distance", "=", "d", ";", "transform", ".", "angle", "=", "a", ";", "}" ]
A second finger means we need to start tracking another event coordinate, which may lead to rotation and scaling updates for the element we're working for.
[ "A", "second", "finger", "means", "we", "need", "to", "start", "tracking", "another", "event", "coordinate", "which", "may", "lead", "to", "rotation", "and", "scaling", "updates", "for", "the", "element", "we", "re", "working", "for", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/lib/touchhandler.js#L141-L165
train
mozilla/webmaker-core
src/lib/touchhandler.js
function(evt) { evt.preventDefault(); evt.stopPropagation(); if (debug) { timedLog("endSecondFinger"); } if (evt.touches.length > 1) { if (debug) { timedLog("endSecondFinger - capped"); } return true; } if (debug) { timedLog("endSecondFinger - continued"); } handlers.startmark(evt); // If there are no fingers left on the screen, // we have not finished the handling return evt.touches.length !== 0; }
javascript
function(evt) { evt.preventDefault(); evt.stopPropagation(); if (debug) { timedLog("endSecondFinger"); } if (evt.touches.length > 1) { if (debug) { timedLog("endSecondFinger - capped"); } return true; } if (debug) { timedLog("endSecondFinger - continued"); } handlers.startmark(evt); // If there are no fingers left on the screen, // we have not finished the handling return evt.touches.length !== 0; }
[ "function", "(", "evt", ")", "{", "evt", ".", "preventDefault", "(", ")", ";", "evt", ".", "stopPropagation", "(", ")", ";", "if", "(", "debug", ")", "{", "timedLog", "(", "\"endSecondFinger\"", ")", ";", "}", "if", "(", "evt", ".", "touches", ".", "length", ">", "1", ")", "{", "if", "(", "debug", ")", "{", "timedLog", "(", "\"endSecondFinger - capped\"", ")", ";", "}", "return", "true", ";", "}", "if", "(", "debug", ")", "{", "timedLog", "(", "\"endSecondFinger - continued\"", ")", ";", "}", "handlers", ".", "startmark", "(", "evt", ")", ";", "return", "evt", ".", "touches", ".", "length", "!==", "0", ";", "}" ]
When the second touch event ends, we might still need to keep processing plain single touch updates.
[ "When", "the", "second", "touch", "event", "ends", "we", "might", "still", "need", "to", "keep", "processing", "plain", "single", "touch", "updates", "." ]
69fd62ea9bdcc14fcb71575393ff95baa5e6f889
https://github.com/mozilla/webmaker-core/blob/69fd62ea9bdcc14fcb71575393ff95baa5e6f889/src/lib/touchhandler.js#L197-L210
train
sanity-io/get-it
src/middleware/debug.js
tryFormat
function tryFormat(body) { try { const parsed = typeof body === 'string' ? JSON.parse(body) : body return JSON.stringify(parsed, null, 2) } catch (err) { return body } }
javascript
function tryFormat(body) { try { const parsed = typeof body === 'string' ? JSON.parse(body) : body return JSON.stringify(parsed, null, 2) } catch (err) { return body } }
[ "function", "tryFormat", "(", "body", ")", "{", "try", "{", "const", "parsed", "=", "typeof", "body", "===", "'string'", "?", "JSON", ".", "parse", "(", "body", ")", ":", "body", "return", "JSON", ".", "stringify", "(", "parsed", ",", "null", ",", "2", ")", "}", "catch", "(", "err", ")", "{", "return", "body", "}", "}" ]
Attempt pretty-formatting JSON
[ "Attempt", "pretty", "-", "formatting", "JSON" ]
765ff1e0203e5ad0109e2f959f5c6008b47e8103
https://github.com/sanity-io/get-it/blob/765ff1e0203e5ad0109e2f959f5c6008b47e8103/src/middleware/debug.js#L94-L101
train
cedx/lcov.js
example/main.js
formatReport
function formatReport() { // eslint-disable-line no-unused-vars const lineCoverage = new LineCoverage(2, 2, [ new LineData(6, 2, 'PF4Rz2r7RTliO9u6bZ7h6g'), new LineData(7, 2, 'yGMB6FhEEAd8OyASe3Ni1w') ]); const record = new Record('/home/cedx/lcov.js/fixture.js', { functions: new FunctionCoverage(1, 1), lines: lineCoverage }); const report = new Report('Example', [record]); console.log(report.toString()); }
javascript
function formatReport() { // eslint-disable-line no-unused-vars const lineCoverage = new LineCoverage(2, 2, [ new LineData(6, 2, 'PF4Rz2r7RTliO9u6bZ7h6g'), new LineData(7, 2, 'yGMB6FhEEAd8OyASe3Ni1w') ]); const record = new Record('/home/cedx/lcov.js/fixture.js', { functions: new FunctionCoverage(1, 1), lines: lineCoverage }); const report = new Report('Example', [record]); console.log(report.toString()); }
[ "function", "formatReport", "(", ")", "{", "const", "lineCoverage", "=", "new", "LineCoverage", "(", "2", ",", "2", ",", "[", "new", "LineData", "(", "6", ",", "2", ",", "'PF4Rz2r7RTliO9u6bZ7h6g'", ")", ",", "new", "LineData", "(", "7", ",", "2", ",", "'yGMB6FhEEAd8OyASe3Ni1w'", ")", "]", ")", ";", "const", "record", "=", "new", "Record", "(", "'/home/cedx/lcov.js/fixture.js'", ",", "{", "functions", ":", "new", "FunctionCoverage", "(", "1", ",", "1", ")", ",", "lines", ":", "lineCoverage", "}", ")", ";", "const", "report", "=", "new", "Report", "(", "'Example'", ",", "[", "record", "]", ")", ";", "console", ".", "log", "(", "report", ".", "toString", "(", ")", ")", ";", "}" ]
Formats coverage data as LCOV report.
[ "Formats", "coverage", "data", "as", "LCOV", "report", "." ]
63a56e188478753fe3b8c12721b8a19f858258c4
https://github.com/cedx/lcov.js/blob/63a56e188478753fe3b8c12721b8a19f858258c4/example/main.js#L5-L18
train
cedx/lcov.js
example/main.js
parseReport
async function parseReport() { // eslint-disable-line no-unused-vars try { const coverage = await promises.readFile('lcov.info', 'utf8'); const report = Report.fromCoverage(coverage); console.log(`The coverage report contains ${report.records.length} records:`); console.log(report.toJSON()); } catch (error) { console.log(`An error occurred: ${error.message}`); } }
javascript
async function parseReport() { // eslint-disable-line no-unused-vars try { const coverage = await promises.readFile('lcov.info', 'utf8'); const report = Report.fromCoverage(coverage); console.log(`The coverage report contains ${report.records.length} records:`); console.log(report.toJSON()); } catch (error) { console.log(`An error occurred: ${error.message}`); } }
[ "async", "function", "parseReport", "(", ")", "{", "try", "{", "const", "coverage", "=", "await", "promises", ".", "readFile", "(", "'lcov.info'", ",", "'utf8'", ")", ";", "const", "report", "=", "Report", ".", "fromCoverage", "(", "coverage", ")", ";", "console", ".", "log", "(", "`", "${", "report", ".", "records", ".", "length", "}", "`", ")", ";", "console", ".", "log", "(", "report", ".", "toJSON", "(", ")", ")", ";", "}", "catch", "(", "error", ")", "{", "console", ".", "log", "(", "`", "${", "error", ".", "message", "}", "`", ")", ";", "}", "}" ]
Parses a LCOV report to coverage data.
[ "Parses", "a", "LCOV", "report", "to", "coverage", "data", "." ]
63a56e188478753fe3b8c12721b8a19f858258c4
https://github.com/cedx/lcov.js/blob/63a56e188478753fe3b8c12721b8a19f858258c4/example/main.js#L21-L32
train
reklatsmasters/saslprep
lib/util.js
range
function range(from, to) { // TODO: make this inlined. const list = new Array(to - from + 1); for (let i = 0; i < list.length; i += 1) { list[i] = from + i; } return list; }
javascript
function range(from, to) { // TODO: make this inlined. const list = new Array(to - from + 1); for (let i = 0; i < list.length; i += 1) { list[i] = from + i; } return list; }
[ "function", "range", "(", "from", ",", "to", ")", "{", "const", "list", "=", "new", "Array", "(", "to", "-", "from", "+", "1", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "+=", "1", ")", "{", "list", "[", "i", "]", "=", "from", "+", "i", ";", "}", "return", "list", ";", "}" ]
Create an array of numbers. @param {number} from @param {number} to @returns {number[]}
[ "Create", "an", "array", "of", "numbers", "." ]
4ad8884b461a6a8e496d6e648ad5da0a1b43cb42
https://github.com/reklatsmasters/saslprep/blob/4ad8884b461a6a8e496d6e648ad5da0a1b43cb42/lib/util.js#L9-L17
train
jpodwys/cache-service-cache-module
cacheModule.js
setupBrowserStorage
function setupBrowserStorage(){ if(browser || storageMock){ if(storageMock){ store = storageMock; storageKey = 'cache-module-storage-mock'; } else{ var storageType = (config.storage === 'local' || config.storage === 'session') ? config.storage : null; store = (storageType && typeof Storage !== void(0)) ? window[storageType + 'Storage'] : false; storageKey = (storageType) ? self.type + '-' + storageType + '-storage' : null; } if(store){ var db = store.getItem(storageKey); try { cache = JSON.parse(db) || cache; } catch (err) { /* Do nothing */ } } // If storageType is set but store is not, the desired storage mechanism was not available else if(storageType){ log(true, 'Browser storage is not supported by this browser. Defaulting to an in-memory cache.'); } } }
javascript
function setupBrowserStorage(){ if(browser || storageMock){ if(storageMock){ store = storageMock; storageKey = 'cache-module-storage-mock'; } else{ var storageType = (config.storage === 'local' || config.storage === 'session') ? config.storage : null; store = (storageType && typeof Storage !== void(0)) ? window[storageType + 'Storage'] : false; storageKey = (storageType) ? self.type + '-' + storageType + '-storage' : null; } if(store){ var db = store.getItem(storageKey); try { cache = JSON.parse(db) || cache; } catch (err) { /* Do nothing */ } } // If storageType is set but store is not, the desired storage mechanism was not available else if(storageType){ log(true, 'Browser storage is not supported by this browser. Defaulting to an in-memory cache.'); } } }
[ "function", "setupBrowserStorage", "(", ")", "{", "if", "(", "browser", "||", "storageMock", ")", "{", "if", "(", "storageMock", ")", "{", "store", "=", "storageMock", ";", "storageKey", "=", "'cache-module-storage-mock'", ";", "}", "else", "{", "var", "storageType", "=", "(", "config", ".", "storage", "===", "'local'", "||", "config", ".", "storage", "===", "'session'", ")", "?", "config", ".", "storage", ":", "null", ";", "store", "=", "(", "storageType", "&&", "typeof", "Storage", "!==", "void", "(", "0", ")", ")", "?", "window", "[", "storageType", "+", "'Storage'", "]", ":", "false", ";", "storageKey", "=", "(", "storageType", ")", "?", "self", ".", "type", "+", "'-'", "+", "storageType", "+", "'-storage'", ":", "null", ";", "}", "if", "(", "store", ")", "{", "var", "db", "=", "store", ".", "getItem", "(", "storageKey", ")", ";", "try", "{", "cache", "=", "JSON", ".", "parse", "(", "db", ")", "||", "cache", ";", "}", "catch", "(", "err", ")", "{", "}", "}", "else", "if", "(", "storageType", ")", "{", "log", "(", "true", ",", "'Browser storage is not supported by this browser. Defaulting to an in-memory cache.'", ")", ";", "}", "}", "}" ]
Enable browser storage if desired and available
[ "Enable", "browser", "storage", "if", "desired", "and", "available" ]
d81b4efe255922d0a2cd678eee745e96ac8a11c1
https://github.com/jpodwys/cache-service-cache-module/blob/d81b4efe255922d0a2cd678eee745e96ac8a11c1/cacheModule.js#L191-L213
train
jpodwys/cache-service-cache-module
cacheModule.js
overwriteBrowserStorage
function overwriteBrowserStorage(){ if((browser && store) || storageMock){ var db = cache; try { db = JSON.stringify(db); store.setItem(storageKey, db); } catch (err) { /* Do nothing */ } } }
javascript
function overwriteBrowserStorage(){ if((browser && store) || storageMock){ var db = cache; try { db = JSON.stringify(db); store.setItem(storageKey, db); } catch (err) { /* Do nothing */ } } }
[ "function", "overwriteBrowserStorage", "(", ")", "{", "if", "(", "(", "browser", "&&", "store", ")", "||", "storageMock", ")", "{", "var", "db", "=", "cache", ";", "try", "{", "db", "=", "JSON", ".", "stringify", "(", "db", ")", ";", "store", ".", "setItem", "(", "storageKey", ",", "db", ")", ";", "}", "catch", "(", "err", ")", "{", "}", "}", "}" ]
Overwrite namespaced browser storage with current cache
[ "Overwrite", "namespaced", "browser", "storage", "with", "current", "cache" ]
d81b4efe255922d0a2cd678eee745e96ac8a11c1
https://github.com/jpodwys/cache-service-cache-module/blob/d81b4efe255922d0a2cd678eee745e96ac8a11c1/cacheModule.js#L218-L226
train
jpodwys/cache-service-cache-module
cacheModule.js
handleRefreshResponse
function handleRefreshResponse (key, data, err, response) { if(!err) { this.set(key, response, (data.lifeSpan / 1000), data.refresh, function(){}); } }
javascript
function handleRefreshResponse (key, data, err, response) { if(!err) { this.set(key, response, (data.lifeSpan / 1000), data.refresh, function(){}); } }
[ "function", "handleRefreshResponse", "(", "key", ",", "data", ",", "err", ",", "response", ")", "{", "if", "(", "!", "err", ")", "{", "this", ".", "set", "(", "key", ",", "response", ",", "(", "data", ".", "lifeSpan", "/", "1000", ")", ",", "data", ".", "refresh", ",", "function", "(", ")", "{", "}", ")", ";", "}", "}" ]
Handle the refresh callback from the consumer, save the data to redis. @param {string} key The key used to save. @param {Object} data refresh keys data. @param {Error|null} err consumer callback failure. @param {*} response The consumer response.
[ "Handle", "the", "refresh", "callback", "from", "the", "consumer", "save", "the", "data", "to", "redis", "." ]
d81b4efe255922d0a2cd678eee745e96ac8a11c1
https://github.com/jpodwys/cache-service-cache-module/blob/d81b4efe255922d0a2cd678eee745e96ac8a11c1/cacheModule.js#L270-L274
train
jpodwys/cache-service-cache-module
cacheModule.js
log
function log(isError, message, data){ if(self.verbose || isError){ if(data) console.log(self.type + ': ' + message, data); else console.log(self.type + message); } }
javascript
function log(isError, message, data){ if(self.verbose || isError){ if(data) console.log(self.type + ': ' + message, data); else console.log(self.type + message); } }
[ "function", "log", "(", "isError", ",", "message", ",", "data", ")", "{", "if", "(", "self", ".", "verbose", "||", "isError", ")", "{", "if", "(", "data", ")", "console", ".", "log", "(", "self", ".", "type", "+", "': '", "+", "message", ",", "data", ")", ";", "else", "console", ".", "log", "(", "self", ".", "type", "+", "message", ")", ";", "}", "}" ]
Error logging logic @param {boolean} isError @param {string} message @param {object} data
[ "Error", "logging", "logic" ]
d81b4efe255922d0a2cd678eee745e96ac8a11c1
https://github.com/jpodwys/cache-service-cache-module/blob/d81b4efe255922d0a2cd678eee745e96ac8a11c1/cacheModule.js#L303-L308
train
Nicklason/node-bptf-listings
lib/webrequest.js
WebRequest
function WebRequest (options, callback) { request(options, function (err, response, body) { if (err) { return callback(err); } callback(null, body); }); }
javascript
function WebRequest (options, callback) { request(options, function (err, response, body) { if (err) { return callback(err); } callback(null, body); }); }
[ "function", "WebRequest", "(", "options", ",", "callback", ")", "{", "request", "(", "options", ",", "function", "(", "err", ",", "response", ",", "body", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "callback", "(", "null", ",", "body", ")", ";", "}", ")", ";", "}" ]
Sends a request to the Steam api @param {object} options Request options @param {function} callback Function to call when done
[ "Sends", "a", "request", "to", "the", "Steam", "api" ]
8ed38a4e2457603ec2941991e8af924531e8389b
https://github.com/Nicklason/node-bptf-listings/blob/8ed38a4e2457603ec2941991e8af924531e8389b/lib/webrequest.js#L10-L18
train
glennjones/microformat-shiv
microformat-shiv.js
function(options) { var out = this.formatEmpty(), data = [], rels; this.init(); options = (options)? options : {}; this.mergeOptions(options); this.getDOMContext( options ); // if we do not have any context create error if(!this.rootNode || !this.document){ this.errors.push(this.noContentErr); }else{ // only parse h-* microformats if we need to // this is added to speed up parsing if(this.hasMicroformats(this.rootNode, options)){ this.prepareDOM( options ); if(this.options.filters.length > 0){ // parse flat list of items var newRootNode = this.findFilterNodes(this.rootNode, this.options.filters); data = this.walkRoot(newRootNode); }else{ // parse whole document from root data = this.walkRoot(this.rootNode); } out.items = data; // don't clear-up DOM if it was cloned if(modules.domUtils.canCloneDocument(this.document) === false){ this.clearUpDom(this.rootNode); } } // find any rels if(this.findRels){ rels = this.findRels(this.rootNode); out.rels = rels.rels; out['rel-urls'] = rels['rel-urls']; } } if(this.errors.length > 0){ return this.formatError(); } return out; }
javascript
function(options) { var out = this.formatEmpty(), data = [], rels; this.init(); options = (options)? options : {}; this.mergeOptions(options); this.getDOMContext( options ); // if we do not have any context create error if(!this.rootNode || !this.document){ this.errors.push(this.noContentErr); }else{ // only parse h-* microformats if we need to // this is added to speed up parsing if(this.hasMicroformats(this.rootNode, options)){ this.prepareDOM( options ); if(this.options.filters.length > 0){ // parse flat list of items var newRootNode = this.findFilterNodes(this.rootNode, this.options.filters); data = this.walkRoot(newRootNode); }else{ // parse whole document from root data = this.walkRoot(this.rootNode); } out.items = data; // don't clear-up DOM if it was cloned if(modules.domUtils.canCloneDocument(this.document) === false){ this.clearUpDom(this.rootNode); } } // find any rels if(this.findRels){ rels = this.findRels(this.rootNode); out.rels = rels.rels; out['rel-urls'] = rels['rel-urls']; } } if(this.errors.length > 0){ return this.formatError(); } return out; }
[ "function", "(", "options", ")", "{", "var", "out", "=", "this", ".", "formatEmpty", "(", ")", ",", "data", "=", "[", "]", ",", "rels", ";", "this", ".", "init", "(", ")", ";", "options", "=", "(", "options", ")", "?", "options", ":", "{", "}", ";", "this", ".", "mergeOptions", "(", "options", ")", ";", "this", ".", "getDOMContext", "(", "options", ")", ";", "if", "(", "!", "this", ".", "rootNode", "||", "!", "this", ".", "document", ")", "{", "this", ".", "errors", ".", "push", "(", "this", ".", "noContentErr", ")", ";", "}", "else", "{", "if", "(", "this", ".", "hasMicroformats", "(", "this", ".", "rootNode", ",", "options", ")", ")", "{", "this", ".", "prepareDOM", "(", "options", ")", ";", "if", "(", "this", ".", "options", ".", "filters", ".", "length", ">", "0", ")", "{", "var", "newRootNode", "=", "this", ".", "findFilterNodes", "(", "this", ".", "rootNode", ",", "this", ".", "options", ".", "filters", ")", ";", "data", "=", "this", ".", "walkRoot", "(", "newRootNode", ")", ";", "}", "else", "{", "data", "=", "this", ".", "walkRoot", "(", "this", ".", "rootNode", ")", ";", "}", "out", ".", "items", "=", "data", ";", "if", "(", "modules", ".", "domUtils", ".", "canCloneDocument", "(", "this", ".", "document", ")", "===", "false", ")", "{", "this", ".", "clearUpDom", "(", "this", ".", "rootNode", ")", ";", "}", "}", "if", "(", "this", ".", "findRels", ")", "{", "rels", "=", "this", ".", "findRels", "(", "this", ".", "rootNode", ")", ";", "out", ".", "rels", "=", "rels", ".", "rels", ";", "out", "[", "'rel-urls'", "]", "=", "rels", "[", "'rel-urls'", "]", ";", "}", "}", "if", "(", "this", ".", "errors", ".", "length", ">", "0", ")", "{", "return", "this", ".", "formatError", "(", ")", ";", "}", "return", "out", ";", "}" ]
internal parse function @param {Object} options @return {Object}
[ "internal", "parse", "function" ]
90c5ea5e43ae95fc460aef79f8c19832c6f1dc26
https://github.com/glennjones/microformat-shiv/blob/90c5ea5e43ae95fc460aef79f8c19832c6f1dc26/microformat-shiv.js#L70-L119
train
glennjones/microformat-shiv
microformat-shiv.js
function(node, options) { this.init(); options = (options)? options : {}; if(node){ return this.getParentTreeWalk(node, options); }else{ this.errors.push(this.noContentErr); return this.formatError(); } }
javascript
function(node, options) { this.init(); options = (options)? options : {}; if(node){ return this.getParentTreeWalk(node, options); }else{ this.errors.push(this.noContentErr); return this.formatError(); } }
[ "function", "(", "node", ",", "options", ")", "{", "this", ".", "init", "(", ")", ";", "options", "=", "(", "options", ")", "?", "options", ":", "{", "}", ";", "if", "(", "node", ")", "{", "return", "this", ".", "getParentTreeWalk", "(", "node", ",", "options", ")", ";", "}", "else", "{", "this", ".", "errors", ".", "push", "(", "this", ".", "noContentErr", ")", ";", "return", "this", ".", "formatError", "(", ")", ";", "}", "}" ]
parse to get parent microformat of passed node @param {DOM Node} node @param {Object} options @return {Object}
[ "parse", "to", "get", "parent", "microformat", "of", "passed", "node" ]
90c5ea5e43ae95fc460aef79f8c19832c6f1dc26
https://github.com/glennjones/microformat-shiv/blob/90c5ea5e43ae95fc460aef79f8c19832c6f1dc26/microformat-shiv.js#L129-L139
train
glennjones/microformat-shiv
microformat-shiv.js
function( options ) { var out = {}, items, classItems, x, i; this.init(); options = (options)? options : {}; this.getDOMContext( options ); // if we do not have any context create error if(!this.rootNode || !this.document){ return {'errors': [this.noContentErr]}; }else{ items = this.findRootNodes( this.rootNode, true ); i = items.length; while(i--) { classItems = modules.domUtils.getAttributeList(items[i], 'class'); x = classItems.length; while(x--) { // find v2 names if(modules.utils.startWith( classItems[x], 'h-' )){ this.appendCount(classItems[x], 1, out); } // find v1 names for(var key in modules.maps) { // dont double count if v1 and v2 roots are present if(modules.maps[key].root === classItems[x] && classItems.indexOf(key) === -1) { this.appendCount(key, 1, out); } } } } var relCount = this.countRels( this.rootNode ); if(relCount > 0){ out.rels = relCount; } return out; } }
javascript
function( options ) { var out = {}, items, classItems, x, i; this.init(); options = (options)? options : {}; this.getDOMContext( options ); // if we do not have any context create error if(!this.rootNode || !this.document){ return {'errors': [this.noContentErr]}; }else{ items = this.findRootNodes( this.rootNode, true ); i = items.length; while(i--) { classItems = modules.domUtils.getAttributeList(items[i], 'class'); x = classItems.length; while(x--) { // find v2 names if(modules.utils.startWith( classItems[x], 'h-' )){ this.appendCount(classItems[x], 1, out); } // find v1 names for(var key in modules.maps) { // dont double count if v1 and v2 roots are present if(modules.maps[key].root === classItems[x] && classItems.indexOf(key) === -1) { this.appendCount(key, 1, out); } } } } var relCount = this.countRels( this.rootNode ); if(relCount > 0){ out.rels = relCount; } return out; } }
[ "function", "(", "options", ")", "{", "var", "out", "=", "{", "}", ",", "items", ",", "classItems", ",", "x", ",", "i", ";", "this", ".", "init", "(", ")", ";", "options", "=", "(", "options", ")", "?", "options", ":", "{", "}", ";", "this", ".", "getDOMContext", "(", "options", ")", ";", "if", "(", "!", "this", ".", "rootNode", "||", "!", "this", ".", "document", ")", "{", "return", "{", "'errors'", ":", "[", "this", ".", "noContentErr", "]", "}", ";", "}", "else", "{", "items", "=", "this", ".", "findRootNodes", "(", "this", ".", "rootNode", ",", "true", ")", ";", "i", "=", "items", ".", "length", ";", "while", "(", "i", "--", ")", "{", "classItems", "=", "modules", ".", "domUtils", ".", "getAttributeList", "(", "items", "[", "i", "]", ",", "'class'", ")", ";", "x", "=", "classItems", ".", "length", ";", "while", "(", "x", "--", ")", "{", "if", "(", "modules", ".", "utils", ".", "startWith", "(", "classItems", "[", "x", "]", ",", "'h-'", ")", ")", "{", "this", ".", "appendCount", "(", "classItems", "[", "x", "]", ",", "1", ",", "out", ")", ";", "}", "for", "(", "var", "key", "in", "modules", ".", "maps", ")", "{", "if", "(", "modules", ".", "maps", "[", "key", "]", ".", "root", "===", "classItems", "[", "x", "]", "&&", "classItems", ".", "indexOf", "(", "key", ")", "===", "-", "1", ")", "{", "this", ".", "appendCount", "(", "key", ",", "1", ",", "out", ")", ";", "}", "}", "}", "}", "var", "relCount", "=", "this", ".", "countRels", "(", "this", ".", "rootNode", ")", ";", "if", "(", "relCount", ">", "0", ")", "{", "out", ".", "rels", "=", "relCount", ";", "}", "return", "out", ";", "}", "}" ]
get the count of microformats @param {DOM Node} rootNode @return {Int}
[ "get", "the", "count", "of", "microformats" ]
90c5ea5e43ae95fc460aef79f8c19832c6f1dc26
https://github.com/glennjones/microformat-shiv/blob/90c5ea5e43ae95fc460aef79f8c19832c6f1dc26/microformat-shiv.js#L148-L190
train
glennjones/microformat-shiv
microformat-shiv.js
function( node, options ) { var classes, i; if(!node){ return false; } // if documemt gets topmost node node = modules.domUtils.getTopMostNode( node ); // look for h-* microformats classes = this.getUfClassNames(node); if(options && options.filters && modules.utils.isArray(options.filters)){ i = options.filters.length; while(i--) { if(classes.root.indexOf(options.filters[i]) > -1){ return true; } } return false; }else{ return (classes.root.length > 0); } }
javascript
function( node, options ) { var classes, i; if(!node){ return false; } // if documemt gets topmost node node = modules.domUtils.getTopMostNode( node ); // look for h-* microformats classes = this.getUfClassNames(node); if(options && options.filters && modules.utils.isArray(options.filters)){ i = options.filters.length; while(i--) { if(classes.root.indexOf(options.filters[i]) > -1){ return true; } } return false; }else{ return (classes.root.length > 0); } }
[ "function", "(", "node", ",", "options", ")", "{", "var", "classes", ",", "i", ";", "if", "(", "!", "node", ")", "{", "return", "false", ";", "}", "node", "=", "modules", ".", "domUtils", ".", "getTopMostNode", "(", "node", ")", ";", "classes", "=", "this", ".", "getUfClassNames", "(", "node", ")", ";", "if", "(", "options", "&&", "options", ".", "filters", "&&", "modules", ".", "utils", ".", "isArray", "(", "options", ".", "filters", ")", ")", "{", "i", "=", "options", ".", "filters", ".", "length", ";", "while", "(", "i", "--", ")", "{", "if", "(", "classes", ".", "root", ".", "indexOf", "(", "options", ".", "filters", "[", "i", "]", ")", ">", "-", "1", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "else", "{", "return", "(", "classes", ".", "root", ".", "length", ">", "0", ")", ";", "}", "}" ]
does a node have a class that marks it as a microformats root @param {DOM Node} node @param {Objecte} options @return {Boolean}
[ "does", "a", "node", "have", "a", "class", "that", "marks", "it", "as", "a", "microformats", "root" ]
90c5ea5e43ae95fc460aef79f8c19832c6f1dc26
https://github.com/glennjones/microformat-shiv/blob/90c5ea5e43ae95fc460aef79f8c19832c6f1dc26/microformat-shiv.js#L200-L224
train
glennjones/microformat-shiv
microformat-shiv.js
function( node, options ) { var items, i; if(!node){ return false; } // if browser based documemt get topmost node node = modules.domUtils.getTopMostNode( node ); // returns all microformat roots items = this.findRootNodes( node, true ); if(options && options.filters && modules.utils.isArray(options.filters)){ i = items.length; while(i--) { if( this.isMicroformat( items[i], options ) ){ return true; } } return false; }else{ return (items.length > 0); } }
javascript
function( node, options ) { var items, i; if(!node){ return false; } // if browser based documemt get topmost node node = modules.domUtils.getTopMostNode( node ); // returns all microformat roots items = this.findRootNodes( node, true ); if(options && options.filters && modules.utils.isArray(options.filters)){ i = items.length; while(i--) { if( this.isMicroformat( items[i], options ) ){ return true; } } return false; }else{ return (items.length > 0); } }
[ "function", "(", "node", ",", "options", ")", "{", "var", "items", ",", "i", ";", "if", "(", "!", "node", ")", "{", "return", "false", ";", "}", "node", "=", "modules", ".", "domUtils", ".", "getTopMostNode", "(", "node", ")", ";", "items", "=", "this", ".", "findRootNodes", "(", "node", ",", "true", ")", ";", "if", "(", "options", "&&", "options", ".", "filters", "&&", "modules", ".", "utils", ".", "isArray", "(", "options", ".", "filters", ")", ")", "{", "i", "=", "items", ".", "length", ";", "while", "(", "i", "--", ")", "{", "if", "(", "this", ".", "isMicroformat", "(", "items", "[", "i", "]", ",", "options", ")", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}", "else", "{", "return", "(", "items", ".", "length", ">", "0", ")", ";", "}", "}" ]
does a node or its children have microformats @param {DOM Node} node @param {Objecte} options @return {Boolean}
[ "does", "a", "node", "or", "its", "children", "have", "microformats" ]
90c5ea5e43ae95fc460aef79f8c19832c6f1dc26
https://github.com/glennjones/microformat-shiv/blob/90c5ea5e43ae95fc460aef79f8c19832c6f1dc26/microformat-shiv.js#L234-L258
train
glennjones/microformat-shiv
microformat-shiv.js
function( maps ){ maps.forEach(function(map){ if(map && map.root && map.name && map.properties){ modules.maps[map.name] = JSON.parse(JSON.stringify(map)); } }); }
javascript
function( maps ){ maps.forEach(function(map){ if(map && map.root && map.name && map.properties){ modules.maps[map.name] = JSON.parse(JSON.stringify(map)); } }); }
[ "function", "(", "maps", ")", "{", "maps", ".", "forEach", "(", "function", "(", "map", ")", "{", "if", "(", "map", "&&", "map", ".", "root", "&&", "map", ".", "name", "&&", "map", ".", "properties", ")", "{", "modules", ".", "maps", "[", "map", ".", "name", "]", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "map", ")", ")", ";", "}", "}", ")", ";", "}" ]
add a new v1 mapping object to parser @param {Array} maps
[ "add", "a", "new", "v1", "mapping", "object", "to", "parser" ]
90c5ea5e43ae95fc460aef79f8c19832c6f1dc26
https://github.com/glennjones/microformat-shiv/blob/90c5ea5e43ae95fc460aef79f8c19832c6f1dc26/microformat-shiv.js#L266-L272
train
glennjones/microformat-shiv
microformat-shiv.js
function (node, options, recursive) { options = (options)? options : {}; // recursive calls if (recursive === undefined) { if (node.parentNode && node.nodeName !== 'HTML'){ return this.getParentTreeWalk(node.parentNode, options, true); }else{ return this.formatEmpty(); } } if (node !== null && node !== undefined && node.parentNode) { if (this.isMicroformat( node, options )) { // if we have a match return microformat options.node = node; return this.get( options ); }else{ return this.getParentTreeWalk(node.parentNode, options, true); } }else{ return this.formatEmpty(); } }
javascript
function (node, options, recursive) { options = (options)? options : {}; // recursive calls if (recursive === undefined) { if (node.parentNode && node.nodeName !== 'HTML'){ return this.getParentTreeWalk(node.parentNode, options, true); }else{ return this.formatEmpty(); } } if (node !== null && node !== undefined && node.parentNode) { if (this.isMicroformat( node, options )) { // if we have a match return microformat options.node = node; return this.get( options ); }else{ return this.getParentTreeWalk(node.parentNode, options, true); } }else{ return this.formatEmpty(); } }
[ "function", "(", "node", ",", "options", ",", "recursive", ")", "{", "options", "=", "(", "options", ")", "?", "options", ":", "{", "}", ";", "if", "(", "recursive", "===", "undefined", ")", "{", "if", "(", "node", ".", "parentNode", "&&", "node", ".", "nodeName", "!==", "'HTML'", ")", "{", "return", "this", ".", "getParentTreeWalk", "(", "node", ".", "parentNode", ",", "options", ",", "true", ")", ";", "}", "else", "{", "return", "this", ".", "formatEmpty", "(", ")", ";", "}", "}", "if", "(", "node", "!==", "null", "&&", "node", "!==", "undefined", "&&", "node", ".", "parentNode", ")", "{", "if", "(", "this", ".", "isMicroformat", "(", "node", ",", "options", ")", ")", "{", "options", ".", "node", "=", "node", ";", "return", "this", ".", "get", "(", "options", ")", ";", "}", "else", "{", "return", "this", ".", "getParentTreeWalk", "(", "node", ".", "parentNode", ",", "options", ",", "true", ")", ";", "}", "}", "else", "{", "return", "this", ".", "formatEmpty", "(", ")", ";", "}", "}" ]
internal parse to get parent microformats by walking up the tree @param {DOM Node} node @param {Object} options @param {Int} recursive @return {Object}
[ "internal", "parse", "to", "get", "parent", "microformats", "by", "walking", "up", "the", "tree" ]
90c5ea5e43ae95fc460aef79f8c19832c6f1dc26
https://github.com/glennjones/microformat-shiv/blob/90c5ea5e43ae95fc460aef79f8c19832c6f1dc26/microformat-shiv.js#L283-L305
train
glennjones/microformat-shiv
microformat-shiv.js
function( options ){ var baseTag, href; // use current document to define baseUrl, try/catch needed for IE10+ error try { if (!options.baseUrl && this.document && this.document.location) { this.options.baseUrl = this.document.location.href; } } catch (e) { // there is no alt action } // find base tag to set baseUrl baseTag = modules.domUtils.querySelector(this.document,'base'); if(baseTag) { href = modules.domUtils.getAttribute(baseTag, 'href'); if(href){ this.options.baseUrl = href; } } // get path to rootNode // then clone document // then reset the rootNode to its cloned version in a new document var path, newDocument, newRootNode; path = modules.domUtils.getNodePath(this.rootNode); newDocument = modules.domUtils.cloneDocument(this.document); newRootNode = modules.domUtils.getNodeByPath(newDocument, path); // check results as early IE fails if(newDocument && newRootNode){ this.document = newDocument; this.rootNode = newRootNode; } // add includes if(this.addIncludes){ this.addIncludes( this.document ); } return (this.rootNode && this.document); }
javascript
function( options ){ var baseTag, href; // use current document to define baseUrl, try/catch needed for IE10+ error try { if (!options.baseUrl && this.document && this.document.location) { this.options.baseUrl = this.document.location.href; } } catch (e) { // there is no alt action } // find base tag to set baseUrl baseTag = modules.domUtils.querySelector(this.document,'base'); if(baseTag) { href = modules.domUtils.getAttribute(baseTag, 'href'); if(href){ this.options.baseUrl = href; } } // get path to rootNode // then clone document // then reset the rootNode to its cloned version in a new document var path, newDocument, newRootNode; path = modules.domUtils.getNodePath(this.rootNode); newDocument = modules.domUtils.cloneDocument(this.document); newRootNode = modules.domUtils.getNodeByPath(newDocument, path); // check results as early IE fails if(newDocument && newRootNode){ this.document = newDocument; this.rootNode = newRootNode; } // add includes if(this.addIncludes){ this.addIncludes( this.document ); } return (this.rootNode && this.document); }
[ "function", "(", "options", ")", "{", "var", "baseTag", ",", "href", ";", "try", "{", "if", "(", "!", "options", ".", "baseUrl", "&&", "this", ".", "document", "&&", "this", ".", "document", ".", "location", ")", "{", "this", ".", "options", ".", "baseUrl", "=", "this", ".", "document", ".", "location", ".", "href", ";", "}", "}", "catch", "(", "e", ")", "{", "}", "baseTag", "=", "modules", ".", "domUtils", ".", "querySelector", "(", "this", ".", "document", ",", "'base'", ")", ";", "if", "(", "baseTag", ")", "{", "href", "=", "modules", ".", "domUtils", ".", "getAttribute", "(", "baseTag", ",", "'href'", ")", ";", "if", "(", "href", ")", "{", "this", ".", "options", ".", "baseUrl", "=", "href", ";", "}", "}", "var", "path", ",", "newDocument", ",", "newRootNode", ";", "path", "=", "modules", ".", "domUtils", ".", "getNodePath", "(", "this", ".", "rootNode", ")", ";", "newDocument", "=", "modules", ".", "domUtils", ".", "cloneDocument", "(", "this", ".", "document", ")", ";", "newRootNode", "=", "modules", ".", "domUtils", ".", "getNodeByPath", "(", "newDocument", ",", "path", ")", ";", "if", "(", "newDocument", "&&", "newRootNode", ")", "{", "this", ".", "document", "=", "newDocument", ";", "this", ".", "rootNode", "=", "newRootNode", ";", "}", "if", "(", "this", ".", "addIncludes", ")", "{", "this", ".", "addIncludes", "(", "this", ".", "document", ")", ";", "}", "return", "(", "this", ".", "rootNode", "&&", "this", ".", "document", ")", ";", "}" ]
prepares DOM before the parse begins @param {Object} options @return {Boolean}
[ "prepares", "DOM", "before", "the", "parse", "begins" ]
90c5ea5e43ae95fc460aef79f8c19832c6f1dc26
https://github.com/glennjones/microformat-shiv/blob/90c5ea5e43ae95fc460aef79f8c19832c6f1dc26/microformat-shiv.js#L327-L373
train