id
int32
0
58k
repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
43,700
simonguo/hbook
lib/utils/git.js
resolveFileFromGit
function resolveFileFromGit(giturl) { if (_.isString(giturl)) giturl = parseGitUrl(giturl); if (!giturl) return Q(null); // Clone or get from cache return cloneGitRepo(giturl.host, giturl.ref) .then(function(repo) { // Resolve relative path return path.resolve(repo, giturl.filepath); }); }
javascript
function resolveFileFromGit(giturl) { if (_.isString(giturl)) giturl = parseGitUrl(giturl); if (!giturl) return Q(null); // Clone or get from cache return cloneGitRepo(giturl.host, giturl.ref) .then(function(repo) { // Resolve relative path return path.resolve(repo, giturl.filepath); }); }
[ "function", "resolveFileFromGit", "(", "giturl", ")", "{", "if", "(", "_", ".", "isString", "(", "giturl", ")", ")", "giturl", "=", "parseGitUrl", "(", "giturl", ")", ";", "if", "(", "!", "giturl", ")", "return", "Q", "(", "null", ")", ";", "// Clone or get from cache", "return", "cloneGitRepo", "(", "giturl", ".", "host", ",", "giturl", ".", "ref", ")", ".", "then", "(", "function", "(", "repo", ")", "{", "// Resolve relative path", "return", "path", ".", "resolve", "(", "repo", ",", "giturl", ".", "filepath", ")", ";", "}", ")", ";", "}" ]
Get file from a git repo
[ "Get", "file", "from", "a", "git", "repo" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/utils/git.js#L92-L103
43,701
simonguo/hbook
lib/utils/git.js
resolveGitRoot
function resolveGitRoot(filepath) { var relativeToGit, repoId; // No git repo cloned, or file is not in a git repository if (!GIT_TMP || !pathUtil.isInRoot(GIT_TMP, filepath)) return null; // Extract first directory (is the repo id) relativeToGit = path.relative(GIT_TMP, filepath); repoId = _.first(relativeToGit.split(path.sep)); if (!repoId) return; // Return an absolute file return path.resolve(GIT_TMP, repoId); }
javascript
function resolveGitRoot(filepath) { var relativeToGit, repoId; // No git repo cloned, or file is not in a git repository if (!GIT_TMP || !pathUtil.isInRoot(GIT_TMP, filepath)) return null; // Extract first directory (is the repo id) relativeToGit = path.relative(GIT_TMP, filepath); repoId = _.first(relativeToGit.split(path.sep)); if (!repoId) return; // Return an absolute file return path.resolve(GIT_TMP, repoId); }
[ "function", "resolveGitRoot", "(", "filepath", ")", "{", "var", "relativeToGit", ",", "repoId", ";", "// No git repo cloned, or file is not in a git repository", "if", "(", "!", "GIT_TMP", "||", "!", "pathUtil", ".", "isInRoot", "(", "GIT_TMP", ",", "filepath", ")", ")", "return", "null", ";", "// Extract first directory (is the repo id)", "relativeToGit", "=", "path", ".", "relative", "(", "GIT_TMP", ",", "filepath", ")", ";", "repoId", "=", "_", ".", "first", "(", "relativeToGit", ".", "split", "(", "path", ".", "sep", ")", ")", ";", "if", "(", "!", "repoId", ")", "return", ";", "// Return an absolute file", "return", "path", ".", "resolve", "(", "GIT_TMP", ",", "repoId", ")", ";", "}" ]
Return root of git repo from a filepath
[ "Return", "root", "of", "git", "repo", "from", "a", "filepath" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/utils/git.js#L106-L119
43,702
KirinJS/Kirin
javascript/lib/extensions/Networking.js
function(config) { var hasParams = (typeof config.params === 'object'); var hasFiles = _.isArray(config.attachments); if('GET' === config.method) { if(hasParams) { config.url = addParams(config.url, config.params); } if (hasFiles) { throw new Error("Cannot upload files with a GET request"); } } else if('POST' === config.method) { if(typeof config.postData !== "undefined") { // We have raw POST data to send up so we give it no further treatment. config.params = config.postData; } else if (hasFiles) { if (hasParams) { config.paramMap = _.clone(config.params); _.each(config.paramMap, function (num, key) { var value = config.paramMap[key]; if (value === null) { delete config.paramMap[key]; } }); delete config.params; _.each(config.attachments, function (filestats) { api.normalizeAPI({ 'string': { mandatory: ['name'], oneOf: ['filename', 'fileArea', 'filePath'], optional: ['contentType', 'name'] } }, filestats); }); } } else if(hasParams) { // We have a bunch of key/values, so we need to encode each of them. // A string like a posted form is created. e.g. "param1key=param1value&param2key=param2value" var paramsWithQuestion = addParams('', config.params); config.params = paramsWithQuestion.substring(1); // Lop off the '?' at the head } } }
javascript
function(config) { var hasParams = (typeof config.params === 'object'); var hasFiles = _.isArray(config.attachments); if('GET' === config.method) { if(hasParams) { config.url = addParams(config.url, config.params); } if (hasFiles) { throw new Error("Cannot upload files with a GET request"); } } else if('POST' === config.method) { if(typeof config.postData !== "undefined") { // We have raw POST data to send up so we give it no further treatment. config.params = config.postData; } else if (hasFiles) { if (hasParams) { config.paramMap = _.clone(config.params); _.each(config.paramMap, function (num, key) { var value = config.paramMap[key]; if (value === null) { delete config.paramMap[key]; } }); delete config.params; _.each(config.attachments, function (filestats) { api.normalizeAPI({ 'string': { mandatory: ['name'], oneOf: ['filename', 'fileArea', 'filePath'], optional: ['contentType', 'name'] } }, filestats); }); } } else if(hasParams) { // We have a bunch of key/values, so we need to encode each of them. // A string like a posted form is created. e.g. "param1key=param1value&param2key=param2value" var paramsWithQuestion = addParams('', config.params); config.params = paramsWithQuestion.substring(1); // Lop off the '?' at the head } } }
[ "function", "(", "config", ")", "{", "var", "hasParams", "=", "(", "typeof", "config", ".", "params", "===", "'object'", ")", ";", "var", "hasFiles", "=", "_", ".", "isArray", "(", "config", ".", "attachments", ")", ";", "if", "(", "'GET'", "===", "config", ".", "method", ")", "{", "if", "(", "hasParams", ")", "{", "config", ".", "url", "=", "addParams", "(", "config", ".", "url", ",", "config", ".", "params", ")", ";", "}", "if", "(", "hasFiles", ")", "{", "throw", "new", "Error", "(", "\"Cannot upload files with a GET request\"", ")", ";", "}", "}", "else", "if", "(", "'POST'", "===", "config", ".", "method", ")", "{", "if", "(", "typeof", "config", ".", "postData", "!==", "\"undefined\"", ")", "{", "// We have raw POST data to send up so we give it no further treatment.", "config", ".", "params", "=", "config", ".", "postData", ";", "}", "else", "if", "(", "hasFiles", ")", "{", "if", "(", "hasParams", ")", "{", "config", ".", "paramMap", "=", "_", ".", "clone", "(", "config", ".", "params", ")", ";", "_", ".", "each", "(", "config", ".", "paramMap", ",", "function", "(", "num", ",", "key", ")", "{", "var", "value", "=", "config", ".", "paramMap", "[", "key", "]", ";", "if", "(", "value", "===", "null", ")", "{", "delete", "config", ".", "paramMap", "[", "key", "]", ";", "}", "}", ")", ";", "delete", "config", ".", "params", ";", "_", ".", "each", "(", "config", ".", "attachments", ",", "function", "(", "filestats", ")", "{", "api", ".", "normalizeAPI", "(", "{", "'string'", ":", "{", "mandatory", ":", "[", "'name'", "]", ",", "oneOf", ":", "[", "'filename'", ",", "'fileArea'", ",", "'filePath'", "]", ",", "optional", ":", "[", "'contentType'", ",", "'name'", "]", "}", "}", ",", "filestats", ")", ";", "}", ")", ";", "}", "}", "else", "if", "(", "hasParams", ")", "{", "// We have a bunch of key/values, so we need to encode each of them.", "// A string like a posted form is created. e.g. \"param1key=param1value&param2key=param2value\"", "var", "paramsWithQuestion", "=", "addParams", "(", "''", ",", "config", ".", "params", ")", ";", "config", ".", "params", "=", "paramsWithQuestion", ".", "substring", "(", "1", ")", ";", "// Lop off the '?' at the head", "}", "}", "}" ]
If the method is GET, the config.url string will have any parameters in the config.params added to it appropriately. If the method is POST and there is no config.postData, the config.params object will be changed to a string. The form of this string will be "param1key=param1value&param2key=param2value". Each key and value will be encoded using encodeURIComponent(). If the method is POST and there is a config.postData string, the config.params object will be changed to be the same as the postData string. No encoding will take placed.
[ "If", "the", "method", "is", "GET", "the", "config", ".", "url", "string", "will", "have", "any", "parameters", "in", "the", "config", ".", "params", "added", "to", "it", "appropriately", "." ]
d40e86ca89c40b5d3e0c129c24ff3b77ed3d28e1
https://github.com/KirinJS/Kirin/blob/d40e86ca89c40b5d3e0c129c24ff3b77ed3d28e1/javascript/lib/extensions/Networking.js#L124-L170
43,703
simonguo/hbook
lib/utils/progress.js
calculProgress
function calculProgress(navigation, current) { var n = _.size(navigation); var percent = 0, prevPercent = 0, currentChapter = null; var done = true; var chapters = _.chain(navigation) // Transform as array .map(function(nav, path) { nav.path = path; return nav; }) // Sort entries .sortBy(function(nav) { return nav.index; }) .map(function(nav, i) { // Calcul percent nav.percent = (i * 100) / Math.max((n - 1), 1); // Is it done nav.done = done; if (nav.path == current) { currentChapter = nav; percent = nav.percent; done = false; } else if (done) { prevPercent = nav.percent; } return nav; }) .value(); return { // Previous percent prevPercent: prevPercent, // Current percent percent: percent, // List of chapter with progress chapters: chapters, // Current chapter current: currentChapter }; }
javascript
function calculProgress(navigation, current) { var n = _.size(navigation); var percent = 0, prevPercent = 0, currentChapter = null; var done = true; var chapters = _.chain(navigation) // Transform as array .map(function(nav, path) { nav.path = path; return nav; }) // Sort entries .sortBy(function(nav) { return nav.index; }) .map(function(nav, i) { // Calcul percent nav.percent = (i * 100) / Math.max((n - 1), 1); // Is it done nav.done = done; if (nav.path == current) { currentChapter = nav; percent = nav.percent; done = false; } else if (done) { prevPercent = nav.percent; } return nav; }) .value(); return { // Previous percent prevPercent: prevPercent, // Current percent percent: percent, // List of chapter with progress chapters: chapters, // Current chapter current: currentChapter }; }
[ "function", "calculProgress", "(", "navigation", ",", "current", ")", "{", "var", "n", "=", "_", ".", "size", "(", "navigation", ")", ";", "var", "percent", "=", "0", ",", "prevPercent", "=", "0", ",", "currentChapter", "=", "null", ";", "var", "done", "=", "true", ";", "var", "chapters", "=", "_", ".", "chain", "(", "navigation", ")", "// Transform as array", ".", "map", "(", "function", "(", "nav", ",", "path", ")", "{", "nav", ".", "path", "=", "path", ";", "return", "nav", ";", "}", ")", "// Sort entries", ".", "sortBy", "(", "function", "(", "nav", ")", "{", "return", "nav", ".", "index", ";", "}", ")", ".", "map", "(", "function", "(", "nav", ",", "i", ")", "{", "// Calcul percent", "nav", ".", "percent", "=", "(", "i", "*", "100", ")", "/", "Math", ".", "max", "(", "(", "n", "-", "1", ")", ",", "1", ")", ";", "// Is it done", "nav", ".", "done", "=", "done", ";", "if", "(", "nav", ".", "path", "==", "current", ")", "{", "currentChapter", "=", "nav", ";", "percent", "=", "nav", ".", "percent", ";", "done", "=", "false", ";", "}", "else", "if", "(", "done", ")", "{", "prevPercent", "=", "nav", ".", "percent", ";", "}", "return", "nav", ";", "}", ")", ".", "value", "(", ")", ";", "return", "{", "// Previous percent", "prevPercent", ":", "prevPercent", ",", "// Current percent", "percent", ":", "percent", ",", "// List of chapter with progress", "chapters", ":", "chapters", ",", "// Current chapter", "current", ":", "currentChapter", "}", ";", "}" ]
Returns from a navigation and a current file, a snapshot of current detailed state
[ "Returns", "from", "a", "navigation", "and", "a", "current", "file", "a", "snapshot", "of", "current", "detailed", "state" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/utils/progress.js#L4-L53
43,704
anvaka/amator
index.js
animate
function animate(source, target, options) { var start = Object.create(null) var diff = Object.create(null) options = options || {} // We let clients specify their own easing function var easing = (typeof options.easing === 'function') ? options.easing : animations[options.easing] // if nothing is specified, default to ease (similar to CSS animations) if (!easing) { if (options.easing) { console.warn('Unknown easing function in amator: ' + options.easing); } easing = animations.ease } var step = typeof options.step === 'function' ? options.step : noop var done = typeof options.done === 'function' ? options.done : noop var scheduler = getScheduler(options.scheduler) var keys = Object.keys(target) keys.forEach(function(key) { start[key] = source[key] diff[key] = target[key] - source[key] }) var durationInMs = typeof options.duration === 'number' ? options.duration : 400 var durationInFrames = Math.max(1, durationInMs * 0.06) // 0.06 because 60 frames pers 1,000 ms var previousAnimationId var frame = 0 previousAnimationId = scheduler.next(loop) return { cancel: cancel } function cancel() { scheduler.cancel(previousAnimationId) previousAnimationId = 0 } function loop() { var t = easing(frame/durationInFrames) frame += 1 setValues(t) if (frame <= durationInFrames) { previousAnimationId = scheduler.next(loop) step(source) } else { previousAnimationId = 0 setTimeout(function() { done(source) }, 0) } } function setValues(t) { keys.forEach(function(key) { source[key] = diff[key] * t + start[key] }) } }
javascript
function animate(source, target, options) { var start = Object.create(null) var diff = Object.create(null) options = options || {} // We let clients specify their own easing function var easing = (typeof options.easing === 'function') ? options.easing : animations[options.easing] // if nothing is specified, default to ease (similar to CSS animations) if (!easing) { if (options.easing) { console.warn('Unknown easing function in amator: ' + options.easing); } easing = animations.ease } var step = typeof options.step === 'function' ? options.step : noop var done = typeof options.done === 'function' ? options.done : noop var scheduler = getScheduler(options.scheduler) var keys = Object.keys(target) keys.forEach(function(key) { start[key] = source[key] diff[key] = target[key] - source[key] }) var durationInMs = typeof options.duration === 'number' ? options.duration : 400 var durationInFrames = Math.max(1, durationInMs * 0.06) // 0.06 because 60 frames pers 1,000 ms var previousAnimationId var frame = 0 previousAnimationId = scheduler.next(loop) return { cancel: cancel } function cancel() { scheduler.cancel(previousAnimationId) previousAnimationId = 0 } function loop() { var t = easing(frame/durationInFrames) frame += 1 setValues(t) if (frame <= durationInFrames) { previousAnimationId = scheduler.next(loop) step(source) } else { previousAnimationId = 0 setTimeout(function() { done(source) }, 0) } } function setValues(t) { keys.forEach(function(key) { source[key] = diff[key] * t + start[key] }) } }
[ "function", "animate", "(", "source", ",", "target", ",", "options", ")", "{", "var", "start", "=", "Object", ".", "create", "(", "null", ")", "var", "diff", "=", "Object", ".", "create", "(", "null", ")", "options", "=", "options", "||", "{", "}", "// We let clients specify their own easing function", "var", "easing", "=", "(", "typeof", "options", ".", "easing", "===", "'function'", ")", "?", "options", ".", "easing", ":", "animations", "[", "options", ".", "easing", "]", "// if nothing is specified, default to ease (similar to CSS animations)", "if", "(", "!", "easing", ")", "{", "if", "(", "options", ".", "easing", ")", "{", "console", ".", "warn", "(", "'Unknown easing function in amator: '", "+", "options", ".", "easing", ")", ";", "}", "easing", "=", "animations", ".", "ease", "}", "var", "step", "=", "typeof", "options", ".", "step", "===", "'function'", "?", "options", ".", "step", ":", "noop", "var", "done", "=", "typeof", "options", ".", "done", "===", "'function'", "?", "options", ".", "done", ":", "noop", "var", "scheduler", "=", "getScheduler", "(", "options", ".", "scheduler", ")", "var", "keys", "=", "Object", ".", "keys", "(", "target", ")", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "start", "[", "key", "]", "=", "source", "[", "key", "]", "diff", "[", "key", "]", "=", "target", "[", "key", "]", "-", "source", "[", "key", "]", "}", ")", "var", "durationInMs", "=", "typeof", "options", ".", "duration", "===", "'number'", "?", "options", ".", "duration", ":", "400", "var", "durationInFrames", "=", "Math", ".", "max", "(", "1", ",", "durationInMs", "*", "0.06", ")", "// 0.06 because 60 frames pers 1,000 ms", "var", "previousAnimationId", "var", "frame", "=", "0", "previousAnimationId", "=", "scheduler", ".", "next", "(", "loop", ")", "return", "{", "cancel", ":", "cancel", "}", "function", "cancel", "(", ")", "{", "scheduler", ".", "cancel", "(", "previousAnimationId", ")", "previousAnimationId", "=", "0", "}", "function", "loop", "(", ")", "{", "var", "t", "=", "easing", "(", "frame", "/", "durationInFrames", ")", "frame", "+=", "1", "setValues", "(", "t", ")", "if", "(", "frame", "<=", "durationInFrames", ")", "{", "previousAnimationId", "=", "scheduler", ".", "next", "(", "loop", ")", "step", "(", "source", ")", "}", "else", "{", "previousAnimationId", "=", "0", "setTimeout", "(", "function", "(", ")", "{", "done", "(", "source", ")", "}", ",", "0", ")", "}", "}", "function", "setValues", "(", "t", ")", "{", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "source", "[", "key", "]", "=", "diff", "[", "key", "]", "*", "t", "+", "start", "[", "key", "]", "}", ")", "}", "}" ]
Creates a new instance of animator. Animator uses interpolation function to change `source` object into `target` object. Note: this method mutates `source` object properties. @param {Object} source @param {Object} target @param {Object} options - animation configuration @param {Function} options.step - called on each animation step @param {Function} options.easing - easing function, which takes one argument `t` in range [0, 1], and returns corresponding interpolation value. @param {Function} options.done - called when animation is over
[ "Creates", "a", "new", "instance", "of", "animator", ".", "Animator", "uses", "interpolation", "function", "to", "change", "source", "object", "into", "target", "object", "." ]
9147cdb2e9dbfcb35c564184150c2dfbd36fe4ee
https://github.com/anvaka/amator/blob/9147cdb2e9dbfcb35c564184150c2dfbd36fe4ee/index.js#L34-L94
43,705
bhoriuchi/vsphere-connect
archive/v1/client/method.js
getFields
function getFields(def, obj) { var a = {}; // if not an object, return the value if (!_.isObject(obj)) { return obj; } // check for type override var defType = _.get(obj, 'attributes.xsi:type') || _.get(obj, 'attributes.type'); defType = defType ? defType.replace(/^vim25\:/i, '') : null; // if there is a type override and it is a valid type, set the def to that type // and add the type to the attributes if (defType && _.has(_client.types, defType)) { def = _client.types[defType](); a.attributes = { 'xsi:type': defType }; } // loop through each field in the type definition and look for fields // that were supplied by the user _.forEach(def, function(v, k) { if (_.has(obj, k)) { if (Array.isArray(obj[k])) { a[k] = _.map(obj[k], function(o) { return getFields(v, o); }); } else if (_.isObject(v) && _.isObject(obj[k])) { a[k] = getFields(v, obj[k]); } else { a[k] = obj[k]; } } }); // return the new arguments object return a; }
javascript
function getFields(def, obj) { var a = {}; // if not an object, return the value if (!_.isObject(obj)) { return obj; } // check for type override var defType = _.get(obj, 'attributes.xsi:type') || _.get(obj, 'attributes.type'); defType = defType ? defType.replace(/^vim25\:/i, '') : null; // if there is a type override and it is a valid type, set the def to that type // and add the type to the attributes if (defType && _.has(_client.types, defType)) { def = _client.types[defType](); a.attributes = { 'xsi:type': defType }; } // loop through each field in the type definition and look for fields // that were supplied by the user _.forEach(def, function(v, k) { if (_.has(obj, k)) { if (Array.isArray(obj[k])) { a[k] = _.map(obj[k], function(o) { return getFields(v, o); }); } else if (_.isObject(v) && _.isObject(obj[k])) { a[k] = getFields(v, obj[k]); } else { a[k] = obj[k]; } } }); // return the new arguments object return a; }
[ "function", "getFields", "(", "def", ",", "obj", ")", "{", "var", "a", "=", "{", "}", ";", "// if not an object, return the value", "if", "(", "!", "_", ".", "isObject", "(", "obj", ")", ")", "{", "return", "obj", ";", "}", "// check for type override", "var", "defType", "=", "_", ".", "get", "(", "obj", ",", "'attributes.xsi:type'", ")", "||", "_", ".", "get", "(", "obj", ",", "'attributes.type'", ")", ";", "defType", "=", "defType", "?", "defType", ".", "replace", "(", "/", "^vim25\\:", "/", "i", ",", "''", ")", ":", "null", ";", "// if there is a type override and it is a valid type, set the def to that type", "// and add the type to the attributes", "if", "(", "defType", "&&", "_", ".", "has", "(", "_client", ".", "types", ",", "defType", ")", ")", "{", "def", "=", "_client", ".", "types", "[", "defType", "]", "(", ")", ";", "a", ".", "attributes", "=", "{", "'xsi:type'", ":", "defType", "}", ";", "}", "// loop through each field in the type definition and look for fields", "// that were supplied by the user", "_", ".", "forEach", "(", "def", ",", "function", "(", "v", ",", "k", ")", "{", "if", "(", "_", ".", "has", "(", "obj", ",", "k", ")", ")", "{", "if", "(", "Array", ".", "isArray", "(", "obj", "[", "k", "]", ")", ")", "{", "a", "[", "k", "]", "=", "_", ".", "map", "(", "obj", "[", "k", "]", ",", "function", "(", "o", ")", "{", "return", "getFields", "(", "v", ",", "o", ")", ";", "}", ")", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "v", ")", "&&", "_", ".", "isObject", "(", "obj", "[", "k", "]", ")", ")", "{", "a", "[", "k", "]", "=", "getFields", "(", "v", ",", "obj", "[", "k", "]", ")", ";", "}", "else", "{", "a", "[", "k", "]", "=", "obj", "[", "k", "]", ";", "}", "}", "}", ")", ";", "// return the new arguments object", "return", "a", ";", "}" ]
recursive function to get the fields in the correct order based on the wsdl definitions
[ "recursive", "function", "to", "get", "the", "fields", "in", "the", "correct", "order", "based", "on", "the", "wsdl", "definitions" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/client/method.js#L19-L60
43,706
bhoriuchi/vsphere-connect
archive/v1/client/method.js
sortArgs
function sortArgs(method, args) { // get the method definition var def = _.get(_client.types, method.replace(/\_Task$/i, '') + 'RequestType'); // if found create the definition by calling its function if (def) { return getFields(def(), args); } return args; }
javascript
function sortArgs(method, args) { // get the method definition var def = _.get(_client.types, method.replace(/\_Task$/i, '') + 'RequestType'); // if found create the definition by calling its function if (def) { return getFields(def(), args); } return args; }
[ "function", "sortArgs", "(", "method", ",", "args", ")", "{", "// get the method definition", "var", "def", "=", "_", ".", "get", "(", "_client", ".", "types", ",", "method", ".", "replace", "(", "/", "\\_Task$", "/", "i", ",", "''", ")", "+", "'RequestType'", ")", ";", "// if found create the definition by calling its function", "if", "(", "def", ")", "{", "return", "getFields", "(", "def", "(", ")", ",", "args", ")", ";", "}", "return", "args", ";", "}" ]
function to correctly order the arguments this is done because arguments in an incorrect order will cause the soap method to fail
[ "function", "to", "correctly", "order", "the", "arguments", "this", "is", "done", "because", "arguments", "in", "an", "incorrect", "order", "will", "cause", "the", "soap", "method", "to", "fail" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/client/method.js#L66-L76
43,707
bhoriuchi/vsphere-connect
archive/v1/client/method.js
function(resolve, reject) { var fn = _client.client.VimService.VimPort[name]; fn(args, function(err, result, raw, soapHeader) { if (err) { // emit an error and handle the error _client.emit('method.error', err); _client.errorHandler(err, name, args, resolve, reject); } else { _client.retry = 0; // emit an event and resolve the output _client.emit('method.result', result); resolve(_.get(result, 'returnval')); } }); }
javascript
function(resolve, reject) { var fn = _client.client.VimService.VimPort[name]; fn(args, function(err, result, raw, soapHeader) { if (err) { // emit an error and handle the error _client.emit('method.error', err); _client.errorHandler(err, name, args, resolve, reject); } else { _client.retry = 0; // emit an event and resolve the output _client.emit('method.result', result); resolve(_.get(result, 'returnval')); } }); }
[ "function", "(", "resolve", ",", "reject", ")", "{", "var", "fn", "=", "_client", ".", "client", ".", "VimService", ".", "VimPort", "[", "name", "]", ";", "fn", "(", "args", ",", "function", "(", "err", ",", "result", ",", "raw", ",", "soapHeader", ")", "{", "if", "(", "err", ")", "{", "// emit an error and handle the error", "_client", ".", "emit", "(", "'method.error'", ",", "err", ")", ";", "_client", ".", "errorHandler", "(", "err", ",", "name", ",", "args", ",", "resolve", ",", "reject", ")", ";", "}", "else", "{", "_client", ".", "retry", "=", "0", ";", "// emit an event and resolve the output", "_client", ".", "emit", "(", "'method.result'", ",", "result", ")", ";", "resolve", "(", "_", ".", "get", "(", "result", ",", "'returnval'", ")", ")", ";", "}", "}", ")", ";", "}" ]
executes the function
[ "executes", "the", "function" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/client/method.js#L86-L103
43,708
bhoriuchi/vsphere-connect
archive/v1/client/emitUpdates.js
getUpdates
function getUpdates() { return _client.method('WaitForUpdatesEx', { _this: _client._updatesCollector, version: _client._updatesVersion, options: { maxWaitSeconds: 0 } }) .then(function(set) { if (set) { // update the version _client._updatesVersion = set.version; // get only the updates var updates = []; var filterSet = _.get(set, 'filterSet'); filterSet = Array.isArray(filterSet) ? filterSet : [filterSet]; // loop through the filter sets _.forEach(filterSet, function(f) { var objectSet = _.get(f, 'objectSet'); objectSet = Array.isArray(objectSet) ? objectSet : [objectSet]; // format the objects _.forEach(objectSet, function(u) { u.obj = { type: _.get(u, 'obj.attributes.type'), id: _.get(u, 'obj.$value') }; // make the change set an array u.changeSet = Array.isArray(u.changeSet) ? u.changeSet : [u.changeSet]; // update change set _.forEach(u.changeSet, function(c) { c.val = _.get(c, 'val.$value'); }); // push the update updates.push(u); }); }); // emit the results _client.emit('updates', updates); } }); }
javascript
function getUpdates() { return _client.method('WaitForUpdatesEx', { _this: _client._updatesCollector, version: _client._updatesVersion, options: { maxWaitSeconds: 0 } }) .then(function(set) { if (set) { // update the version _client._updatesVersion = set.version; // get only the updates var updates = []; var filterSet = _.get(set, 'filterSet'); filterSet = Array.isArray(filterSet) ? filterSet : [filterSet]; // loop through the filter sets _.forEach(filterSet, function(f) { var objectSet = _.get(f, 'objectSet'); objectSet = Array.isArray(objectSet) ? objectSet : [objectSet]; // format the objects _.forEach(objectSet, function(u) { u.obj = { type: _.get(u, 'obj.attributes.type'), id: _.get(u, 'obj.$value') }; // make the change set an array u.changeSet = Array.isArray(u.changeSet) ? u.changeSet : [u.changeSet]; // update change set _.forEach(u.changeSet, function(c) { c.val = _.get(c, 'val.$value'); }); // push the update updates.push(u); }); }); // emit the results _client.emit('updates', updates); } }); }
[ "function", "getUpdates", "(", ")", "{", "return", "_client", ".", "method", "(", "'WaitForUpdatesEx'", ",", "{", "_this", ":", "_client", ".", "_updatesCollector", ",", "version", ":", "_client", ".", "_updatesVersion", ",", "options", ":", "{", "maxWaitSeconds", ":", "0", "}", "}", ")", ".", "then", "(", "function", "(", "set", ")", "{", "if", "(", "set", ")", "{", "// update the version", "_client", ".", "_updatesVersion", "=", "set", ".", "version", ";", "// get only the updates", "var", "updates", "=", "[", "]", ";", "var", "filterSet", "=", "_", ".", "get", "(", "set", ",", "'filterSet'", ")", ";", "filterSet", "=", "Array", ".", "isArray", "(", "filterSet", ")", "?", "filterSet", ":", "[", "filterSet", "]", ";", "// loop through the filter sets", "_", ".", "forEach", "(", "filterSet", ",", "function", "(", "f", ")", "{", "var", "objectSet", "=", "_", ".", "get", "(", "f", ",", "'objectSet'", ")", ";", "objectSet", "=", "Array", ".", "isArray", "(", "objectSet", ")", "?", "objectSet", ":", "[", "objectSet", "]", ";", "// format the objects", "_", ".", "forEach", "(", "objectSet", ",", "function", "(", "u", ")", "{", "u", ".", "obj", "=", "{", "type", ":", "_", ".", "get", "(", "u", ",", "'obj.attributes.type'", ")", ",", "id", ":", "_", ".", "get", "(", "u", ",", "'obj.$value'", ")", "}", ";", "// make the change set an array", "u", ".", "changeSet", "=", "Array", ".", "isArray", "(", "u", ".", "changeSet", ")", "?", "u", ".", "changeSet", ":", "[", "u", ".", "changeSet", "]", ";", "// update change set", "_", ".", "forEach", "(", "u", ".", "changeSet", ",", "function", "(", "c", ")", "{", "c", ".", "val", "=", "_", ".", "get", "(", "c", ",", "'val.$value'", ")", ";", "}", ")", ";", "// push the update", "updates", ".", "push", "(", "u", ")", ";", "}", ")", ";", "}", ")", ";", "// emit the results", "_client", ".", "emit", "(", "'updates'", ",", "updates", ")", ";", "}", "}", ")", ";", "}" ]
function to get updates
[ "function", "to", "get", "updates" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/client/emitUpdates.js#L28-L77
43,709
serg-io/backbone-dynamodb
backbone-dynamodb.js
wrapComplete
function wrapComplete(instance, options) { var complete = options.complete; options.complete = function(response) { if ( _.isFunction( complete ) ) { complete.call( this, instance, response, options ); } }; }
javascript
function wrapComplete(instance, options) { var complete = options.complete; options.complete = function(response) { if ( _.isFunction( complete ) ) { complete.call( this, instance, response, options ); } }; }
[ "function", "wrapComplete", "(", "instance", ",", "options", ")", "{", "var", "complete", "=", "options", ".", "complete", ";", "options", ".", "complete", "=", "function", "(", "response", ")", "{", "if", "(", "_", ".", "isFunction", "(", "complete", ")", ")", "{", "complete", ".", "call", "(", "this", ",", "instance", ",", "response", ",", "options", ")", ";", "}", "}", ";", "}" ]
Wraps the complete callback function inside another function to ensure it is executed with the right arguments. @param {Backbone.DynamoDB.Model} instance @param {Object} options
[ "Wraps", "the", "complete", "callback", "function", "inside", "another", "function", "to", "ensure", "it", "is", "executed", "with", "the", "right", "arguments", "." ]
a501865f8513d27f6577289d7cf4a20324075146
https://github.com/serg-io/backbone-dynamodb/blob/a501865f8513d27f6577289d7cf4a20324075146/backbone-dynamodb.js#L48-L56
43,710
serg-io/backbone-dynamodb
backbone-dynamodb.js
putItem
function putItem(model, options) { options || ( options = {} ); if ( options.serializeDates !== false ) { // If serializeDates is NOT `false`, use `true` by default. options.serializeDates = true; } var newKey, // If the model `isNew`, a new key is generated. request, hashName, // Name of the hash attribute. rangeName, // Name of the range attribute. keyPromise, deferred = new _.Deferred(), /** * Container object to store the attributes that are changed as part of saving the model. */ changed = {}, /** * Parameters to use in the DynamoDB PutItem request */ params = { /** * Convert the model into an object. * If `options.serializeDates` is `true`, `Date` values are converted into strings. */ Item: model.toJSON( options ), TableName: model._tableName() }; if ( model.isNew() ) { // If the model is new, a new key attribute(s) must be generated hashName = _.result( model, 'hashAttribute' ) || _.result( model, 'idAttribute' ); rangeName = _.result( model, 'rangeAttribute' ); /** * Convenience method to set the `newKey` attribute(s), once it's generated. */ function setNewKey(_newKey) { if ( rangeName ) { /** * If the model has a range attribute, _newKey must be an object that contains * the hash and range attributes. */ _.extend( changed, _newKey ); } else { /** * If the model doesn't have a range attribute, _newKey must be the value of the hash attribute. */ changed[ hashName ] = _newKey; } // Add the new key attribute(s) to the Item to be sent to DynamoDB _.extend( params.Item, options.serializeDates === true ? serializeAllDates( model, _.clone( changed ) ) : changed ); } // Generate new key attribute(s) newKey = model.newKey( options ); if ( isPromise( newKey ) ) { /** * If `newKey` is a promise, wait until it's resolved to execute `setNewKey` * and assign the resulting promise to `keyPromise`. */ keyPromise = newKey.then( setNewKey ); } else { // If `newKey` is NOT a promise, call `setNewKey` right away. setNewKey( newKey ); } } wrapComplete( model, options ); _.extend( params, options.dynamodb ); request = dynamo().putItem( params ); request.on('complete', function (response) { var ctx = options.context || model; if ( response.error ) { deferred.rejectWith( ctx, [ response, options ] ); } else { /** * Backbone's "internal" success callback takes the changed attributes as the first argument. * Make the entire AWS `response` available as `options.awsResponse`. */ options.awsResponse = response; deferred.resolveWith( ctx, [ changed, options ] ); } }); if ( !keyPromise ) { // If there's no `keyPromise`, send the request right away. request.send(); } else { // If there's a `keyPromise`, wait until it is "done" before sending the request. keyPromise.done(function () { request.send(); }).fail(function () { var ctx = options.context || model; deferred.rejectWith( ctx, arguments ); }); } deferred.done( options.success ).fail( options.error ).always( options.complete ); return deferred.promise( request ); }
javascript
function putItem(model, options) { options || ( options = {} ); if ( options.serializeDates !== false ) { // If serializeDates is NOT `false`, use `true` by default. options.serializeDates = true; } var newKey, // If the model `isNew`, a new key is generated. request, hashName, // Name of the hash attribute. rangeName, // Name of the range attribute. keyPromise, deferred = new _.Deferred(), /** * Container object to store the attributes that are changed as part of saving the model. */ changed = {}, /** * Parameters to use in the DynamoDB PutItem request */ params = { /** * Convert the model into an object. * If `options.serializeDates` is `true`, `Date` values are converted into strings. */ Item: model.toJSON( options ), TableName: model._tableName() }; if ( model.isNew() ) { // If the model is new, a new key attribute(s) must be generated hashName = _.result( model, 'hashAttribute' ) || _.result( model, 'idAttribute' ); rangeName = _.result( model, 'rangeAttribute' ); /** * Convenience method to set the `newKey` attribute(s), once it's generated. */ function setNewKey(_newKey) { if ( rangeName ) { /** * If the model has a range attribute, _newKey must be an object that contains * the hash and range attributes. */ _.extend( changed, _newKey ); } else { /** * If the model doesn't have a range attribute, _newKey must be the value of the hash attribute. */ changed[ hashName ] = _newKey; } // Add the new key attribute(s) to the Item to be sent to DynamoDB _.extend( params.Item, options.serializeDates === true ? serializeAllDates( model, _.clone( changed ) ) : changed ); } // Generate new key attribute(s) newKey = model.newKey( options ); if ( isPromise( newKey ) ) { /** * If `newKey` is a promise, wait until it's resolved to execute `setNewKey` * and assign the resulting promise to `keyPromise`. */ keyPromise = newKey.then( setNewKey ); } else { // If `newKey` is NOT a promise, call `setNewKey` right away. setNewKey( newKey ); } } wrapComplete( model, options ); _.extend( params, options.dynamodb ); request = dynamo().putItem( params ); request.on('complete', function (response) { var ctx = options.context || model; if ( response.error ) { deferred.rejectWith( ctx, [ response, options ] ); } else { /** * Backbone's "internal" success callback takes the changed attributes as the first argument. * Make the entire AWS `response` available as `options.awsResponse`. */ options.awsResponse = response; deferred.resolveWith( ctx, [ changed, options ] ); } }); if ( !keyPromise ) { // If there's no `keyPromise`, send the request right away. request.send(); } else { // If there's a `keyPromise`, wait until it is "done" before sending the request. keyPromise.done(function () { request.send(); }).fail(function () { var ctx = options.context || model; deferred.rejectWith( ctx, arguments ); }); } deferred.done( options.success ).fail( options.error ).always( options.complete ); return deferred.promise( request ); }
[ "function", "putItem", "(", "model", ",", "options", ")", "{", "options", "||", "(", "options", "=", "{", "}", ")", ";", "if", "(", "options", ".", "serializeDates", "!==", "false", ")", "{", "// If serializeDates is NOT `false`, use `true` by default.", "options", ".", "serializeDates", "=", "true", ";", "}", "var", "newKey", ",", "// If the model `isNew`, a new key is generated.", "request", ",", "hashName", ",", "// Name of the hash attribute.", "rangeName", ",", "// Name of the range attribute.", "keyPromise", ",", "deferred", "=", "new", "_", ".", "Deferred", "(", ")", ",", "/**\n\t\t * Container object to store the attributes that are changed as part of saving the model.\n\t\t */", "changed", "=", "{", "}", ",", "/**\n\t\t * Parameters to use in the DynamoDB PutItem request\n\t\t */", "params", "=", "{", "/**\n\t\t\t * Convert the model into an object.\n\t\t\t * If `options.serializeDates` is `true`, `Date` values are converted into strings.\n\t\t\t */", "Item", ":", "model", ".", "toJSON", "(", "options", ")", ",", "TableName", ":", "model", ".", "_tableName", "(", ")", "}", ";", "if", "(", "model", ".", "isNew", "(", ")", ")", "{", "// If the model is new, a new key attribute(s) must be generated", "hashName", "=", "_", ".", "result", "(", "model", ",", "'hashAttribute'", ")", "||", "_", ".", "result", "(", "model", ",", "'idAttribute'", ")", ";", "rangeName", "=", "_", ".", "result", "(", "model", ",", "'rangeAttribute'", ")", ";", "/**\n\t\t * Convenience method to set the `newKey` attribute(s), once it's generated.\n\t\t */", "function", "setNewKey", "(", "_newKey", ")", "{", "if", "(", "rangeName", ")", "{", "/**\n\t\t\t\t * If the model has a range attribute, _newKey must be an object that contains\n\t\t\t\t * the hash and range attributes.\n\t\t\t\t */", "_", ".", "extend", "(", "changed", ",", "_newKey", ")", ";", "}", "else", "{", "/**\n\t\t\t\t * If the model doesn't have a range attribute, _newKey must be the value of the hash attribute.\n\t\t\t\t */", "changed", "[", "hashName", "]", "=", "_newKey", ";", "}", "// Add the new key attribute(s) to the Item to be sent to DynamoDB", "_", ".", "extend", "(", "params", ".", "Item", ",", "options", ".", "serializeDates", "===", "true", "?", "serializeAllDates", "(", "model", ",", "_", ".", "clone", "(", "changed", ")", ")", ":", "changed", ")", ";", "}", "// Generate new key attribute(s)", "newKey", "=", "model", ".", "newKey", "(", "options", ")", ";", "if", "(", "isPromise", "(", "newKey", ")", ")", "{", "/**\n\t\t\t * If `newKey` is a promise, wait until it's resolved to execute `setNewKey`\n\t\t\t * and assign the resulting promise to `keyPromise`.\n\t\t\t */", "keyPromise", "=", "newKey", ".", "then", "(", "setNewKey", ")", ";", "}", "else", "{", "// If `newKey` is NOT a promise, call `setNewKey` right away.", "setNewKey", "(", "newKey", ")", ";", "}", "}", "wrapComplete", "(", "model", ",", "options", ")", ";", "_", ".", "extend", "(", "params", ",", "options", ".", "dynamodb", ")", ";", "request", "=", "dynamo", "(", ")", ".", "putItem", "(", "params", ")", ";", "request", ".", "on", "(", "'complete'", ",", "function", "(", "response", ")", "{", "var", "ctx", "=", "options", ".", "context", "||", "model", ";", "if", "(", "response", ".", "error", ")", "{", "deferred", ".", "rejectWith", "(", "ctx", ",", "[", "response", ",", "options", "]", ")", ";", "}", "else", "{", "/**\n\t\t\t * Backbone's \"internal\" success callback takes the changed attributes as the first argument.\n\t\t\t * Make the entire AWS `response` available as `options.awsResponse`.\n\t\t\t */", "options", ".", "awsResponse", "=", "response", ";", "deferred", ".", "resolveWith", "(", "ctx", ",", "[", "changed", ",", "options", "]", ")", ";", "}", "}", ")", ";", "if", "(", "!", "keyPromise", ")", "{", "// If there's no `keyPromise`, send the request right away.", "request", ".", "send", "(", ")", ";", "}", "else", "{", "// If there's a `keyPromise`, wait until it is \"done\" before sending the request.", "keyPromise", ".", "done", "(", "function", "(", ")", "{", "request", ".", "send", "(", ")", ";", "}", ")", ".", "fail", "(", "function", "(", ")", "{", "var", "ctx", "=", "options", ".", "context", "||", "model", ";", "deferred", ".", "rejectWith", "(", "ctx", ",", "arguments", ")", ";", "}", ")", ";", "}", "deferred", ".", "done", "(", "options", ".", "success", ")", ".", "fail", "(", "options", ".", "error", ")", ".", "always", "(", "options", ".", "complete", ")", ";", "return", "deferred", ".", "promise", "(", "request", ")", ";", "}" ]
Sends a request to store a Backbone.DynamoDB.Model in a DynamoDB table using a PutItem request. @param {Backbone.DynamoDB.Model} model The model to store in DynamoDB. @param {Object} options The options object.
[ "Sends", "a", "request", "to", "store", "a", "Backbone", ".", "DynamoDB", ".", "Model", "in", "a", "DynamoDB", "table", "using", "a", "PutItem", "request", "." ]
a501865f8513d27f6577289d7cf4a20324075146
https://github.com/serg-io/backbone-dynamodb/blob/a501865f8513d27f6577289d7cf4a20324075146/backbone-dynamodb.js#L64-L169
43,711
serg-io/backbone-dynamodb
backbone-dynamodb.js
deleteItem
function deleteItem(model, options) { var request, deferred = new _.Deferred(), params = { Key: key.call( model ), TableName: model._tableName() }; options || ( options = {} ); wrapComplete( model, options ); _.extend( params, options.dynamodb ); if ( options.serializeDates !== false ) { // If the hash and/or range attributes are `Date` instance they must be serialized before sending the request. serializeAllDates( model, params.Key ); } request = dynamo().deleteItem( params ); request.on('complete', function (response) { var ctx = options.context || model; if ( response.error ) { deferred.rejectWith( ctx, [ response, options ] ); } else { deferred.resolveWith( ctx, [ response, options ] ); } }); request.send(); deferred.done( options.success ).fail( options.error ).always( options.complete ); return deferred.promise( request ); }
javascript
function deleteItem(model, options) { var request, deferred = new _.Deferred(), params = { Key: key.call( model ), TableName: model._tableName() }; options || ( options = {} ); wrapComplete( model, options ); _.extend( params, options.dynamodb ); if ( options.serializeDates !== false ) { // If the hash and/or range attributes are `Date` instance they must be serialized before sending the request. serializeAllDates( model, params.Key ); } request = dynamo().deleteItem( params ); request.on('complete', function (response) { var ctx = options.context || model; if ( response.error ) { deferred.rejectWith( ctx, [ response, options ] ); } else { deferred.resolveWith( ctx, [ response, options ] ); } }); request.send(); deferred.done( options.success ).fail( options.error ).always( options.complete ); return deferred.promise( request ); }
[ "function", "deleteItem", "(", "model", ",", "options", ")", "{", "var", "request", ",", "deferred", "=", "new", "_", ".", "Deferred", "(", ")", ",", "params", "=", "{", "Key", ":", "key", ".", "call", "(", "model", ")", ",", "TableName", ":", "model", ".", "_tableName", "(", ")", "}", ";", "options", "||", "(", "options", "=", "{", "}", ")", ";", "wrapComplete", "(", "model", ",", "options", ")", ";", "_", ".", "extend", "(", "params", ",", "options", ".", "dynamodb", ")", ";", "if", "(", "options", ".", "serializeDates", "!==", "false", ")", "{", "// If the hash and/or range attributes are `Date` instance they must be serialized before sending the request.", "serializeAllDates", "(", "model", ",", "params", ".", "Key", ")", ";", "}", "request", "=", "dynamo", "(", ")", ".", "deleteItem", "(", "params", ")", ";", "request", ".", "on", "(", "'complete'", ",", "function", "(", "response", ")", "{", "var", "ctx", "=", "options", ".", "context", "||", "model", ";", "if", "(", "response", ".", "error", ")", "{", "deferred", ".", "rejectWith", "(", "ctx", ",", "[", "response", ",", "options", "]", ")", ";", "}", "else", "{", "deferred", ".", "resolveWith", "(", "ctx", ",", "[", "response", ",", "options", "]", ")", ";", "}", "}", ")", ";", "request", ".", "send", "(", ")", ";", "deferred", ".", "done", "(", "options", ".", "success", ")", ".", "fail", "(", "options", ".", "error", ")", ".", "always", "(", "options", ".", "complete", ")", ";", "return", "deferred", ".", "promise", "(", "request", ")", ";", "}" ]
Deletes a Backbone.DynamoDB.Model from a DynamoDB table using a DeleteItem request. @param {Backbone.DynamoDB.Model} model The model to delete from DynamoDB. @param {Object} options The options object.
[ "Deletes", "a", "Backbone", ".", "DynamoDB", ".", "Model", "from", "a", "DynamoDB", "table", "using", "a", "DeleteItem", "request", "." ]
a501865f8513d27f6577289d7cf4a20324075146
https://github.com/serg-io/backbone-dynamodb/blob/a501865f8513d27f6577289d7cf4a20324075146/backbone-dynamodb.js#L177-L210
43,712
serg-io/backbone-dynamodb
backbone-dynamodb.js
fetchCollection
function fetchCollection(collection, options) { options || ( options = {} ); var request, deferred = new _.Deferred(), // Determine the type of request: Query or Scan. Default is Scan. fetchType = options.query ? 'query' : 'scan', params = { TableName: collection._tableName() }; wrapComplete( collection, options ); _.extend( params, options[ fetchType ], options.dynamodb ); // Create the Query or Scan request request = dynamo()[ fetchType ]( params ); request.on('complete', function (response) { var dummyModel, ctx = options.context || collection; if ( response.error ) { deferred.rejectWith( ctx, [ response, options ] ); } else { /** * Backbone's "internal" success callback takes an array of models/objects as the first argument. * Make the entire AWS `response` available as `options.awsResponse`. * `Date` attributes are deserialized here. */ options.awsResponse = response; dummyModel = new collection.model(); _.each(response.data.Items, function (item) { deserializeAllDates( dummyModel, item ); }); deferred.resolveWith( ctx, [ response.data.Items, options ] ); } }); request.send(); deferred.done( options.success ).fail( options.error ).always( options.complete ); return deferred.promise( request ); }
javascript
function fetchCollection(collection, options) { options || ( options = {} ); var request, deferred = new _.Deferred(), // Determine the type of request: Query or Scan. Default is Scan. fetchType = options.query ? 'query' : 'scan', params = { TableName: collection._tableName() }; wrapComplete( collection, options ); _.extend( params, options[ fetchType ], options.dynamodb ); // Create the Query or Scan request request = dynamo()[ fetchType ]( params ); request.on('complete', function (response) { var dummyModel, ctx = options.context || collection; if ( response.error ) { deferred.rejectWith( ctx, [ response, options ] ); } else { /** * Backbone's "internal" success callback takes an array of models/objects as the first argument. * Make the entire AWS `response` available as `options.awsResponse`. * `Date` attributes are deserialized here. */ options.awsResponse = response; dummyModel = new collection.model(); _.each(response.data.Items, function (item) { deserializeAllDates( dummyModel, item ); }); deferred.resolveWith( ctx, [ response.data.Items, options ] ); } }); request.send(); deferred.done( options.success ).fail( options.error ).always( options.complete ); return deferred.promise( request ); }
[ "function", "fetchCollection", "(", "collection", ",", "options", ")", "{", "options", "||", "(", "options", "=", "{", "}", ")", ";", "var", "request", ",", "deferred", "=", "new", "_", ".", "Deferred", "(", ")", ",", "// Determine the type of request: Query or Scan. Default is Scan.", "fetchType", "=", "options", ".", "query", "?", "'query'", ":", "'scan'", ",", "params", "=", "{", "TableName", ":", "collection", ".", "_tableName", "(", ")", "}", ";", "wrapComplete", "(", "collection", ",", "options", ")", ";", "_", ".", "extend", "(", "params", ",", "options", "[", "fetchType", "]", ",", "options", ".", "dynamodb", ")", ";", "// Create the Query or Scan request", "request", "=", "dynamo", "(", ")", "[", "fetchType", "]", "(", "params", ")", ";", "request", ".", "on", "(", "'complete'", ",", "function", "(", "response", ")", "{", "var", "dummyModel", ",", "ctx", "=", "options", ".", "context", "||", "collection", ";", "if", "(", "response", ".", "error", ")", "{", "deferred", ".", "rejectWith", "(", "ctx", ",", "[", "response", ",", "options", "]", ")", ";", "}", "else", "{", "/**\n\t\t\t * Backbone's \"internal\" success callback takes an array of models/objects as the first argument.\n\t\t\t * Make the entire AWS `response` available as `options.awsResponse`.\n\t\t\t * `Date` attributes are deserialized here.\n\t\t\t */", "options", ".", "awsResponse", "=", "response", ";", "dummyModel", "=", "new", "collection", ".", "model", "(", ")", ";", "_", ".", "each", "(", "response", ".", "data", ".", "Items", ",", "function", "(", "item", ")", "{", "deserializeAllDates", "(", "dummyModel", ",", "item", ")", ";", "}", ")", ";", "deferred", ".", "resolveWith", "(", "ctx", ",", "[", "response", ".", "data", ".", "Items", ",", "options", "]", ")", ";", "}", "}", ")", ";", "request", ".", "send", "(", ")", ";", "deferred", ".", "done", "(", "options", ".", "success", ")", ".", "fail", "(", "options", ".", "error", ")", ".", "always", "(", "options", ".", "complete", ")", ";", "return", "deferred", ".", "promise", "(", "request", ")", ";", "}" ]
Retrieves a collection of Backbone.DynamoDB.Models from a DynamoDB table using a Query or Scan request. @param {Backbone.DynamoDB.Collection} collection The collection instance. @param {Object} options The options object.
[ "Retrieves", "a", "collection", "of", "Backbone", ".", "DynamoDB", ".", "Models", "from", "a", "DynamoDB", "table", "using", "a", "Query", "or", "Scan", "request", "." ]
a501865f8513d27f6577289d7cf4a20324075146
https://github.com/serg-io/backbone-dynamodb/blob/a501865f8513d27f6577289d7cf4a20324075146/backbone-dynamodb.js#L271-L311
43,713
serg-io/backbone-dynamodb
backbone-dynamodb.js
serializeAllDates
function serializeAllDates(model, json) { _.each(json, function (value, name) { if ( _.isDate( value ) ) { json[ name ] = model.serializeDate( name, value ); } else if ( !isScalar( value ) && !isBackboneInstance( value ) && isRecursive( value ) ) { serializeAllDates( model, value ); } }); return json; }
javascript
function serializeAllDates(model, json) { _.each(json, function (value, name) { if ( _.isDate( value ) ) { json[ name ] = model.serializeDate( name, value ); } else if ( !isScalar( value ) && !isBackboneInstance( value ) && isRecursive( value ) ) { serializeAllDates( model, value ); } }); return json; }
[ "function", "serializeAllDates", "(", "model", ",", "json", ")", "{", "_", ".", "each", "(", "json", ",", "function", "(", "value", ",", "name", ")", "{", "if", "(", "_", ".", "isDate", "(", "value", ")", ")", "{", "json", "[", "name", "]", "=", "model", ".", "serializeDate", "(", "name", ",", "value", ")", ";", "}", "else", "if", "(", "!", "isScalar", "(", "value", ")", "&&", "!", "isBackboneInstance", "(", "value", ")", "&&", "isRecursive", "(", "value", ")", ")", "{", "serializeAllDates", "(", "model", ",", "value", ")", ";", "}", "}", ")", ";", "return", "json", ";", "}" ]
Recursively serializes all `Date` values in an object. @param {Backbone.DynamoDB.Model} model @param {Object} json
[ "Recursively", "serializes", "all", "Date", "values", "in", "an", "object", "." ]
a501865f8513d27f6577289d7cf4a20324075146
https://github.com/serg-io/backbone-dynamodb/blob/a501865f8513d27f6577289d7cf4a20324075146/backbone-dynamodb.js#L365-L375
43,714
serg-io/backbone-dynamodb
backbone-dynamodb.js
deserializeAllDates
function deserializeAllDates(model, json) { _.each(json, function (value, name) { if ( !_.isDate( value ) && !isBackboneInstance( value ) ) { if ( _.isString( value ) && model.isSerializedDate( name, value ) ) { json[ name ] = model.deserializeDate( name, value ); } else if ( !isScalar( value ) && isRecursive( value ) ) { deserializeAllDates( model, value ); } } }); return json; }
javascript
function deserializeAllDates(model, json) { _.each(json, function (value, name) { if ( !_.isDate( value ) && !isBackboneInstance( value ) ) { if ( _.isString( value ) && model.isSerializedDate( name, value ) ) { json[ name ] = model.deserializeDate( name, value ); } else if ( !isScalar( value ) && isRecursive( value ) ) { deserializeAllDates( model, value ); } } }); return json; }
[ "function", "deserializeAllDates", "(", "model", ",", "json", ")", "{", "_", ".", "each", "(", "json", ",", "function", "(", "value", ",", "name", ")", "{", "if", "(", "!", "_", ".", "isDate", "(", "value", ")", "&&", "!", "isBackboneInstance", "(", "value", ")", ")", "{", "if", "(", "_", ".", "isString", "(", "value", ")", "&&", "model", ".", "isSerializedDate", "(", "name", ",", "value", ")", ")", "{", "json", "[", "name", "]", "=", "model", ".", "deserializeDate", "(", "name", ",", "value", ")", ";", "}", "else", "if", "(", "!", "isScalar", "(", "value", ")", "&&", "isRecursive", "(", "value", ")", ")", "{", "deserializeAllDates", "(", "model", ",", "value", ")", ";", "}", "}", "}", ")", ";", "return", "json", ";", "}" ]
Recursively deserializes all date values in an object. @param {Backbone.DynamoDB.Model} model @param {Object} json
[ "Recursively", "deserializes", "all", "date", "values", "in", "an", "object", "." ]
a501865f8513d27f6577289d7cf4a20324075146
https://github.com/serg-io/backbone-dynamodb/blob/a501865f8513d27f6577289d7cf4a20324075146/backbone-dynamodb.js#L383-L395
43,715
serg-io/backbone-dynamodb
backbone-dynamodb.js
_tableName
function _tableName() { if ( this.tableName ) { return _.result( this, 'tableName' ); } var urlAttributeName = this instanceof Backbone.DynamoDB.Model ? 'urlRoot' : 'url', table = _.result( this, urlAttributeName ).replace( /^\//, '' ); return table.charAt( 0 ).toUpperCase() + table.substr( 1 ); }
javascript
function _tableName() { if ( this.tableName ) { return _.result( this, 'tableName' ); } var urlAttributeName = this instanceof Backbone.DynamoDB.Model ? 'urlRoot' : 'url', table = _.result( this, urlAttributeName ).replace( /^\//, '' ); return table.charAt( 0 ).toUpperCase() + table.substr( 1 ); }
[ "function", "_tableName", "(", ")", "{", "if", "(", "this", ".", "tableName", ")", "{", "return", "_", ".", "result", "(", "this", ",", "'tableName'", ")", ";", "}", "var", "urlAttributeName", "=", "this", "instanceof", "Backbone", ".", "DynamoDB", ".", "Model", "?", "'urlRoot'", ":", "'url'", ",", "table", "=", "_", ".", "result", "(", "this", ",", "urlAttributeName", ")", ".", "replace", "(", "/", "^\\/", "/", ",", "''", ")", ";", "return", "table", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "table", ".", "substr", "(", "1", ")", ";", "}" ]
Determines the name of the table for the Model or Collection instance. It returns the instance's `tableName` property, if it has one. Otherwise, it determines the name using the `urlRoot` property, if it's a Model, or the `url` property if it's a Collection.
[ "Determines", "the", "name", "of", "the", "table", "for", "the", "Model", "or", "Collection", "instance", ".", "It", "returns", "the", "instance", "s", "tableName", "property", "if", "it", "has", "one", ".", "Otherwise", "it", "determines", "the", "name", "using", "the", "urlRoot", "property", "if", "it", "s", "a", "Model", "or", "the", "url", "property", "if", "it", "s", "a", "Collection", "." ]
a501865f8513d27f6577289d7cf4a20324075146
https://github.com/serg-io/backbone-dynamodb/blob/a501865f8513d27f6577289d7cf4a20324075146/backbone-dynamodb.js#L403-L412
43,716
serg-io/backbone-dynamodb
backbone-dynamodb.js
function() { var hashKey = _.result( this, 'hashAttribute' ) || _.result( this, 'idAttribute' ), rangeKey = _.result( this, 'rangeAttribute' ), hashValue = this.get( hashKey ), rangeValue = rangeKey ? this.get( rangeKey ) : null; return hashValue == null || ( rangeKey && rangeValue == null ); }
javascript
function() { var hashKey = _.result( this, 'hashAttribute' ) || _.result( this, 'idAttribute' ), rangeKey = _.result( this, 'rangeAttribute' ), hashValue = this.get( hashKey ), rangeValue = rangeKey ? this.get( rangeKey ) : null; return hashValue == null || ( rangeKey && rangeValue == null ); }
[ "function", "(", ")", "{", "var", "hashKey", "=", "_", ".", "result", "(", "this", ",", "'hashAttribute'", ")", "||", "_", ".", "result", "(", "this", ",", "'idAttribute'", ")", ",", "rangeKey", "=", "_", ".", "result", "(", "this", ",", "'rangeAttribute'", ")", ",", "hashValue", "=", "this", ".", "get", "(", "hashKey", ")", ",", "rangeValue", "=", "rangeKey", "?", "this", ".", "get", "(", "rangeKey", ")", ":", "null", ";", "return", "hashValue", "==", "null", "||", "(", "rangeKey", "&&", "rangeValue", "==", "null", ")", ";", "}" ]
Determines if the model is new.
[ "Determines", "if", "the", "model", "is", "new", "." ]
a501865f8513d27f6577289d7cf4a20324075146
https://github.com/serg-io/backbone-dynamodb/blob/a501865f8513d27f6577289d7cf4a20324075146/backbone-dynamodb.js#L491-L498
43,717
serg-io/backbone-dynamodb
backbone-dynamodb.js
function (dynamoDbParams, options) { var _options = { query: dynamoDbParams }; _.extend( _options, options ); return this.fetch( _options ); }
javascript
function (dynamoDbParams, options) { var _options = { query: dynamoDbParams }; _.extend( _options, options ); return this.fetch( _options ); }
[ "function", "(", "dynamoDbParams", ",", "options", ")", "{", "var", "_options", "=", "{", "query", ":", "dynamoDbParams", "}", ";", "_", ".", "extend", "(", "_options", ",", "options", ")", ";", "return", "this", ".", "fetch", "(", "_options", ")", ";", "}" ]
Sends a "Query" request to DynamoDB to "fetch" a collection. @param {Object} dynamoDbParams DynamoDB [query](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#query-property) parameters. @param {Object} options Additional `fetch` options.
[ "Sends", "a", "Query", "request", "to", "DynamoDB", "to", "fetch", "a", "collection", "." ]
a501865f8513d27f6577289d7cf4a20324075146
https://github.com/serg-io/backbone-dynamodb/blob/a501865f8513d27f6577289d7cf4a20324075146/backbone-dynamodb.js#L642-L646
43,718
serg-io/backbone-dynamodb
backbone-dynamodb.js
function (dynamoDbParams, options) { var _options = { scan: dynamoDbParams }; _.extend( _options, options ); return this.fetch( _options ); }
javascript
function (dynamoDbParams, options) { var _options = { scan: dynamoDbParams }; _.extend( _options, options ); return this.fetch( _options ); }
[ "function", "(", "dynamoDbParams", ",", "options", ")", "{", "var", "_options", "=", "{", "scan", ":", "dynamoDbParams", "}", ";", "_", ".", "extend", "(", "_options", ",", "options", ")", ";", "return", "this", ".", "fetch", "(", "_options", ")", ";", "}" ]
Sends a "Scan" request to DynamoDB to "fetch" a collection. @param {Object} dynamoDbParams DynamoDB [scan](http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB.html#scan-property) parameters. @param {Object} options Additional `fetch` options.
[ "Sends", "a", "Scan", "request", "to", "DynamoDB", "to", "fetch", "a", "collection", "." ]
a501865f8513d27f6577289d7cf4a20324075146
https://github.com/serg-io/backbone-dynamodb/blob/a501865f8513d27f6577289d7cf4a20324075146/backbone-dynamodb.js#L653-L657
43,719
KirinJS/Kirin
javascript/lib/core/kirin-webview.js
function (jsName, methodName) { return function () { var args = slice.call(arguments, 0); var i = 0, max, arg, util, id, exportable; for (max=args.length; i<max; i++) { arg = args[i]; if (arg.kirin_bridgeUtils) { util = arg.kirin_bridgeUtils; util.fillInDefaults(arg); util.validate(arg); exportable = util.createExportableObject(arg); if (util.hasCallbacks(arg)) { // TODO stash the original object some place where we can use it for callbacks later. id = tokenGenerator(jsName, methodName); exportable.__id = id; nativeAccessibleJavascriptObjects[id] = arg; } args[i] = exportable; } else if (typeof arg === 'function') { console.error("OMG WE'RE WRAPPING AN ERRANT FUNCTION"); args[i] = wrapCallback(arg, jsName, methodName); } } args.unshift(jsName + "." + methodName); return Native.exec.apply(null, args); }; }
javascript
function (jsName, methodName) { return function () { var args = slice.call(arguments, 0); var i = 0, max, arg, util, id, exportable; for (max=args.length; i<max; i++) { arg = args[i]; if (arg.kirin_bridgeUtils) { util = arg.kirin_bridgeUtils; util.fillInDefaults(arg); util.validate(arg); exportable = util.createExportableObject(arg); if (util.hasCallbacks(arg)) { // TODO stash the original object some place where we can use it for callbacks later. id = tokenGenerator(jsName, methodName); exportable.__id = id; nativeAccessibleJavascriptObjects[id] = arg; } args[i] = exportable; } else if (typeof arg === 'function') { console.error("OMG WE'RE WRAPPING AN ERRANT FUNCTION"); args[i] = wrapCallback(arg, jsName, methodName); } } args.unshift(jsName + "." + methodName); return Native.exec.apply(null, args); }; }
[ "function", "(", "jsName", ",", "methodName", ")", "{", "return", "function", "(", ")", "{", "var", "args", "=", "slice", ".", "call", "(", "arguments", ",", "0", ")", ";", "var", "i", "=", "0", ",", "max", ",", "arg", ",", "util", ",", "id", ",", "exportable", ";", "for", "(", "max", "=", "args", ".", "length", ";", "i", "<", "max", ";", "i", "++", ")", "{", "arg", "=", "args", "[", "i", "]", ";", "if", "(", "arg", ".", "kirin_bridgeUtils", ")", "{", "util", "=", "arg", ".", "kirin_bridgeUtils", ";", "util", ".", "fillInDefaults", "(", "arg", ")", ";", "util", ".", "validate", "(", "arg", ")", ";", "exportable", "=", "util", ".", "createExportableObject", "(", "arg", ")", ";", "if", "(", "util", ".", "hasCallbacks", "(", "arg", ")", ")", "{", "// TODO stash the original object some place where we can use it for callbacks later.", "id", "=", "tokenGenerator", "(", "jsName", ",", "methodName", ")", ";", "exportable", ".", "__id", "=", "id", ";", "nativeAccessibleJavascriptObjects", "[", "id", "]", "=", "arg", ";", "}", "args", "[", "i", "]", "=", "exportable", ";", "}", "else", "if", "(", "typeof", "arg", "===", "'function'", ")", "{", "console", ".", "error", "(", "\"OMG WE'RE WRAPPING AN ERRANT FUNCTION\"", ")", ";", "args", "[", "i", "]", "=", "wrapCallback", "(", "arg", ",", "jsName", ",", "methodName", ")", ";", "}", "}", "args", ".", "unshift", "(", "jsName", "+", "\".\"", "+", "methodName", ")", ";", "return", "Native", ".", "exec", ".", "apply", "(", "null", ",", "args", ")", ";", "}", ";", "}" ]
This is the function call that every call out to native goes through.
[ "This", "is", "the", "function", "call", "that", "every", "call", "out", "to", "native", "goes", "through", "." ]
d40e86ca89c40b5d3e0c129c24ff3b77ed3d28e1
https://github.com/KirinJS/Kirin/blob/d40e86ca89c40b5d3e0c129c24ff3b77ed3d28e1/javascript/lib/core/kirin-webview.js#L84-L113
43,720
KirinJS/Kirin
javascript/lib/core/kirin-webview.js
handleError
function handleError(during, e) { /* * { "message": "Can't find variable: cardObject", "line": 505, "sourceId": 250182872, "sourceURL": "file:///Users/james/Library/Application%20Support/iPhone%20Simulator/4.3.2/Applications/ADE774FF-B033-46A2-9CBA-DD362196E1F7/Moo.app/generated-javascript//src/controller/CardController.js", "expressionBeginOffset": 22187, "expressionCaretOffset": 22197, "expressionEndOffset": 22197 } */ console.error("-------------------------------------------------"); console.error("Exception found " + during); console.error("Message: " + e.message); console.error("at : " + e.line); var filename = e.sourceURL || "unknown"; /*jshint regexp:false*/ filename = filename.replace(/.*generated-javascript\//, ""); /*jshint regexp:true*/ console.error("file : " + filename); console.error("url : " + e.sourceURL); var stack = e.stack || e.stacktrace; if (stack) { console.error(stack); } else { console.log("No stack trace"); } }
javascript
function handleError(during, e) { /* * { "message": "Can't find variable: cardObject", "line": 505, "sourceId": 250182872, "sourceURL": "file:///Users/james/Library/Application%20Support/iPhone%20Simulator/4.3.2/Applications/ADE774FF-B033-46A2-9CBA-DD362196E1F7/Moo.app/generated-javascript//src/controller/CardController.js", "expressionBeginOffset": 22187, "expressionCaretOffset": 22197, "expressionEndOffset": 22197 } */ console.error("-------------------------------------------------"); console.error("Exception found " + during); console.error("Message: " + e.message); console.error("at : " + e.line); var filename = e.sourceURL || "unknown"; /*jshint regexp:false*/ filename = filename.replace(/.*generated-javascript\//, ""); /*jshint regexp:true*/ console.error("file : " + filename); console.error("url : " + e.sourceURL); var stack = e.stack || e.stacktrace; if (stack) { console.error(stack); } else { console.log("No stack trace"); } }
[ "function", "handleError", "(", "during", ",", "e", ")", "{", "/*\n * {\n \"message\": \"Can't find variable: cardObject\",\n \"line\": 505,\n \"sourceId\": 250182872,\n \"sourceURL\": \"file:///Users/james/Library/Application%20Support/iPhone%20Simulator/4.3.2/Applications/ADE774FF-B033-46A2-9CBA-DD362196E1F7/Moo.app/generated-javascript//src/controller/CardController.js\",\n \"expressionBeginOffset\": 22187,\n \"expressionCaretOffset\": 22197,\n \"expressionEndOffset\": 22197\n }\n */", "console", ".", "error", "(", "\"-------------------------------------------------\"", ")", ";", "console", ".", "error", "(", "\"Exception found \"", "+", "during", ")", ";", "console", ".", "error", "(", "\"Message: \"", "+", "e", ".", "message", ")", ";", "console", ".", "error", "(", "\"at : \"", "+", "e", ".", "line", ")", ";", "var", "filename", "=", "e", ".", "sourceURL", "||", "\"unknown\"", ";", "/*jshint regexp:false*/", "filename", "=", "filename", ".", "replace", "(", "/", ".*generated-javascript\\/", "/", ",", "\"\"", ")", ";", "/*jshint regexp:true*/", "console", ".", "error", "(", "\"file : \"", "+", "filename", ")", ";", "console", ".", "error", "(", "\"url : \"", "+", "e", ".", "sourceURL", ")", ";", "var", "stack", "=", "e", ".", "stack", "||", "e", ".", "stacktrace", ";", "if", "(", "stack", ")", "{", "console", ".", "error", "(", "stack", ")", ";", "}", "else", "{", "console", ".", "log", "(", "\"No stack trace\"", ")", ";", "}", "}" ]
This is a generic error handler. It does its best to report a stack trace, or an error or *something*. Unfortunately, some devices are better suported than others. e.g. Android >2.0, iOS 4.3 and iOS 6.0 are pretty good at providing errors (e.g. file location, stack trace etc) iOS5 was shockingly bad. @param during - what were you doing when you saw this error. This is a string. @param e - the error itself. This, hopefully, is an Error object.
[ "This", "is", "a", "generic", "error", "handler", "." ]
d40e86ca89c40b5d3e0c129c24ff3b77ed3d28e1
https://github.com/KirinJS/Kirin/blob/d40e86ca89c40b5d3e0c129c24ff3b77ed3d28e1/javascript/lib/core/kirin-webview.js#L140-L170
43,721
KirinJS/Kirin
javascript/lib/core/kirin-webview.js
resolveModule
function resolveModule(moduleName) { if (loadedObjects[moduleName]) { return loadedObjects[moduleName]; } var aModule, anObject, MyModule; if (gwtClasses) { aModule = gwtClasses[moduleName]; } if (!aModule) { try { aModule = myRequire(moduleName); } catch (e) { // we don't need to do anymore, // as require will have reported the problem } } if (aModule) { if (typeof aModule === 'function') { MyModule = aModule; anObject = new MyModule(); } else { anObject = aModule; } loadedObjects[moduleName] = anObject; return anObject; } // we've tried require, and gwt modules. // require() will have reported the error already. //throw new Error("Cannot load module " + moduleName); }
javascript
function resolveModule(moduleName) { if (loadedObjects[moduleName]) { return loadedObjects[moduleName]; } var aModule, anObject, MyModule; if (gwtClasses) { aModule = gwtClasses[moduleName]; } if (!aModule) { try { aModule = myRequire(moduleName); } catch (e) { // we don't need to do anymore, // as require will have reported the problem } } if (aModule) { if (typeof aModule === 'function') { MyModule = aModule; anObject = new MyModule(); } else { anObject = aModule; } loadedObjects[moduleName] = anObject; return anObject; } // we've tried require, and gwt modules. // require() will have reported the error already. //throw new Error("Cannot load module " + moduleName); }
[ "function", "resolveModule", "(", "moduleName", ")", "{", "if", "(", "loadedObjects", "[", "moduleName", "]", ")", "{", "return", "loadedObjects", "[", "moduleName", "]", ";", "}", "var", "aModule", ",", "anObject", ",", "MyModule", ";", "if", "(", "gwtClasses", ")", "{", "aModule", "=", "gwtClasses", "[", "moduleName", "]", ";", "}", "if", "(", "!", "aModule", ")", "{", "try", "{", "aModule", "=", "myRequire", "(", "moduleName", ")", ";", "}", "catch", "(", "e", ")", "{", "// we don't need to do anymore, ", "// as require will have reported the problem", "}", "}", "if", "(", "aModule", ")", "{", "if", "(", "typeof", "aModule", "===", "'function'", ")", "{", "MyModule", "=", "aModule", ";", "anObject", "=", "new", "MyModule", "(", ")", ";", "}", "else", "{", "anObject", "=", "aModule", ";", "}", "loadedObjects", "[", "moduleName", "]", "=", "anObject", ";", "return", "anObject", ";", "}", "// we've tried require, and gwt modules.", "// require() will have reported the error already.", "//throw new Error(\"Cannot load module \" + moduleName);", "}" ]
Finds the named module. It tries quite hard to do this, looking at where gwtClasses may be stashed, and the browserify.require mechanism. If the resulting object is a function, then it is assumed that the function is a constructor, and an object is newed. Once we have an object to return, we keep it around as a cache. This is to preserve the require-like semantics, and also to allow multiple calls to the same object from native. @param moduleName @returns anObject.
[ "Finds", "the", "named", "module", "." ]
d40e86ca89c40b5d3e0c129c24ff3b77ed3d28e1
https://github.com/KirinJS/Kirin/blob/d40e86ca89c40b5d3e0c129c24ff3b77ed3d28e1/javascript/lib/core/kirin-webview.js#L185-L216
43,722
bhoriuchi/vsphere-connect
archive/v1/specUtil.js
traversalSpec
function traversalSpec(args) { return { attributes: { 'xsi:type': 'TraversalSpec' }, type: args.listSpec.type, path: args.listSpec.path, skip: false }; }
javascript
function traversalSpec(args) { return { attributes: { 'xsi:type': 'TraversalSpec' }, type: args.listSpec.type, path: args.listSpec.path, skip: false }; }
[ "function", "traversalSpec", "(", "args", ")", "{", "return", "{", "attributes", ":", "{", "'xsi:type'", ":", "'TraversalSpec'", "}", ",", "type", ":", "args", ".", "listSpec", ".", "type", ",", "path", ":", "args", ".", "listSpec", ".", "path", ",", "skip", ":", "false", "}", ";", "}" ]
new traversal spec
[ "new", "traversal", "spec" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/specUtil.js#L16-L25
43,723
bhoriuchi/vsphere-connect
archive/v1/specUtil.js
objectSpec
function objectSpec(args) { var set = []; if (!args.id) { // create a base object var spec = { attributes: { 'xsi:type': 'ObjectSpec' } }; // check for containerview if (args.listSpec.type === 'ContainerView' && args.containerView) { spec.obj = args.containerView; } else { spec.obj = util.moRef(args.listSpec.type, args.listSpec.id); } // set the skip and select set spec.skip = (typeof(args.skip) === 'boolean') ? args.skip : true; spec.selectSet = selectionSpec(args); // push the object set.push(spec); } else { // ensure args.id is an array of ids even if there is only one id args.id = Array.isArray(args.id) ? args.id : [args.id]; // loop through each if and create an object spec _.forEach(args.id, function(id) { set.push({ attributes: { 'xsi:type': 'ObjectSpec', }, obj: util.moRef(args.type, id) }); }); } // return the specSet return set; }
javascript
function objectSpec(args) { var set = []; if (!args.id) { // create a base object var spec = { attributes: { 'xsi:type': 'ObjectSpec' } }; // check for containerview if (args.listSpec.type === 'ContainerView' && args.containerView) { spec.obj = args.containerView; } else { spec.obj = util.moRef(args.listSpec.type, args.listSpec.id); } // set the skip and select set spec.skip = (typeof(args.skip) === 'boolean') ? args.skip : true; spec.selectSet = selectionSpec(args); // push the object set.push(spec); } else { // ensure args.id is an array of ids even if there is only one id args.id = Array.isArray(args.id) ? args.id : [args.id]; // loop through each if and create an object spec _.forEach(args.id, function(id) { set.push({ attributes: { 'xsi:type': 'ObjectSpec', }, obj: util.moRef(args.type, id) }); }); } // return the specSet return set; }
[ "function", "objectSpec", "(", "args", ")", "{", "var", "set", "=", "[", "]", ";", "if", "(", "!", "args", ".", "id", ")", "{", "// create a base object", "var", "spec", "=", "{", "attributes", ":", "{", "'xsi:type'", ":", "'ObjectSpec'", "}", "}", ";", "// check for containerview", "if", "(", "args", ".", "listSpec", ".", "type", "===", "'ContainerView'", "&&", "args", ".", "containerView", ")", "{", "spec", ".", "obj", "=", "args", ".", "containerView", ";", "}", "else", "{", "spec", ".", "obj", "=", "util", ".", "moRef", "(", "args", ".", "listSpec", ".", "type", ",", "args", ".", "listSpec", ".", "id", ")", ";", "}", "// set the skip and select set", "spec", ".", "skip", "=", "(", "typeof", "(", "args", ".", "skip", ")", "===", "'boolean'", ")", "?", "args", ".", "skip", ":", "true", ";", "spec", ".", "selectSet", "=", "selectionSpec", "(", "args", ")", ";", "// push the object", "set", ".", "push", "(", "spec", ")", ";", "}", "else", "{", "// ensure args.id is an array of ids even if there is only one id", "args", ".", "id", "=", "Array", ".", "isArray", "(", "args", ".", "id", ")", "?", "args", ".", "id", ":", "[", "args", ".", "id", "]", ";", "// loop through each if and create an object spec", "_", ".", "forEach", "(", "args", ".", "id", ",", "function", "(", "id", ")", "{", "set", ".", "push", "(", "{", "attributes", ":", "{", "'xsi:type'", ":", "'ObjectSpec'", ",", "}", ",", "obj", ":", "util", ".", "moRef", "(", "args", ".", "type", ",", "id", ")", "}", ")", ";", "}", ")", ";", "}", "// return the specSet", "return", "set", ";", "}" ]
new object spec
[ "new", "object", "spec" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/specUtil.js#L35-L76
43,724
bhoriuchi/vsphere-connect
archive/v1/specUtil.js
propertySpec
function propertySpec(args) { // create a basic specification var spec = { attributes: { 'xsi:type': 'PropertySpec' }, type: args.type }; // if an array of properties was passed, validate the properties if (Array.isArray(args.properties) && args.properties.length > 0) { var validPaths = util.filterValidPaths(args.type, args.properties, args.apiVersion); if (validPaths.length > 0) { spec.pathSet = validPaths; } } // if the properties is a string literal "all" else if (args.properties === 'all') { spec.all = true; } // return the specification return [spec]; }
javascript
function propertySpec(args) { // create a basic specification var spec = { attributes: { 'xsi:type': 'PropertySpec' }, type: args.type }; // if an array of properties was passed, validate the properties if (Array.isArray(args.properties) && args.properties.length > 0) { var validPaths = util.filterValidPaths(args.type, args.properties, args.apiVersion); if (validPaths.length > 0) { spec.pathSet = validPaths; } } // if the properties is a string literal "all" else if (args.properties === 'all') { spec.all = true; } // return the specification return [spec]; }
[ "function", "propertySpec", "(", "args", ")", "{", "// create a basic specification", "var", "spec", "=", "{", "attributes", ":", "{", "'xsi:type'", ":", "'PropertySpec'", "}", ",", "type", ":", "args", ".", "type", "}", ";", "// if an array of properties was passed, validate the properties", "if", "(", "Array", ".", "isArray", "(", "args", ".", "properties", ")", "&&", "args", ".", "properties", ".", "length", ">", "0", ")", "{", "var", "validPaths", "=", "util", ".", "filterValidPaths", "(", "args", ".", "type", ",", "args", ".", "properties", ",", "args", ".", "apiVersion", ")", ";", "if", "(", "validPaths", ".", "length", ">", "0", ")", "{", "spec", ".", "pathSet", "=", "validPaths", ";", "}", "}", "// if the properties is a string literal \"all\"", "else", "if", "(", "args", ".", "properties", "===", "'all'", ")", "{", "spec", ".", "all", "=", "true", ";", "}", "// return the specification", "return", "[", "spec", "]", ";", "}" ]
new property spec
[ "new", "property", "spec" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/specUtil.js#L79-L105
43,725
slorber/backspace-disabler
index.js
isInActiveContentEditable
function isInActiveContentEditable(node) { while (node) { if ( node.getAttribute && node.getAttribute("contenteditable") && node.getAttribute("contenteditable").toUpperCase() === "TRUE" ) { return true } node = node.parentNode } return false }
javascript
function isInActiveContentEditable(node) { while (node) { if ( node.getAttribute && node.getAttribute("contenteditable") && node.getAttribute("contenteditable").toUpperCase() === "TRUE" ) { return true } node = node.parentNode } return false }
[ "function", "isInActiveContentEditable", "(", "node", ")", "{", "while", "(", "node", ")", "{", "if", "(", "node", ".", "getAttribute", "&&", "node", ".", "getAttribute", "(", "\"contenteditable\"", ")", "&&", "node", ".", "getAttribute", "(", "\"contenteditable\"", ")", ".", "toUpperCase", "(", ")", "===", "\"TRUE\"", ")", "{", "return", "true", "}", "node", "=", "node", ".", "parentNode", "}", "return", "false", "}" ]
Returns true if the node is or is inside an active contenteditable
[ "Returns", "true", "if", "the", "node", "is", "or", "is", "inside", "an", "active", "contenteditable" ]
d57c4c6642a090aa03459b25db5e9d06c755e292
https://github.com/slorber/backspace-disabler/blob/d57c4c6642a090aa03459b25db5e9d06c755e292/index.js#L53-L65
43,726
slorber/backspace-disabler
index.js
connectedToTheDom
function connectedToTheDom(node) { // IE does not have contains method on document element, only body var container = node.ownerDocument.contains ? node.ownerDocument : node.ownerDocument.body; return container.contains(node); }
javascript
function connectedToTheDom(node) { // IE does not have contains method on document element, only body var container = node.ownerDocument.contains ? node.ownerDocument : node.ownerDocument.body; return container.contains(node); }
[ "function", "connectedToTheDom", "(", "node", ")", "{", "// IE does not have contains method on document element, only body ", "var", "container", "=", "node", ".", "ownerDocument", ".", "contains", "?", "node", ".", "ownerDocument", ":", "node", ".", "ownerDocument", ".", "body", ";", "return", "container", ".", "contains", "(", "node", ")", ";", "}" ]
returns true if the element is contained within a document
[ "returns", "true", "if", "the", "element", "is", "contained", "within", "a", "document" ]
d57c4c6642a090aa03459b25db5e9d06c755e292
https://github.com/slorber/backspace-disabler/blob/d57c4c6642a090aa03459b25db5e9d06c755e292/index.js#L68-L72
43,727
andrewimm/js-struct
lib/sign.js
sign
function sign(value, pow) { const msb = 1 << pow; if ((value & msb) === 0) { return value; } let neg = -1 * (value & msb); neg += (value & (msb - 1)); return neg; }
javascript
function sign(value, pow) { const msb = 1 << pow; if ((value & msb) === 0) { return value; } let neg = -1 * (value & msb); neg += (value & (msb - 1)); return neg; }
[ "function", "sign", "(", "value", ",", "pow", ")", "{", "const", "msb", "=", "1", "<<", "pow", ";", "if", "(", "(", "value", "&", "msb", ")", "===", "0", ")", "{", "return", "value", ";", "}", "let", "neg", "=", "-", "1", "*", "(", "value", "&", "msb", ")", ";", "neg", "+=", "(", "value", "&", "(", "msb", "-", "1", ")", ")", ";", "return", "neg", ";", "}" ]
Convert a two's-complement negative to its JS numeric value
[ "Convert", "a", "two", "s", "-", "complement", "negative", "to", "its", "JS", "numeric", "value" ]
730cb45660e36910a65dc515a880a26aca18d4b6
https://github.com/andrewimm/js-struct/blob/730cb45660e36910a65dc515a880a26aca18d4b6/lib/sign.js#L6-L14
43,728
simonguo/hbook
lib/utils/page.js
renderDom
function renderDom($, dom, options) { if (!dom && $._root && $._root.children) { dom = $._root.children; } options = options|| dom.options || $._options; return domSerializer(dom, options); }
javascript
function renderDom($, dom, options) { if (!dom && $._root && $._root.children) { dom = $._root.children; } options = options|| dom.options || $._options; return domSerializer(dom, options); }
[ "function", "renderDom", "(", "$", ",", "dom", ",", "options", ")", "{", "if", "(", "!", "dom", "&&", "$", ".", "_root", "&&", "$", ".", "_root", ".", "children", ")", "{", "dom", "=", "$", ".", "_root", ".", "children", ";", "}", "options", "=", "options", "||", "dom", ".", "options", "||", "$", ".", "_options", ";", "return", "domSerializer", "(", "dom", ",", "options", ")", ";", "}" ]
Render a cheerio dom as html
[ "Render", "a", "cheerio", "dom", "as", "html" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/utils/page.js#L22-L29
43,729
simonguo/hbook
lib/utils/page.js
convertImages
function convertImages(images, options) { if (!options.convertImages) return Q(); var downloaded = []; options.book.log.debug.ln('convert ', images.length, 'images to png'); return batch.execEach(images, { max: 100, fn: function(image) { var imgin = path.resolve(options.book.options.output, image.source); return Q() // Write image if need to be download .then(function() { if (!image.origin && !_.contains(downloaded, image.origin)) return; options.book.log.debug('download image', image.origin, '...'); downloaded.push(image.origin); return options.book.log.debug.promise(fs.writeStream(imgin, request(image.origin))) .fail(function(err) { if (!_.isError(err)) err = new Error(err); err.message = 'Fail downloading '+image.origin+': '+err.message; throw err; }); }) // Write svg if content .then(function() { if (!image.content) return; return fs.writeFile(imgin, image.content); }) // Convert .then(function() { if (!image.dest) return; var imgout = path.resolve(options.book.options.output, image.dest); options.book.log.debug('convert image', image.source, 'to', image.dest, '...'); return options.book.log.debug.promise(imgUtils.convertSVG(imgin, imgout)); }); } }) .then(function() { options.book.log.debug.ok(images.length+' images converted with success'); }); }
javascript
function convertImages(images, options) { if (!options.convertImages) return Q(); var downloaded = []; options.book.log.debug.ln('convert ', images.length, 'images to png'); return batch.execEach(images, { max: 100, fn: function(image) { var imgin = path.resolve(options.book.options.output, image.source); return Q() // Write image if need to be download .then(function() { if (!image.origin && !_.contains(downloaded, image.origin)) return; options.book.log.debug('download image', image.origin, '...'); downloaded.push(image.origin); return options.book.log.debug.promise(fs.writeStream(imgin, request(image.origin))) .fail(function(err) { if (!_.isError(err)) err = new Error(err); err.message = 'Fail downloading '+image.origin+': '+err.message; throw err; }); }) // Write svg if content .then(function() { if (!image.content) return; return fs.writeFile(imgin, image.content); }) // Convert .then(function() { if (!image.dest) return; var imgout = path.resolve(options.book.options.output, image.dest); options.book.log.debug('convert image', image.source, 'to', image.dest, '...'); return options.book.log.debug.promise(imgUtils.convertSVG(imgin, imgout)); }); } }) .then(function() { options.book.log.debug.ok(images.length+' images converted with success'); }); }
[ "function", "convertImages", "(", "images", ",", "options", ")", "{", "if", "(", "!", "options", ".", "convertImages", ")", "return", "Q", "(", ")", ";", "var", "downloaded", "=", "[", "]", ";", "options", ".", "book", ".", "log", ".", "debug", ".", "ln", "(", "'convert '", ",", "images", ".", "length", ",", "'images to png'", ")", ";", "return", "batch", ".", "execEach", "(", "images", ",", "{", "max", ":", "100", ",", "fn", ":", "function", "(", "image", ")", "{", "var", "imgin", "=", "path", ".", "resolve", "(", "options", ".", "book", ".", "options", ".", "output", ",", "image", ".", "source", ")", ";", "return", "Q", "(", ")", "// Write image if need to be download", ".", "then", "(", "function", "(", ")", "{", "if", "(", "!", "image", ".", "origin", "&&", "!", "_", ".", "contains", "(", "downloaded", ",", "image", ".", "origin", ")", ")", "return", ";", "options", ".", "book", ".", "log", ".", "debug", "(", "'download image'", ",", "image", ".", "origin", ",", "'...'", ")", ";", "downloaded", ".", "push", "(", "image", ".", "origin", ")", ";", "return", "options", ".", "book", ".", "log", ".", "debug", ".", "promise", "(", "fs", ".", "writeStream", "(", "imgin", ",", "request", "(", "image", ".", "origin", ")", ")", ")", ".", "fail", "(", "function", "(", "err", ")", "{", "if", "(", "!", "_", ".", "isError", "(", "err", ")", ")", "err", "=", "new", "Error", "(", "err", ")", ";", "err", ".", "message", "=", "'Fail downloading '", "+", "image", ".", "origin", "+", "': '", "+", "err", ".", "message", ";", "throw", "err", ";", "}", ")", ";", "}", ")", "// Write svg if content", ".", "then", "(", "function", "(", ")", "{", "if", "(", "!", "image", ".", "content", ")", "return", ";", "return", "fs", ".", "writeFile", "(", "imgin", ",", "image", ".", "content", ")", ";", "}", ")", "// Convert", ".", "then", "(", "function", "(", ")", "{", "if", "(", "!", "image", ".", "dest", ")", "return", ";", "var", "imgout", "=", "path", ".", "resolve", "(", "options", ".", "book", ".", "options", ".", "output", ",", "image", ".", "dest", ")", ";", "options", ".", "book", ".", "log", ".", "debug", "(", "'convert image'", ",", "image", ".", "source", ",", "'to'", ",", "image", ".", "dest", ",", "'...'", ")", ";", "return", "options", ".", "book", ".", "log", ".", "debug", ".", "promise", "(", "imgUtils", ".", "convertSVG", "(", "imgin", ",", "imgout", ")", ")", ";", "}", ")", ";", "}", "}", ")", ".", "then", "(", "function", "(", ")", "{", "options", ".", "book", ".", "log", ".", "debug", ".", "ok", "(", "images", ".", "length", "+", "' images converted with success'", ")", ";", "}", ")", ";", "}" ]
Convert svg images to png
[ "Convert", "svg", "images", "to", "png" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/utils/page.js#L298-L343
43,730
simonguo/hbook
lib/utils/page.js
normalizePage
function normalizePage(sections, options) { options = _.defaults(options || {}, { // Current book book: null, // Do we need to convert svg? convertImages: false, // Current file path input: '.', // Navigation to use to transform path navigation: {}, // Directory parent of the file currently in rendering process base: './', // Directory parent from the html output output: './', // Glossary terms glossary: [] }); // List of images to convert var toConvert = []; sections = _.map(sections, function(section) { if (section.type != 'normal') return section; var out = normalizeHtml(section.content, options); toConvert = toConvert.concat(out.images); section.content = out.html; return section; }); return Q() .then(function() { toConvert = _.uniq(toConvert, 'source'); return convertImages(toConvert, options); }) .thenResolve(sections); }
javascript
function normalizePage(sections, options) { options = _.defaults(options || {}, { // Current book book: null, // Do we need to convert svg? convertImages: false, // Current file path input: '.', // Navigation to use to transform path navigation: {}, // Directory parent of the file currently in rendering process base: './', // Directory parent from the html output output: './', // Glossary terms glossary: [] }); // List of images to convert var toConvert = []; sections = _.map(sections, function(section) { if (section.type != 'normal') return section; var out = normalizeHtml(section.content, options); toConvert = toConvert.concat(out.images); section.content = out.html; return section; }); return Q() .then(function() { toConvert = _.uniq(toConvert, 'source'); return convertImages(toConvert, options); }) .thenResolve(sections); }
[ "function", "normalizePage", "(", "sections", ",", "options", ")", "{", "options", "=", "_", ".", "defaults", "(", "options", "||", "{", "}", ",", "{", "// Current book", "book", ":", "null", ",", "// Do we need to convert svg?", "convertImages", ":", "false", ",", "// Current file path", "input", ":", "'.'", ",", "// Navigation to use to transform path", "navigation", ":", "{", "}", ",", "// Directory parent of the file currently in rendering process", "base", ":", "'./'", ",", "// Directory parent from the html output", "output", ":", "'./'", ",", "// Glossary terms", "glossary", ":", "[", "]", "}", ")", ";", "// List of images to convert", "var", "toConvert", "=", "[", "]", ";", "sections", "=", "_", ".", "map", "(", "sections", ",", "function", "(", "section", ")", "{", "if", "(", "section", ".", "type", "!=", "'normal'", ")", "return", "section", ";", "var", "out", "=", "normalizeHtml", "(", "section", ".", "content", ",", "options", ")", ";", "toConvert", "=", "toConvert", ".", "concat", "(", "out", ".", "images", ")", ";", "section", ".", "content", "=", "out", ".", "html", ";", "return", "section", ";", "}", ")", ";", "return", "Q", "(", ")", ".", "then", "(", "function", "(", ")", "{", "toConvert", "=", "_", ".", "uniq", "(", "toConvert", ",", "'source'", ")", ";", "return", "convertImages", "(", "toConvert", ",", "options", ")", ";", "}", ")", ".", "thenResolve", "(", "sections", ")", ";", "}" ]
Adapt page content to be relative to a base folder
[ "Adapt", "page", "content", "to", "be", "relative", "to", "a", "base", "folder" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/utils/page.js#L346-L389
43,731
simonguo/hbook
lib/utils/batch.js
execEach
function execEach(items, options) { if (_.size(items) === 0) return Q(); var concurrents = 0, d = Q.defer(), pending = []; options = _.defaults(options || {}, { max: 100, fn: function() {} }); function startItem(item, i) { if (concurrents >= options.max) { pending.push([item, i]); return; } concurrents++; Q() .then(function() { return options.fn(item, i); }) .then(function() { concurrents--; // Next pending var next = pending.shift(); if (concurrents === 0 && !next) { d.resolve(); } else if (next) { startItem.apply(null, next); } }) .fail(function(err) { pending = []; d.reject(err); }); } _.each(items, startItem); return d.promise; }
javascript
function execEach(items, options) { if (_.size(items) === 0) return Q(); var concurrents = 0, d = Q.defer(), pending = []; options = _.defaults(options || {}, { max: 100, fn: function() {} }); function startItem(item, i) { if (concurrents >= options.max) { pending.push([item, i]); return; } concurrents++; Q() .then(function() { return options.fn(item, i); }) .then(function() { concurrents--; // Next pending var next = pending.shift(); if (concurrents === 0 && !next) { d.resolve(); } else if (next) { startItem.apply(null, next); } }) .fail(function(err) { pending = []; d.reject(err); }); } _.each(items, startItem); return d.promise; }
[ "function", "execEach", "(", "items", ",", "options", ")", "{", "if", "(", "_", ".", "size", "(", "items", ")", "===", "0", ")", "return", "Q", "(", ")", ";", "var", "concurrents", "=", "0", ",", "d", "=", "Q", ".", "defer", "(", ")", ",", "pending", "=", "[", "]", ";", "options", "=", "_", ".", "defaults", "(", "options", "||", "{", "}", ",", "{", "max", ":", "100", ",", "fn", ":", "function", "(", ")", "{", "}", "}", ")", ";", "function", "startItem", "(", "item", ",", "i", ")", "{", "if", "(", "concurrents", ">=", "options", ".", "max", ")", "{", "pending", ".", "push", "(", "[", "item", ",", "i", "]", ")", ";", "return", ";", "}", "concurrents", "++", ";", "Q", "(", ")", ".", "then", "(", "function", "(", ")", "{", "return", "options", ".", "fn", "(", "item", ",", "i", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "concurrents", "--", ";", "// Next pending", "var", "next", "=", "pending", ".", "shift", "(", ")", ";", "if", "(", "concurrents", "===", "0", "&&", "!", "next", ")", "{", "d", ".", "resolve", "(", ")", ";", "}", "else", "if", "(", "next", ")", "{", "startItem", ".", "apply", "(", "null", ",", "next", ")", ";", "}", "}", ")", ".", "fail", "(", "function", "(", "err", ")", "{", "pending", "=", "[", "]", ";", "d", ".", "reject", "(", "err", ")", ";", "}", ")", ";", "}", "_", ".", "each", "(", "items", ",", "startItem", ")", ";", "return", "d", ".", "promise", ";", "}" ]
Execute a method for all element
[ "Execute", "a", "method", "for", "all", "element" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/utils/batch.js#L5-L47
43,732
simonguo/hbook
lib/template.js
function(filepath, source) { var parser = parsers.get(path.extname(filepath)); var type = parser? parser.name : null; return that.applyShortcuts(type, source); }
javascript
function(filepath, source) { var parser = parsers.get(path.extname(filepath)); var type = parser? parser.name : null; return that.applyShortcuts(type, source); }
[ "function", "(", "filepath", ",", "source", ")", "{", "var", "parser", "=", "parsers", ".", "get", "(", "path", ".", "extname", "(", "filepath", ")", ")", ";", "var", "type", "=", "parser", "?", "parser", ".", "name", ":", "null", ";", "return", "that", ".", "applyShortcuts", "(", "type", ",", "source", ")", ";", "}" ]
Replace shortcuts in imported files
[ "Replace", "shortcuts", "in", "imported", "files" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/template.js#L29-L34
43,733
simonguo/hbook
theme/javascript/toolbar.js
createDropdownMenu
function createDropdownMenu(dropdown) { var $menu = $('<div>', { 'class': 'dropdown-menu', 'html': '<div class="dropdown-caret"><span class="caret-outer"></span><span class="caret-inner"></span></div>' }); if (_.isString(dropdown)) { $menu.append(dropdown); } else { var groups = _.map(dropdown, function(group) { if (_.isArray(group)) return group; else return [group]; }); // Create buttons groups _.each(groups, function(group) { var $group = $('<div>', { 'class': 'buttons' }); var sizeClass = 'size-'+group.length; // Append buttons _.each(group, function(btn) { btn = _.defaults(btn || {}, { text: '', className: '', onClick: defaultOnClick }); var $btn = $('<button>', { 'class': 'button '+sizeClass+' '+btn.className, 'text': btn.text }); $btn.click(btn.onClick); $group.append($btn); }); $menu.append($group); }); } return $menu; }
javascript
function createDropdownMenu(dropdown) { var $menu = $('<div>', { 'class': 'dropdown-menu', 'html': '<div class="dropdown-caret"><span class="caret-outer"></span><span class="caret-inner"></span></div>' }); if (_.isString(dropdown)) { $menu.append(dropdown); } else { var groups = _.map(dropdown, function(group) { if (_.isArray(group)) return group; else return [group]; }); // Create buttons groups _.each(groups, function(group) { var $group = $('<div>', { 'class': 'buttons' }); var sizeClass = 'size-'+group.length; // Append buttons _.each(group, function(btn) { btn = _.defaults(btn || {}, { text: '', className: '', onClick: defaultOnClick }); var $btn = $('<button>', { 'class': 'button '+sizeClass+' '+btn.className, 'text': btn.text }); $btn.click(btn.onClick); $group.append($btn); }); $menu.append($group); }); } return $menu; }
[ "function", "createDropdownMenu", "(", "dropdown", ")", "{", "var", "$menu", "=", "$", "(", "'<div>'", ",", "{", "'class'", ":", "'dropdown-menu'", ",", "'html'", ":", "'<div class=\"dropdown-caret\"><span class=\"caret-outer\"></span><span class=\"caret-inner\"></span></div>'", "}", ")", ";", "if", "(", "_", ".", "isString", "(", "dropdown", ")", ")", "{", "$menu", ".", "append", "(", "dropdown", ")", ";", "}", "else", "{", "var", "groups", "=", "_", ".", "map", "(", "dropdown", ",", "function", "(", "group", ")", "{", "if", "(", "_", ".", "isArray", "(", "group", ")", ")", "return", "group", ";", "else", "return", "[", "group", "]", ";", "}", ")", ";", "// Create buttons groups", "_", ".", "each", "(", "groups", ",", "function", "(", "group", ")", "{", "var", "$group", "=", "$", "(", "'<div>'", ",", "{", "'class'", ":", "'buttons'", "}", ")", ";", "var", "sizeClass", "=", "'size-'", "+", "group", ".", "length", ";", "// Append buttons", "_", ".", "each", "(", "group", ",", "function", "(", "btn", ")", "{", "btn", "=", "_", ".", "defaults", "(", "btn", "||", "{", "}", ",", "{", "text", ":", "''", ",", "className", ":", "''", ",", "onClick", ":", "defaultOnClick", "}", ")", ";", "var", "$btn", "=", "$", "(", "'<button>'", ",", "{", "'class'", ":", "'button '", "+", "sizeClass", "+", "' '", "+", "btn", ".", "className", ",", "'text'", ":", "btn", ".", "text", "}", ")", ";", "$btn", ".", "click", "(", "btn", ".", "onClick", ")", ";", "$group", ".", "append", "(", "$btn", ")", ";", "}", ")", ";", "$menu", ".", "append", "(", "$group", ")", ";", "}", ")", ";", "}", "return", "$menu", ";", "}" ]
Create a dropdown menu
[ "Create", "a", "dropdown", "menu" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/theme/javascript/toolbar.js#L28-L74
43,734
simonguo/hbook
theme/javascript/toolbar.js
createButton
function createButton(opts) { opts = _.defaults(opts || {}, { // Aria label for the button label: '', // Icon to show icon: '', // Inner text text: '', // Right or left position position: 'left', // Other class name to add to the button className: '', // Triggered when user click on the button onClick: defaultOnClick, // Button is a dropdown dropdown: null, // Position in the toolbar index: null }); buttons.push(opts); updateButton(opts); }
javascript
function createButton(opts) { opts = _.defaults(opts || {}, { // Aria label for the button label: '', // Icon to show icon: '', // Inner text text: '', // Right or left position position: 'left', // Other class name to add to the button className: '', // Triggered when user click on the button onClick: defaultOnClick, // Button is a dropdown dropdown: null, // Position in the toolbar index: null }); buttons.push(opts); updateButton(opts); }
[ "function", "createButton", "(", "opts", ")", "{", "opts", "=", "_", ".", "defaults", "(", "opts", "||", "{", "}", ",", "{", "// Aria label for the button", "label", ":", "''", ",", "// Icon to show", "icon", ":", "''", ",", "// Inner text", "text", ":", "''", ",", "// Right or left position", "position", ":", "'left'", ",", "// Other class name to add to the button", "className", ":", "''", ",", "// Triggered when user click on the button", "onClick", ":", "defaultOnClick", ",", "// Button is a dropdown", "dropdown", ":", "null", ",", "// Position in the toolbar", "index", ":", "null", "}", ")", ";", "buttons", ".", "push", "(", "opts", ")", ";", "updateButton", "(", "opts", ")", ";", "}" ]
Create a new button in the toolbar
[ "Create", "a", "new", "button", "in", "the", "toolbar" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/theme/javascript/toolbar.js#L77-L106
43,735
simonguo/hbook
theme/javascript/toolbar.js
updateButton
function updateButton(opts) { var $result; var $toolbar = $('.book-header'); var $title = $toolbar.find('h1'); // Build class name var positionClass = 'pull-'+opts.position; // Create button var $btn = $('<a>', { 'class': 'btn', 'text': opts.text? ' ' + opts.text : '', 'aria-label': opts.label, 'href': '#' }); // Bind click $btn.click(opts.onClick); // Prepend icon if (opts.icon) { $('<i>', { 'class': opts.icon }).prependTo($btn); } // Prepare dropdown if (opts.dropdown) { var $container = $('<div>', { 'class': 'dropdown '+positionClass+' '+opts.className }); // Add button to container $btn.addClass('toggle-dropdown'); $container.append($btn); // Create inner menu var $menu = createDropdownMenu(opts.dropdown); // Menu position $menu.addClass('dropdown-'+(opts.position == 'right'? 'left' : 'right')); $container.append($menu); $result = $container; } else { $btn.addClass(positionClass); $btn.addClass(opts.className); $result = $btn; } $result.addClass('js-toolbar-action'); if (_.isNumber(opts.index) && opts.index >= 0) { insertAt($toolbar, '.btn, .dropdown, h1', opts.index, $result); } else { $result.insertBefore($title); } }
javascript
function updateButton(opts) { var $result; var $toolbar = $('.book-header'); var $title = $toolbar.find('h1'); // Build class name var positionClass = 'pull-'+opts.position; // Create button var $btn = $('<a>', { 'class': 'btn', 'text': opts.text? ' ' + opts.text : '', 'aria-label': opts.label, 'href': '#' }); // Bind click $btn.click(opts.onClick); // Prepend icon if (opts.icon) { $('<i>', { 'class': opts.icon }).prependTo($btn); } // Prepare dropdown if (opts.dropdown) { var $container = $('<div>', { 'class': 'dropdown '+positionClass+' '+opts.className }); // Add button to container $btn.addClass('toggle-dropdown'); $container.append($btn); // Create inner menu var $menu = createDropdownMenu(opts.dropdown); // Menu position $menu.addClass('dropdown-'+(opts.position == 'right'? 'left' : 'right')); $container.append($menu); $result = $container; } else { $btn.addClass(positionClass); $btn.addClass(opts.className); $result = $btn; } $result.addClass('js-toolbar-action'); if (_.isNumber(opts.index) && opts.index >= 0) { insertAt($toolbar, '.btn, .dropdown, h1', opts.index, $result); } else { $result.insertBefore($title); } }
[ "function", "updateButton", "(", "opts", ")", "{", "var", "$result", ";", "var", "$toolbar", "=", "$", "(", "'.book-header'", ")", ";", "var", "$title", "=", "$toolbar", ".", "find", "(", "'h1'", ")", ";", "// Build class name", "var", "positionClass", "=", "'pull-'", "+", "opts", ".", "position", ";", "// Create button", "var", "$btn", "=", "$", "(", "'<a>'", ",", "{", "'class'", ":", "'btn'", ",", "'text'", ":", "opts", ".", "text", "?", "' '", "+", "opts", ".", "text", ":", "''", ",", "'aria-label'", ":", "opts", ".", "label", ",", "'href'", ":", "'#'", "}", ")", ";", "// Bind click", "$btn", ".", "click", "(", "opts", ".", "onClick", ")", ";", "// Prepend icon", "if", "(", "opts", ".", "icon", ")", "{", "$", "(", "'<i>'", ",", "{", "'class'", ":", "opts", ".", "icon", "}", ")", ".", "prependTo", "(", "$btn", ")", ";", "}", "// Prepare dropdown", "if", "(", "opts", ".", "dropdown", ")", "{", "var", "$container", "=", "$", "(", "'<div>'", ",", "{", "'class'", ":", "'dropdown '", "+", "positionClass", "+", "' '", "+", "opts", ".", "className", "}", ")", ";", "// Add button to container", "$btn", ".", "addClass", "(", "'toggle-dropdown'", ")", ";", "$container", ".", "append", "(", "$btn", ")", ";", "// Create inner menu", "var", "$menu", "=", "createDropdownMenu", "(", "opts", ".", "dropdown", ")", ";", "// Menu position", "$menu", ".", "addClass", "(", "'dropdown-'", "+", "(", "opts", ".", "position", "==", "'right'", "?", "'left'", ":", "'right'", ")", ")", ";", "$container", ".", "append", "(", "$menu", ")", ";", "$result", "=", "$container", ";", "}", "else", "{", "$btn", ".", "addClass", "(", "positionClass", ")", ";", "$btn", ".", "addClass", "(", "opts", ".", "className", ")", ";", "$result", "=", "$btn", ";", "}", "$result", ".", "addClass", "(", "'js-toolbar-action'", ")", ";", "if", "(", "_", ".", "isNumber", "(", "opts", ".", "index", ")", "&&", "opts", ".", "index", ">=", "0", ")", "{", "insertAt", "(", "$toolbar", ",", "'.btn, .dropdown, h1'", ",", "opts", ".", "index", ",", "$result", ")", ";", "}", "else", "{", "$result", ".", "insertBefore", "(", "$title", ")", ";", "}", "}" ]
Update a button
[ "Update", "a", "button" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/theme/javascript/toolbar.js#L109-L166
43,736
mmoulton/capture
phantomjs/capture.js
argsToObject
function argsToObject(args) { var options = {}; options.address = args.shift(); options.output = args.shift(); // Pair two arguments, while transforming the key to camelCase for (i = 0; i < args.length; i = i + 2) { options[toCamelCase(args[i].substr(2))] = args[i + 1]; } return options; }
javascript
function argsToObject(args) { var options = {}; options.address = args.shift(); options.output = args.shift(); // Pair two arguments, while transforming the key to camelCase for (i = 0; i < args.length; i = i + 2) { options[toCamelCase(args[i].substr(2))] = args[i + 1]; } return options; }
[ "function", "argsToObject", "(", "args", ")", "{", "var", "options", "=", "{", "}", ";", "options", ".", "address", "=", "args", ".", "shift", "(", ")", ";", "options", ".", "output", "=", "args", ".", "shift", "(", ")", ";", "// Pair two arguments, while transforming the key to camelCase", "for", "(", "i", "=", "0", ";", "i", "<", "args", ".", "length", ";", "i", "=", "i", "+", "2", ")", "{", "options", "[", "toCamelCase", "(", "args", "[", "i", "]", ".", "substr", "(", "2", ")", ")", "]", "=", "args", "[", "i", "+", "1", "]", ";", "}", "return", "options", ";", "}" ]
Transform an array to an object literal @param {Array} args Array with seperate arguments @return {Object}
[ "Transform", "an", "array", "to", "an", "object", "literal" ]
794a0542603c4ff1f908d5d00c1bd3cda5c490ec
https://github.com/mmoulton/capture/blob/794a0542603c4ff1f908d5d00c1bd3cda5c490ec/phantomjs/capture.js#L116-L127
43,737
bhoriuchi/vsphere-connect
archive/v1/client/findParentType.js
getParent
function getParent(type, id, parentType, root) { return _client.retrieve({ type: type, id: id, properties: ['parent'] }) .then(function(obj) { if (obj.length > 0) { obj = _.first(obj); type = _.get(obj, 'parent.type'); id = _.get(obj, 'parent.id'); // if there is no parent type or id, the parent could not be found, throw an error if (!type || !id) { throw { errorCode: 404, message: 'could not find parent type' }; } // if the parent is a match if (type === parentType) { // if a root search, keep looking for parent objects of the same type if (root === true) { return _client.retrieve({ type: type, id: id, properties: ['parent'] }) .then(function(parent) { if (_.get(parent, 'parent.type') === parentType) { return getParent(type, id, parentType, root); } return { id: id, type: parentType }; }); } return { id: id, type: parentType }; } return getParent(type, id, parentType, root); } throw { errorCode: 404, message: 'Object not found' }; }); }
javascript
function getParent(type, id, parentType, root) { return _client.retrieve({ type: type, id: id, properties: ['parent'] }) .then(function(obj) { if (obj.length > 0) { obj = _.first(obj); type = _.get(obj, 'parent.type'); id = _.get(obj, 'parent.id'); // if there is no parent type or id, the parent could not be found, throw an error if (!type || !id) { throw { errorCode: 404, message: 'could not find parent type' }; } // if the parent is a match if (type === parentType) { // if a root search, keep looking for parent objects of the same type if (root === true) { return _client.retrieve({ type: type, id: id, properties: ['parent'] }) .then(function(parent) { if (_.get(parent, 'parent.type') === parentType) { return getParent(type, id, parentType, root); } return { id: id, type: parentType }; }); } return { id: id, type: parentType }; } return getParent(type, id, parentType, root); } throw { errorCode: 404, message: 'Object not found' }; }); }
[ "function", "getParent", "(", "type", ",", "id", ",", "parentType", ",", "root", ")", "{", "return", "_client", ".", "retrieve", "(", "{", "type", ":", "type", ",", "id", ":", "id", ",", "properties", ":", "[", "'parent'", "]", "}", ")", ".", "then", "(", "function", "(", "obj", ")", "{", "if", "(", "obj", ".", "length", ">", "0", ")", "{", "obj", "=", "_", ".", "first", "(", "obj", ")", ";", "type", "=", "_", ".", "get", "(", "obj", ",", "'parent.type'", ")", ";", "id", "=", "_", ".", "get", "(", "obj", ",", "'parent.id'", ")", ";", "// if there is no parent type or id, the parent could not be found, throw an error", "if", "(", "!", "type", "||", "!", "id", ")", "{", "throw", "{", "errorCode", ":", "404", ",", "message", ":", "'could not find parent type'", "}", ";", "}", "// if the parent is a match", "if", "(", "type", "===", "parentType", ")", "{", "// if a root search, keep looking for parent objects of the same type", "if", "(", "root", "===", "true", ")", "{", "return", "_client", ".", "retrieve", "(", "{", "type", ":", "type", ",", "id", ":", "id", ",", "properties", ":", "[", "'parent'", "]", "}", ")", ".", "then", "(", "function", "(", "parent", ")", "{", "if", "(", "_", ".", "get", "(", "parent", ",", "'parent.type'", ")", "===", "parentType", ")", "{", "return", "getParent", "(", "type", ",", "id", ",", "parentType", ",", "root", ")", ";", "}", "return", "{", "id", ":", "id", ",", "type", ":", "parentType", "}", ";", "}", ")", ";", "}", "return", "{", "id", ":", "id", ",", "type", ":", "parentType", "}", ";", "}", "return", "getParent", "(", "type", ",", "id", ",", "parentType", ",", "root", ")", ";", "}", "throw", "{", "errorCode", ":", "404", ",", "message", ":", "'Object not found'", "}", ";", "}", ")", ";", "}" ]
recursively looks for a parent type
[ "recursively", "looks", "for", "a", "parent", "type" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/client/findParentType.js#L20-L76
43,738
simonguo/hbook
lib/configuration.js
isDefaultPlugin
function isDefaultPlugin(name, version) { if (!_.contains(DEFAULT_PLUGINS, name)) return false; try { var pluginPkg = require('gitbook-plugin-'+name+'/package.json'); return semver.satisfies(pluginPkg.version, version || '*'); } catch(e) { return false; } }
javascript
function isDefaultPlugin(name, version) { if (!_.contains(DEFAULT_PLUGINS, name)) return false; try { var pluginPkg = require('gitbook-plugin-'+name+'/package.json'); return semver.satisfies(pluginPkg.version, version || '*'); } catch(e) { return false; } }
[ "function", "isDefaultPlugin", "(", "name", ",", "version", ")", "{", "if", "(", "!", "_", ".", "contains", "(", "DEFAULT_PLUGINS", ",", "name", ")", ")", "return", "false", ";", "try", "{", "var", "pluginPkg", "=", "require", "(", "'gitbook-plugin-'", "+", "name", "+", "'/package.json'", ")", ";", "return", "semver", ".", "satisfies", "(", "pluginPkg", ".", "version", ",", "version", "||", "'*'", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}" ]
Check if a plugin is a default plugin Plugin should be in the list And version from book.json specified for this plugin should be satisfied
[ "Check", "if", "a", "plugin", "is", "a", "default", "plugin", "Plugin", "should", "be", "in", "the", "list", "And", "version", "from", "book", ".", "json", "specified", "for", "this", "plugin", "should", "be", "satisfied" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/configuration.js#L18-L27
43,739
simonguo/hbook
lib/configuration.js
normalizePluginsList
function normalizePluginsList(plugins, addDefaults) { // Normalize list to an array plugins = _.isString(plugins) ? plugins.split(',') : (plugins || []); // Remove empty parts plugins = _.compact(plugins); // Divide as {name, version} to handle format like '[email protected]' plugins = _.map(plugins, function(plugin) { if (plugin.name) return plugin; var parts = plugin.split('@'); var name = parts[0]; var version = parts[1]; return { 'name': name, 'version': version, // optional 'isDefault': isDefaultPlugin(name, version) }; }); // List plugins to remove var toremove = _.chain(plugins) .filter(function(plugin) { return plugin.name.length > 0 && plugin.name[0] == '-'; }) .map(function(plugin) { return plugin.name.slice(1); }) .value(); // Merge with defaults if (addDefaults !== false) { _.each(DEFAULT_PLUGINS, function(plugin) { if (_.find(plugins, { name: plugin })) { return; } plugins.push({ 'name': plugin, 'isDefault': true }); }); } // Remove plugin that start with '-' plugins = _.filter(plugins, function(plugin) { return !_.contains(toremove, plugin.name) && !(plugin.name.length > 0 && plugin.name[0] == '-'); }); // Remove duplicates plugins = _.uniq(plugins, 'name'); return plugins; }
javascript
function normalizePluginsList(plugins, addDefaults) { // Normalize list to an array plugins = _.isString(plugins) ? plugins.split(',') : (plugins || []); // Remove empty parts plugins = _.compact(plugins); // Divide as {name, version} to handle format like '[email protected]' plugins = _.map(plugins, function(plugin) { if (plugin.name) return plugin; var parts = plugin.split('@'); var name = parts[0]; var version = parts[1]; return { 'name': name, 'version': version, // optional 'isDefault': isDefaultPlugin(name, version) }; }); // List plugins to remove var toremove = _.chain(plugins) .filter(function(plugin) { return plugin.name.length > 0 && plugin.name[0] == '-'; }) .map(function(plugin) { return plugin.name.slice(1); }) .value(); // Merge with defaults if (addDefaults !== false) { _.each(DEFAULT_PLUGINS, function(plugin) { if (_.find(plugins, { name: plugin })) { return; } plugins.push({ 'name': plugin, 'isDefault': true }); }); } // Remove plugin that start with '-' plugins = _.filter(plugins, function(plugin) { return !_.contains(toremove, plugin.name) && !(plugin.name.length > 0 && plugin.name[0] == '-'); }); // Remove duplicates plugins = _.uniq(plugins, 'name'); return plugins; }
[ "function", "normalizePluginsList", "(", "plugins", ",", "addDefaults", ")", "{", "// Normalize list to an array", "plugins", "=", "_", ".", "isString", "(", "plugins", ")", "?", "plugins", ".", "split", "(", "','", ")", ":", "(", "plugins", "||", "[", "]", ")", ";", "// Remove empty parts", "plugins", "=", "_", ".", "compact", "(", "plugins", ")", ";", "// Divide as {name, version} to handle format like '[email protected]'", "plugins", "=", "_", ".", "map", "(", "plugins", ",", "function", "(", "plugin", ")", "{", "if", "(", "plugin", ".", "name", ")", "return", "plugin", ";", "var", "parts", "=", "plugin", ".", "split", "(", "'@'", ")", ";", "var", "name", "=", "parts", "[", "0", "]", ";", "var", "version", "=", "parts", "[", "1", "]", ";", "return", "{", "'name'", ":", "name", ",", "'version'", ":", "version", ",", "// optional", "'isDefault'", ":", "isDefaultPlugin", "(", "name", ",", "version", ")", "}", ";", "}", ")", ";", "// List plugins to remove", "var", "toremove", "=", "_", ".", "chain", "(", "plugins", ")", ".", "filter", "(", "function", "(", "plugin", ")", "{", "return", "plugin", ".", "name", ".", "length", ">", "0", "&&", "plugin", ".", "name", "[", "0", "]", "==", "'-'", ";", "}", ")", ".", "map", "(", "function", "(", "plugin", ")", "{", "return", "plugin", ".", "name", ".", "slice", "(", "1", ")", ";", "}", ")", ".", "value", "(", ")", ";", "// Merge with defaults", "if", "(", "addDefaults", "!==", "false", ")", "{", "_", ".", "each", "(", "DEFAULT_PLUGINS", ",", "function", "(", "plugin", ")", "{", "if", "(", "_", ".", "find", "(", "plugins", ",", "{", "name", ":", "plugin", "}", ")", ")", "{", "return", ";", "}", "plugins", ".", "push", "(", "{", "'name'", ":", "plugin", ",", "'isDefault'", ":", "true", "}", ")", ";", "}", ")", ";", "}", "// Remove plugin that start with '-'", "plugins", "=", "_", ".", "filter", "(", "plugins", ",", "function", "(", "plugin", ")", "{", "return", "!", "_", ".", "contains", "(", "toremove", ",", "plugin", ".", "name", ")", "&&", "!", "(", "plugin", ".", "name", ".", "length", ">", "0", "&&", "plugin", ".", "name", "[", "0", "]", "==", "'-'", ")", ";", "}", ")", ";", "// Remove duplicates", "plugins", "=", "_", ".", "uniq", "(", "plugins", ",", "'name'", ")", ";", "return", "plugins", ";", "}" ]
Normalize a list of plugins to use
[ "Normalize", "a", "list", "of", "plugins", "to", "use" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/configuration.js#L30-L84
43,740
cnlon/fuck-env
utils.js
getFiles
function getFiles () { const FUCK_ENV = process.env.FUCK_ENV || process.env.npm_package_config_FUCK_ENV || FUCK_ENV_DEFAULT return FUCK_ENV.split(',').map(file => path.resolve(root, file)) }
javascript
function getFiles () { const FUCK_ENV = process.env.FUCK_ENV || process.env.npm_package_config_FUCK_ENV || FUCK_ENV_DEFAULT return FUCK_ENV.split(',').map(file => path.resolve(root, file)) }
[ "function", "getFiles", "(", ")", "{", "const", "FUCK_ENV", "=", "process", ".", "env", ".", "FUCK_ENV", "||", "process", ".", "env", ".", "npm_package_config_FUCK_ENV", "||", "FUCK_ENV_DEFAULT", "return", "FUCK_ENV", ".", "split", "(", "','", ")", ".", "map", "(", "file", "=>", "path", ".", "resolve", "(", "root", ",", "file", ")", ")", "}" ]
Get files from environment variables
[ "Get", "files", "from", "environment", "variables" ]
ddbd6d9ff34a35adf26e807e7fd4db99c52acafd
https://github.com/cnlon/fuck-env/blob/ddbd6d9ff34a35adf26e807e7fd4db99c52acafd/utils.js#L18-L23
43,741
bhoriuchi/vsphere-connect
archive/v1/format.js
formatValue
function formatValue(value) { var out; var type = util.sType(value); // if there is a type, check all sub items for types if (_.has(value, 'attributes.type') && _.has(value, '$value') && _.keys(value).length === 2) { out = util.moRef(value); } else if (type) { if (util.isArray(value)) { out = []; var subtype = type; if (subtype.match(/^ArrayOf/)) { subtype = subtype.replace(/^ArrayOf/, ''); if (!Array.isArray(_.get(value, subtype)) && value[subtype]) { value[subtype] = [value[subtype]]; } } _.forEach(value[_.keys(value)[1]], function(obj) { out.push(formatValue(obj)); }); } else if (util.isBoolean(value)) { // check for valid true values, otherwise false if (_.includes(['1', 'true'], _.lowerCase(value.$value))) { out = true; } else { out = false; } } else if (util.isInt(value)) { out = Number(value.$value); } else if (_.has(value, '$value')) { out = value.$value; } else { out = formatValue(_.omit(value, 'attributes')); } } else if (Array.isArray(value)) { out = []; _.forEach(value, function(val) { if (util.sType(val) || util.isArray(val) || util.hasKeys(val)) { out.push(formatValue(val)); } else { out.push(cast(val)); } }); } else if (util.hasKeys(value)) { out = {}; _.forEach(value, function(val, key) { if (util.sType(val) || util.isArray(val) || util.hasKeys(val)) { out[key] = formatValue(val); } else { out[key] = cast(val); } }); } else { out = cast(value); } return out; }
javascript
function formatValue(value) { var out; var type = util.sType(value); // if there is a type, check all sub items for types if (_.has(value, 'attributes.type') && _.has(value, '$value') && _.keys(value).length === 2) { out = util.moRef(value); } else if (type) { if (util.isArray(value)) { out = []; var subtype = type; if (subtype.match(/^ArrayOf/)) { subtype = subtype.replace(/^ArrayOf/, ''); if (!Array.isArray(_.get(value, subtype)) && value[subtype]) { value[subtype] = [value[subtype]]; } } _.forEach(value[_.keys(value)[1]], function(obj) { out.push(formatValue(obj)); }); } else if (util.isBoolean(value)) { // check for valid true values, otherwise false if (_.includes(['1', 'true'], _.lowerCase(value.$value))) { out = true; } else { out = false; } } else if (util.isInt(value)) { out = Number(value.$value); } else if (_.has(value, '$value')) { out = value.$value; } else { out = formatValue(_.omit(value, 'attributes')); } } else if (Array.isArray(value)) { out = []; _.forEach(value, function(val) { if (util.sType(val) || util.isArray(val) || util.hasKeys(val)) { out.push(formatValue(val)); } else { out.push(cast(val)); } }); } else if (util.hasKeys(value)) { out = {}; _.forEach(value, function(val, key) { if (util.sType(val) || util.isArray(val) || util.hasKeys(val)) { out[key] = formatValue(val); } else { out[key] = cast(val); } }); } else { out = cast(value); } return out; }
[ "function", "formatValue", "(", "value", ")", "{", "var", "out", ";", "var", "type", "=", "util", ".", "sType", "(", "value", ")", ";", "// if there is a type, check all sub items for types", "if", "(", "_", ".", "has", "(", "value", ",", "'attributes.type'", ")", "&&", "_", ".", "has", "(", "value", ",", "'$value'", ")", "&&", "_", ".", "keys", "(", "value", ")", ".", "length", "===", "2", ")", "{", "out", "=", "util", ".", "moRef", "(", "value", ")", ";", "}", "else", "if", "(", "type", ")", "{", "if", "(", "util", ".", "isArray", "(", "value", ")", ")", "{", "out", "=", "[", "]", ";", "var", "subtype", "=", "type", ";", "if", "(", "subtype", ".", "match", "(", "/", "^ArrayOf", "/", ")", ")", "{", "subtype", "=", "subtype", ".", "replace", "(", "/", "^ArrayOf", "/", ",", "''", ")", ";", "if", "(", "!", "Array", ".", "isArray", "(", "_", ".", "get", "(", "value", ",", "subtype", ")", ")", "&&", "value", "[", "subtype", "]", ")", "{", "value", "[", "subtype", "]", "=", "[", "value", "[", "subtype", "]", "]", ";", "}", "}", "_", ".", "forEach", "(", "value", "[", "_", ".", "keys", "(", "value", ")", "[", "1", "]", "]", ",", "function", "(", "obj", ")", "{", "out", ".", "push", "(", "formatValue", "(", "obj", ")", ")", ";", "}", ")", ";", "}", "else", "if", "(", "util", ".", "isBoolean", "(", "value", ")", ")", "{", "// check for valid true values, otherwise false", "if", "(", "_", ".", "includes", "(", "[", "'1'", ",", "'true'", "]", ",", "_", ".", "lowerCase", "(", "value", ".", "$value", ")", ")", ")", "{", "out", "=", "true", ";", "}", "else", "{", "out", "=", "false", ";", "}", "}", "else", "if", "(", "util", ".", "isInt", "(", "value", ")", ")", "{", "out", "=", "Number", "(", "value", ".", "$value", ")", ";", "}", "else", "if", "(", "_", ".", "has", "(", "value", ",", "'$value'", ")", ")", "{", "out", "=", "value", ".", "$value", ";", "}", "else", "{", "out", "=", "formatValue", "(", "_", ".", "omit", "(", "value", ",", "'attributes'", ")", ")", ";", "}", "}", "else", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "out", "=", "[", "]", ";", "_", ".", "forEach", "(", "value", ",", "function", "(", "val", ")", "{", "if", "(", "util", ".", "sType", "(", "val", ")", "||", "util", ".", "isArray", "(", "val", ")", "||", "util", ".", "hasKeys", "(", "val", ")", ")", "{", "out", ".", "push", "(", "formatValue", "(", "val", ")", ")", ";", "}", "else", "{", "out", ".", "push", "(", "cast", "(", "val", ")", ")", ";", "}", "}", ")", ";", "}", "else", "if", "(", "util", ".", "hasKeys", "(", "value", ")", ")", "{", "out", "=", "{", "}", ";", "_", ".", "forEach", "(", "value", ",", "function", "(", "val", ",", "key", ")", "{", "if", "(", "util", ".", "sType", "(", "val", ")", "||", "util", ".", "isArray", "(", "val", ")", "||", "util", ".", "hasKeys", "(", "val", ")", ")", "{", "out", "[", "key", "]", "=", "formatValue", "(", "val", ")", ";", "}", "else", "{", "out", "[", "key", "]", "=", "cast", "(", "val", ")", ";", "}", "}", ")", ";", "}", "else", "{", "out", "=", "cast", "(", "value", ")", ";", "}", "return", "out", ";", "}" ]
recursive formatting function
[ "recursive", "formatting", "function" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/format.js#L45-L119
43,742
bhoriuchi/vsphere-connect
archive/v1/format.js
formatProp
function formatProp(obj) { var out = {}; var props = _.get(obj, 'propSet'); var moRef = _.has(obj, 'obj') ? util.moRef(obj.obj) : util.moRef(obj); out.id = moRef.id; out.type = moRef.type; // loop through the propSet if (Array.isArray(props)) { _.forEach(props, function(prop) { out[prop.name] = formatValue(prop.val); }); } else if (_.has(props, 'name')) { out[props.name] = formatValue(props.val); } return out; }
javascript
function formatProp(obj) { var out = {}; var props = _.get(obj, 'propSet'); var moRef = _.has(obj, 'obj') ? util.moRef(obj.obj) : util.moRef(obj); out.id = moRef.id; out.type = moRef.type; // loop through the propSet if (Array.isArray(props)) { _.forEach(props, function(prop) { out[prop.name] = formatValue(prop.val); }); } else if (_.has(props, 'name')) { out[props.name] = formatValue(props.val); } return out; }
[ "function", "formatProp", "(", "obj", ")", "{", "var", "out", "=", "{", "}", ";", "var", "props", "=", "_", ".", "get", "(", "obj", ",", "'propSet'", ")", ";", "var", "moRef", "=", "_", ".", "has", "(", "obj", ",", "'obj'", ")", "?", "util", ".", "moRef", "(", "obj", ".", "obj", ")", ":", "util", ".", "moRef", "(", "obj", ")", ";", "out", ".", "id", "=", "moRef", ".", "id", ";", "out", ".", "type", "=", "moRef", ".", "type", ";", "// loop through the propSet", "if", "(", "Array", ".", "isArray", "(", "props", ")", ")", "{", "_", ".", "forEach", "(", "props", ",", "function", "(", "prop", ")", "{", "out", "[", "prop", ".", "name", "]", "=", "formatValue", "(", "prop", ".", "val", ")", ";", "}", ")", ";", "}", "else", "if", "(", "_", ".", "has", "(", "props", ",", "'name'", ")", ")", "{", "out", "[", "props", ".", "name", "]", "=", "formatValue", "(", "props", ".", "val", ")", ";", "}", "return", "out", ";", "}" ]
format each object
[ "format", "each", "object" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/format.js#L123-L142
43,743
bhoriuchi/vsphere-connect
archive/v1/format.js
expandFields
function expandFields(obj) { var out = {}; _.forEach(obj, function(val, key) { if (_.includes(key, '.')) { _.set(out, key, val); } else { out[key] = val; } }); return out; }
javascript
function expandFields(obj) { var out = {}; _.forEach(obj, function(val, key) { if (_.includes(key, '.')) { _.set(out, key, val); } else { out[key] = val; } }); return out; }
[ "function", "expandFields", "(", "obj", ")", "{", "var", "out", "=", "{", "}", ";", "_", ".", "forEach", "(", "obj", ",", "function", "(", "val", ",", "key", ")", "{", "if", "(", "_", ".", "includes", "(", "key", ",", "'.'", ")", ")", "{", "_", ".", "set", "(", "out", ",", "key", ",", "val", ")", ";", "}", "else", "{", "out", "[", "key", "]", "=", "val", ";", "}", "}", ")", ";", "return", "out", ";", "}" ]
since filters with dot notation return field names with dots, expand those fields and remove the dot named field
[ "since", "filters", "with", "dot", "notation", "return", "field", "names", "with", "dots", "expand", "those", "fields", "and", "remove", "the", "dot", "named", "field" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/format.js#L146-L159
43,744
bhoriuchi/vsphere-connect
archive/v1/format.js
format
function format(response) { var newObj = []; var objects = _.get(response, 'objects') || response; if (objects) { // check if objects is an array if (Array.isArray(objects)) { _.forEach(objects, function(obj) { newObj.push(expandFields(formatProp(obj))); }); } else { newObj = expandFields(formatProp(objects)); } return newObj; } // if no objects return the raw response return response; }
javascript
function format(response) { var newObj = []; var objects = _.get(response, 'objects') || response; if (objects) { // check if objects is an array if (Array.isArray(objects)) { _.forEach(objects, function(obj) { newObj.push(expandFields(formatProp(obj))); }); } else { newObj = expandFields(formatProp(objects)); } return newObj; } // if no objects return the raw response return response; }
[ "function", "format", "(", "response", ")", "{", "var", "newObj", "=", "[", "]", ";", "var", "objects", "=", "_", ".", "get", "(", "response", ",", "'objects'", ")", "||", "response", ";", "if", "(", "objects", ")", "{", "// check if objects is an array", "if", "(", "Array", ".", "isArray", "(", "objects", ")", ")", "{", "_", ".", "forEach", "(", "objects", ",", "function", "(", "obj", ")", "{", "newObj", ".", "push", "(", "expandFields", "(", "formatProp", "(", "obj", ")", ")", ")", ";", "}", ")", ";", "}", "else", "{", "newObj", "=", "expandFields", "(", "formatProp", "(", "objects", ")", ")", ";", "}", "return", "newObj", ";", "}", "// if no objects return the raw response", "return", "response", ";", "}" ]
main formatting function
[ "main", "formatting", "function" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/format.js#L163-L184
43,745
simonguo/hbook
theme/javascript/sidebar.js
filterSummary
function filterSummary(paths) { var $summary = $('.book-summary'); $summary.find('li').each(function() { var path = $(this).data('path'); var st = paths == null || _.contains(paths, path); $(this).toggle(st); if (st) $(this).parents('li').show(); }); }
javascript
function filterSummary(paths) { var $summary = $('.book-summary'); $summary.find('li').each(function() { var path = $(this).data('path'); var st = paths == null || _.contains(paths, path); $(this).toggle(st); if (st) $(this).parents('li').show(); }); }
[ "function", "filterSummary", "(", "paths", ")", "{", "var", "$summary", "=", "$", "(", "'.book-summary'", ")", ";", "$summary", ".", "find", "(", "'li'", ")", ".", "each", "(", "function", "(", ")", "{", "var", "path", "=", "$", "(", "this", ")", ".", "data", "(", "'path'", ")", ";", "var", "st", "=", "paths", "==", "null", "||", "_", ".", "contains", "(", "paths", ",", "path", ")", ";", "$", "(", "this", ")", ".", "toggle", "(", "st", ")", ";", "if", "(", "st", ")", "$", "(", "this", ")", ".", "parents", "(", "'li'", ")", ".", "show", "(", ")", ";", "}", ")", ";", "}" ]
Filter summary with a list of path
[ "Filter", "summary", "with", "a", "list", "of", "path" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/theme/javascript/sidebar.js#L39-L49
43,746
bhoriuchi/vsphere-connect
src/soap/client/wsdl/methods/process-docs.js
setOperations
function setOperations(operations, portType) { _.forEach(portType.childNodes, node => { if (node.localName === 'operation') { operations[node.getAttribute('name')] = node; } }); }
javascript
function setOperations(operations, portType) { _.forEach(portType.childNodes, node => { if (node.localName === 'operation') { operations[node.getAttribute('name')] = node; } }); }
[ "function", "setOperations", "(", "operations", ",", "portType", ")", "{", "_", ".", "forEach", "(", "portType", ".", "childNodes", ",", "node", "=>", "{", "if", "(", "node", ".", "localName", "===", "'operation'", ")", "{", "operations", "[", "node", ".", "getAttribute", "(", "'name'", ")", "]", "=", "node", ";", "}", "}", ")", ";", "}" ]
set operations via interface or portType
[ "set", "operations", "via", "interface", "or", "portType" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/src/soap/client/wsdl/methods/process-docs.js#L6-L12
43,747
simonguo/hbook
lib/utils/fs.js
getUniqueFilename
function getUniqueFilename(base, filename) { if (!filename) { filename = base; base = '/'; } filename = path.resolve(base, filename); var ext = path.extname(filename); filename = path.join(path.dirname(filename), path.basename(filename, ext)); var _filename = filename+ext; var i = 0; while (fs.existsSync(filename)) { _filename = filename+'_'+i+ext; i = i + 1; } return path.relative(base, _filename); }
javascript
function getUniqueFilename(base, filename) { if (!filename) { filename = base; base = '/'; } filename = path.resolve(base, filename); var ext = path.extname(filename); filename = path.join(path.dirname(filename), path.basename(filename, ext)); var _filename = filename+ext; var i = 0; while (fs.existsSync(filename)) { _filename = filename+'_'+i+ext; i = i + 1; } return path.relative(base, _filename); }
[ "function", "getUniqueFilename", "(", "base", ",", "filename", ")", "{", "if", "(", "!", "filename", ")", "{", "filename", "=", "base", ";", "base", "=", "'/'", ";", "}", "filename", "=", "path", ".", "resolve", "(", "base", ",", "filename", ")", ";", "var", "ext", "=", "path", ".", "extname", "(", "filename", ")", ";", "filename", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "filename", ")", ",", "path", ".", "basename", "(", "filename", ",", "ext", ")", ")", ";", "var", "_filename", "=", "filename", "+", "ext", ";", "var", "i", "=", "0", ";", "while", "(", "fs", ".", "existsSync", "(", "filename", ")", ")", "{", "_filename", "=", "filename", "+", "'_'", "+", "i", "+", "ext", ";", "i", "=", "i", "+", "1", ";", "}", "return", "path", ".", "relative", "(", "base", ",", "_filename", ")", ";", "}" ]
Find a filename available
[ "Find", "a", "filename", "available" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/utils/fs.js#L78-L97
43,748
simonguo/hbook
lib/utils/fs.js
listFiles
function listFiles(root, options) { options = _.defaults(options || {}, { ignoreFiles: [], ignoreRules: [] }); var d = Q.defer(); // Our list of files var files = []; var ig = Ignore({ path: root, ignoreFiles: options.ignoreFiles }); // Add extra rules to ignore common folders ig.addIgnoreRules(options.ignoreRules, '__custom_stuff'); // Push each file to our list ig.on('child', function (c) { files.push( c.path.substr(c.root.path.length + 1) + (c.props.Directory === true ? '/' : '') ); }); ig.on('end', function() { // Normalize paths on Windows if(process.platform === 'win32') { return d.resolve(files.map(function(file) { return file.replace(/\\/g, '/'); })); } // Simply return paths otherwise return d.resolve(files); }); ig.on('error', d.reject); return d.promise; }
javascript
function listFiles(root, options) { options = _.defaults(options || {}, { ignoreFiles: [], ignoreRules: [] }); var d = Q.defer(); // Our list of files var files = []; var ig = Ignore({ path: root, ignoreFiles: options.ignoreFiles }); // Add extra rules to ignore common folders ig.addIgnoreRules(options.ignoreRules, '__custom_stuff'); // Push each file to our list ig.on('child', function (c) { files.push( c.path.substr(c.root.path.length + 1) + (c.props.Directory === true ? '/' : '') ); }); ig.on('end', function() { // Normalize paths on Windows if(process.platform === 'win32') { return d.resolve(files.map(function(file) { return file.replace(/\\/g, '/'); })); } // Simply return paths otherwise return d.resolve(files); }); ig.on('error', d.reject); return d.promise; }
[ "function", "listFiles", "(", "root", ",", "options", ")", "{", "options", "=", "_", ".", "defaults", "(", "options", "||", "{", "}", ",", "{", "ignoreFiles", ":", "[", "]", ",", "ignoreRules", ":", "[", "]", "}", ")", ";", "var", "d", "=", "Q", ".", "defer", "(", ")", ";", "// Our list of files", "var", "files", "=", "[", "]", ";", "var", "ig", "=", "Ignore", "(", "{", "path", ":", "root", ",", "ignoreFiles", ":", "options", ".", "ignoreFiles", "}", ")", ";", "// Add extra rules to ignore common folders", "ig", ".", "addIgnoreRules", "(", "options", ".", "ignoreRules", ",", "'__custom_stuff'", ")", ";", "// Push each file to our list", "ig", ".", "on", "(", "'child'", ",", "function", "(", "c", ")", "{", "files", ".", "push", "(", "c", ".", "path", ".", "substr", "(", "c", ".", "root", ".", "path", ".", "length", "+", "1", ")", "+", "(", "c", ".", "props", ".", "Directory", "===", "true", "?", "'/'", ":", "''", ")", ")", ";", "}", ")", ";", "ig", ".", "on", "(", "'end'", ",", "function", "(", ")", "{", "// Normalize paths on Windows", "if", "(", "process", ".", "platform", "===", "'win32'", ")", "{", "return", "d", ".", "resolve", "(", "files", ".", "map", "(", "function", "(", "file", ")", "{", "return", "file", ".", "replace", "(", "/", "\\\\", "/", "g", ",", "'/'", ")", ";", "}", ")", ")", ";", "}", "// Simply return paths otherwise", "return", "d", ".", "resolve", "(", "files", ")", ";", "}", ")", ";", "ig", ".", "on", "(", "'error'", ",", "d", ".", "reject", ")", ";", "return", "d", ".", "promise", ";", "}" ]
List files in a directory
[ "List", "files", "in", "a", "directory" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/utils/fs.js#L101-L142
43,749
simonguo/hbook
lib/utils/fs.js
cleanFolder
function cleanFolder(root) { if (!fs.existsSync(root)) return fsUtils.mkdirp(root); return listFiles(root, { ignoreFiles: [], ignoreRules: [ // Skip Git and SVN stuff '.git/', '.svn/' ] }) .then(function(files) { var d = Q.defer(); _.reduce(files, function(prev, file, i) { return prev.then(function() { var _file = path.join(root, file); d.notify({ i: i+1, count: files.length, file: _file }); return fsUtils.remove(_file); }); }, Q()) .then(function() { d.resolve(); }, function(err) { d.reject(err); }); return d.promise; }); }
javascript
function cleanFolder(root) { if (!fs.existsSync(root)) return fsUtils.mkdirp(root); return listFiles(root, { ignoreFiles: [], ignoreRules: [ // Skip Git and SVN stuff '.git/', '.svn/' ] }) .then(function(files) { var d = Q.defer(); _.reduce(files, function(prev, file, i) { return prev.then(function() { var _file = path.join(root, file); d.notify({ i: i+1, count: files.length, file: _file }); return fsUtils.remove(_file); }); }, Q()) .then(function() { d.resolve(); }, function(err) { d.reject(err); }); return d.promise; }); }
[ "function", "cleanFolder", "(", "root", ")", "{", "if", "(", "!", "fs", ".", "existsSync", "(", "root", ")", ")", "return", "fsUtils", ".", "mkdirp", "(", "root", ")", ";", "return", "listFiles", "(", "root", ",", "{", "ignoreFiles", ":", "[", "]", ",", "ignoreRules", ":", "[", "// Skip Git and SVN stuff", "'.git/'", ",", "'.svn/'", "]", "}", ")", ".", "then", "(", "function", "(", "files", ")", "{", "var", "d", "=", "Q", ".", "defer", "(", ")", ";", "_", ".", "reduce", "(", "files", ",", "function", "(", "prev", ",", "file", ",", "i", ")", "{", "return", "prev", ".", "then", "(", "function", "(", ")", "{", "var", "_file", "=", "path", ".", "join", "(", "root", ",", "file", ")", ";", "d", ".", "notify", "(", "{", "i", ":", "i", "+", "1", ",", "count", ":", "files", ".", "length", ",", "file", ":", "_file", "}", ")", ";", "return", "fsUtils", ".", "remove", "(", "_file", ")", ";", "}", ")", ";", "}", ",", "Q", "(", ")", ")", ".", "then", "(", "function", "(", ")", "{", "d", ".", "resolve", "(", ")", ";", "}", ",", "function", "(", "err", ")", "{", "d", ".", "reject", "(", "err", ")", ";", "}", ")", ";", "return", "d", ".", "promise", ";", "}", ")", ";", "}" ]
Clean a folder without removing .git and .svn Creates it if non existant
[ "Clean", "a", "folder", "without", "removing", ".", "git", "and", ".", "svn", "Creates", "it", "if", "non", "existant" ]
5ea071130cc418fccd97a3e7e9a285c1d756b80b
https://github.com/simonguo/hbook/blob/5ea071130cc418fccd97a3e7e9a285c1d756b80b/lib/utils/fs.js#L146-L180
43,750
stremlenye/immutable-http
src/validate.js
validateMethod
function validateMethod (method) { if (!method) { return option.some('HTTP method is not specified') } if (typeof method !== 'string') { return option.some('HTTP method should be type of string') } if (supportedMethods.indexOf(method.toUpperCase()) < 0) { return option.some(`Http method ${method} is not supported`) } return option.none }
javascript
function validateMethod (method) { if (!method) { return option.some('HTTP method is not specified') } if (typeof method !== 'string') { return option.some('HTTP method should be type of string') } if (supportedMethods.indexOf(method.toUpperCase()) < 0) { return option.some(`Http method ${method} is not supported`) } return option.none }
[ "function", "validateMethod", "(", "method", ")", "{", "if", "(", "!", "method", ")", "{", "return", "option", ".", "some", "(", "'HTTP method is not specified'", ")", "}", "if", "(", "typeof", "method", "!==", "'string'", ")", "{", "return", "option", ".", "some", "(", "'HTTP method should be type of string'", ")", "}", "if", "(", "supportedMethods", ".", "indexOf", "(", "method", ".", "toUpperCase", "(", ")", ")", "<", "0", ")", "{", "return", "option", ".", "some", "(", "`", "${", "method", "}", "`", ")", "}", "return", "option", ".", "none", "}" ]
Validate HTTP method @param {String} method – HTTP method @return {String} error
[ "Validate", "HTTP", "method" ]
4d46a66cc11cd02d96be63a3283bbfe7df1272c3
https://github.com/stremlenye/immutable-http/blob/4d46a66cc11cd02d96be63a3283bbfe7df1272c3/src/validate.js#L11-L22
43,751
stremlenye/immutable-http
src/validate.js
validateUrl
function validateUrl (url) { if (!url) { return option.some('Url is not specified') } if (typeof url !== 'string') { return option.some('Url should be type of string') } return option.none }
javascript
function validateUrl (url) { if (!url) { return option.some('Url is not specified') } if (typeof url !== 'string') { return option.some('Url should be type of string') } return option.none }
[ "function", "validateUrl", "(", "url", ")", "{", "if", "(", "!", "url", ")", "{", "return", "option", ".", "some", "(", "'Url is not specified'", ")", "}", "if", "(", "typeof", "url", "!==", "'string'", ")", "{", "return", "option", ".", "some", "(", "'Url should be type of string'", ")", "}", "return", "option", ".", "none", "}" ]
Basicly validate url @param {String} url – URL @return {String} error
[ "Basicly", "validate", "url" ]
4d46a66cc11cd02d96be63a3283bbfe7df1272c3
https://github.com/stremlenye/immutable-http/blob/4d46a66cc11cd02d96be63a3283bbfe7df1272c3/src/validate.js#L29-L37
43,752
stremlenye/immutable-http
src/validate.js
validateHeader
function validateHeader (key, value) { if (typeof key !== 'string' || typeof value !== 'string') return option.some(`Parts of header ${key}:${value} must be strings`) return option.none }
javascript
function validateHeader (key, value) { if (typeof key !== 'string' || typeof value !== 'string') return option.some(`Parts of header ${key}:${value} must be strings`) return option.none }
[ "function", "validateHeader", "(", "key", ",", "value", ")", "{", "if", "(", "typeof", "key", "!==", "'string'", "||", "typeof", "value", "!==", "'string'", ")", "return", "option", ".", "some", "(", "`", "${", "key", "}", "${", "value", "}", "`", ")", "return", "option", ".", "none", "}" ]
Validate header to all parts be strings @param {String} key – Header key @param {String} value – Header value @return {String} error
[ "Validate", "header", "to", "all", "parts", "be", "strings" ]
4d46a66cc11cd02d96be63a3283bbfe7df1272c3
https://github.com/stremlenye/immutable-http/blob/4d46a66cc11cd02d96be63a3283bbfe7df1272c3/src/validate.js#L45-L49
43,753
stremlenye/immutable-http
src/validate.js
validateResponseType
function validateResponseType (type) { if (validTypes.indexOf(type) < 0) return option.some(`Response content type ${type} is not supported`) return option.none }
javascript
function validateResponseType (type) { if (validTypes.indexOf(type) < 0) return option.some(`Response content type ${type} is not supported`) return option.none }
[ "function", "validateResponseType", "(", "type", ")", "{", "if", "(", "validTypes", ".", "indexOf", "(", "type", ")", "<", "0", ")", "return", "option", ".", "some", "(", "`", "${", "type", "}", "`", ")", "return", "option", ".", "none", "}" ]
Validates response type @param {string} type - response type @return {String} error
[ "Validates", "response", "type" ]
4d46a66cc11cd02d96be63a3283bbfe7df1272c3
https://github.com/stremlenye/immutable-http/blob/4d46a66cc11cd02d96be63a3283bbfe7df1272c3/src/validate.js#L68-L72
43,754
bhoriuchi/vsphere-connect
archive/v1/client/retrieve.js
getResults
function getResults(result, objects) { // if there are no results, resolve an empty array if (!result) { return new Promise(function(resolve, reject) { resolve([]); }); } // if the result object is undefined or not an array, make it one result.objects = result.objects || []; result.objects = Array.isArray(result.objects) ? result.objects : [result.objects]; objects = _.union(objects, result.objects); // if the result has a token, there are more results, continue to get them if (result.token) { return _client.method('ContinueRetrievePropertiesEx', { _this: _client._sc.propertyCollector, token: result.token }) .then(function(results) { return getResults(results, objects); }); } // if there are no more results, return the formatted results else { return new Promise(function(resolve, reject) { resolve(env.format(objects)); }); } }
javascript
function getResults(result, objects) { // if there are no results, resolve an empty array if (!result) { return new Promise(function(resolve, reject) { resolve([]); }); } // if the result object is undefined or not an array, make it one result.objects = result.objects || []; result.objects = Array.isArray(result.objects) ? result.objects : [result.objects]; objects = _.union(objects, result.objects); // if the result has a token, there are more results, continue to get them if (result.token) { return _client.method('ContinueRetrievePropertiesEx', { _this: _client._sc.propertyCollector, token: result.token }) .then(function(results) { return getResults(results, objects); }); } // if there are no more results, return the formatted results else { return new Promise(function(resolve, reject) { resolve(env.format(objects)); }); } }
[ "function", "getResults", "(", "result", ",", "objects", ")", "{", "// if there are no results, resolve an empty array", "if", "(", "!", "result", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "resolve", "(", "[", "]", ")", ";", "}", ")", ";", "}", "// if the result object is undefined or not an array, make it one", "result", ".", "objects", "=", "result", ".", "objects", "||", "[", "]", ";", "result", ".", "objects", "=", "Array", ".", "isArray", "(", "result", ".", "objects", ")", "?", "result", ".", "objects", ":", "[", "result", ".", "objects", "]", ";", "objects", "=", "_", ".", "union", "(", "objects", ",", "result", ".", "objects", ")", ";", "// if the result has a token, there are more results, continue to get them", "if", "(", "result", ".", "token", ")", "{", "return", "_client", ".", "method", "(", "'ContinueRetrievePropertiesEx'", ",", "{", "_this", ":", "_client", ".", "_sc", ".", "propertyCollector", ",", "token", ":", "result", ".", "token", "}", ")", ".", "then", "(", "function", "(", "results", ")", "{", "return", "getResults", "(", "results", ",", "objects", ")", ";", "}", ")", ";", "}", "// if there are no more results, return the formatted results", "else", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "resolve", "(", "env", ".", "format", "(", "objects", ")", ")", ";", "}", ")", ";", "}", "}" ]
continues to get all properties until finished
[ "continues", "to", "get", "all", "properties", "until", "finished" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/client/retrieve.js#L25-L56
43,755
steamerjs/steamer-react-component
src/spin.js
ins
function ins(parent /* child1, child2, ... */) { for (let i = 1, n = arguments.length; i < n; i++) { parent.appendChild(arguments[i]); } return parent; }
javascript
function ins(parent /* child1, child2, ... */) { for (let i = 1, n = arguments.length; i < n; i++) { parent.appendChild(arguments[i]); } return parent; }
[ "function", "ins", "(", "parent", "/* child1, child2, ... */", ")", "{", "for", "(", "let", "i", "=", "1", ",", "n", "=", "arguments", ".", "length", ";", "i", "<", "n", ";", "i", "++", ")", "{", "parent", ".", "appendChild", "(", "arguments", "[", "i", "]", ")", ";", "}", "return", "parent", ";", "}" ]
Appends children and returns the parent.
[ "Appends", "children", "and", "returns", "the", "parent", "." ]
84cbf6a125d8d5693f037f8544c79e2b1c2bdca6
https://github.com/steamerjs/steamer-react-component/blob/84cbf6a125d8d5693f037f8544c79e2b1c2bdca6/src/spin.js#L54-L60
43,756
steamerjs/steamer-react-component
src/spin.js
function() { let el = this.el; if (el) { clearTimeout(this.timeout); if (el.parentNode) el.parentNode.removeChild(el); this.el = null; } return this; }
javascript
function() { let el = this.el; if (el) { clearTimeout(this.timeout); if (el.parentNode) el.parentNode.removeChild(el); this.el = null; } return this; }
[ "function", "(", ")", "{", "let", "el", "=", "this", ".", "el", ";", "if", "(", "el", ")", "{", "clearTimeout", "(", "this", ".", "timeout", ")", ";", "if", "(", "el", ".", "parentNode", ")", "el", ".", "parentNode", ".", "removeChild", "(", "el", ")", ";", "this", ".", "el", "=", "null", ";", "}", "return", "this", ";", "}" ]
Stops and removes the Spinner.
[ "Stops", "and", "removes", "the", "Spinner", "." ]
84cbf6a125d8d5693f037f8544c79e2b1c2bdca6
https://github.com/steamerjs/steamer-react-component/blob/84cbf6a125d8d5693f037f8544c79e2b1c2bdca6/src/spin.js#L226-L235
43,757
bhoriuchi/vsphere-connect
archive/v1/util.js
moRef
function moRef(type, id) { if (type && id) { return { attributes: { type: type }, "$value": id }; } else if (typeof(type) === 'object') { return { id: _.get(type, '$value'), type: _.get(type, 'attributes.type') || _.get(type, 'attributes.xsi:type') }; } return null; }
javascript
function moRef(type, id) { if (type && id) { return { attributes: { type: type }, "$value": id }; } else if (typeof(type) === 'object') { return { id: _.get(type, '$value'), type: _.get(type, 'attributes.type') || _.get(type, 'attributes.xsi:type') }; } return null; }
[ "function", "moRef", "(", "type", ",", "id", ")", "{", "if", "(", "type", "&&", "id", ")", "{", "return", "{", "attributes", ":", "{", "type", ":", "type", "}", ",", "\"$value\"", ":", "id", "}", ";", "}", "else", "if", "(", "typeof", "(", "type", ")", "===", "'object'", ")", "{", "return", "{", "id", ":", "_", ".", "get", "(", "type", ",", "'$value'", ")", ",", "type", ":", "_", ".", "get", "(", "type", ",", "'attributes.type'", ")", "||", "_", ".", "get", "(", "type", ",", "'attributes.xsi:type'", ")", "}", ";", "}", "return", "null", ";", "}" ]
compose or decompose a moRef
[ "compose", "or", "decompose", "a", "moRef" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/util.js#L14-L31
43,758
bhoriuchi/vsphere-connect
archive/v1/util.js
isArray
function isArray(obj) { var type = sType(obj); return (Array.isArray(obj) || (typeof(type) === 'string' && type.substring(0, 5) === 'Array')); }
javascript
function isArray(obj) { var type = sType(obj); return (Array.isArray(obj) || (typeof(type) === 'string' && type.substring(0, 5) === 'Array')); }
[ "function", "isArray", "(", "obj", ")", "{", "var", "type", "=", "sType", "(", "obj", ")", ";", "return", "(", "Array", ".", "isArray", "(", "obj", ")", "||", "(", "typeof", "(", "type", ")", "===", "'string'", "&&", "type", ".", "substring", "(", "0", ",", "5", ")", "===", "'Array'", ")", ")", ";", "}" ]
determine if type is an array
[ "determine", "if", "type", "is", "an", "array" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/util.js#L39-L42
43,759
bhoriuchi/vsphere-connect
archive/v1/util.js
isBoolean
function isBoolean(obj) { var type = sType(obj); return (_.has(obj, '$value') && (type === 'xsd:boolean' || type === 'boolean')); }
javascript
function isBoolean(obj) { var type = sType(obj); return (_.has(obj, '$value') && (type === 'xsd:boolean' || type === 'boolean')); }
[ "function", "isBoolean", "(", "obj", ")", "{", "var", "type", "=", "sType", "(", "obj", ")", ";", "return", "(", "_", ".", "has", "(", "obj", ",", "'$value'", ")", "&&", "(", "type", "===", "'xsd:boolean'", "||", "type", "===", "'boolean'", ")", ")", ";", "}" ]
check for boolean
[ "check", "for", "boolean" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/util.js#L45-L48
43,760
bhoriuchi/vsphere-connect
archive/v1/util.js
isInt
function isInt(obj) { var type = sType(obj); return (_.has(obj, '$value') && (type === 'xsd:int' || type === 'int')); }
javascript
function isInt(obj) { var type = sType(obj); return (_.has(obj, '$value') && (type === 'xsd:int' || type === 'int')); }
[ "function", "isInt", "(", "obj", ")", "{", "var", "type", "=", "sType", "(", "obj", ")", ";", "return", "(", "_", ".", "has", "(", "obj", ",", "'$value'", ")", "&&", "(", "type", "===", "'xsd:int'", "||", "type", "===", "'int'", ")", ")", ";", "}" ]
check for number
[ "check", "for", "number" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/util.js#L51-L54
43,761
bhoriuchi/vsphere-connect
archive/v1/util.js
hasKeys
function hasKeys(obj) { return (!Array.isArray(obj) && _.isObject(obj) && _.keys(obj).length > 0); }
javascript
function hasKeys(obj) { return (!Array.isArray(obj) && _.isObject(obj) && _.keys(obj).length > 0); }
[ "function", "hasKeys", "(", "obj", ")", "{", "return", "(", "!", "Array", ".", "isArray", "(", "obj", ")", "&&", "_", ".", "isObject", "(", "obj", ")", "&&", "_", ".", "keys", "(", "obj", ")", ".", "length", ">", "0", ")", ";", "}" ]
function to check for object with keys
[ "function", "to", "check", "for", "object", "with", "keys" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/util.js#L57-L59
43,762
bhoriuchi/vsphere-connect
archive/v1/util.js
filterValidPaths
function filterValidPaths(type, paths, version) { var valid = []; version = env.schema[version] || env.schema['5.1']; _.forEach(paths, function(p) { if (env.schema.hasProperty(version, type, p)) { valid.push(p); } }); return valid; }
javascript
function filterValidPaths(type, paths, version) { var valid = []; version = env.schema[version] || env.schema['5.1']; _.forEach(paths, function(p) { if (env.schema.hasProperty(version, type, p)) { valid.push(p); } }); return valid; }
[ "function", "filterValidPaths", "(", "type", ",", "paths", ",", "version", ")", "{", "var", "valid", "=", "[", "]", ";", "version", "=", "env", ".", "schema", "[", "version", "]", "||", "env", ".", "schema", "[", "'5.1'", "]", ";", "_", ".", "forEach", "(", "paths", ",", "function", "(", "p", ")", "{", "if", "(", "env", ".", "schema", ".", "hasProperty", "(", "version", ",", "type", ",", "p", ")", ")", "{", "valid", ".", "push", "(", "p", ")", ";", "}", "}", ")", ";", "return", "valid", ";", "}" ]
function to get valid paths
[ "function", "to", "get", "valid", "paths" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/util.js#L62-L74
43,763
bhoriuchi/vsphere-connect
archive/v1/util.js
newError
function newError(errorCode, errorMessage) { var errObj; if (_.isObject(errorCode)) { errObj = errorCode; } else if (typeof(errorCode) === 'number') { errObj = { errorCode: errorCode, }; if (errorMessage) { errObj.message = errorMessage; } } else { errObj = {errorCode: 500}; } return new Promise(function(resolve, reject) { reject(errObj); }); }
javascript
function newError(errorCode, errorMessage) { var errObj; if (_.isObject(errorCode)) { errObj = errorCode; } else if (typeof(errorCode) === 'number') { errObj = { errorCode: errorCode, }; if (errorMessage) { errObj.message = errorMessage; } } else { errObj = {errorCode: 500}; } return new Promise(function(resolve, reject) { reject(errObj); }); }
[ "function", "newError", "(", "errorCode", ",", "errorMessage", ")", "{", "var", "errObj", ";", "if", "(", "_", ".", "isObject", "(", "errorCode", ")", ")", "{", "errObj", "=", "errorCode", ";", "}", "else", "if", "(", "typeof", "(", "errorCode", ")", "===", "'number'", ")", "{", "errObj", "=", "{", "errorCode", ":", "errorCode", ",", "}", ";", "if", "(", "errorMessage", ")", "{", "errObj", ".", "message", "=", "errorMessage", ";", "}", "}", "else", "{", "errObj", "=", "{", "errorCode", ":", "500", "}", ";", "}", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "reject", "(", "errObj", ")", ";", "}", ")", ";", "}" ]
returns a promise that resolves to an error
[ "returns", "a", "promise", "that", "resolves", "to", "an", "error" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/util.js#L77-L100
43,764
bhoriuchi/vsphere-connect
archive/v1/util.js
getSessionId
function getSessionId(cookie) { if (typeof(cookie.cookies) === 'string') { var idx = cookie.cookies.indexOf('='); if (idx !== -1) { return _.trim(cookie.cookies.substring(idx + 1), '"') || null; } } return null; }
javascript
function getSessionId(cookie) { if (typeof(cookie.cookies) === 'string') { var idx = cookie.cookies.indexOf('='); if (idx !== -1) { return _.trim(cookie.cookies.substring(idx + 1), '"') || null; } } return null; }
[ "function", "getSessionId", "(", "cookie", ")", "{", "if", "(", "typeof", "(", "cookie", ".", "cookies", ")", "===", "'string'", ")", "{", "var", "idx", "=", "cookie", ".", "cookies", ".", "indexOf", "(", "'='", ")", ";", "if", "(", "idx", "!==", "-", "1", ")", "{", "return", "_", ".", "trim", "(", "cookie", ".", "cookies", ".", "substring", "(", "idx", "+", "1", ")", ",", "'\"'", ")", "||", "null", ";", "}", "}", "return", "null", ";", "}" ]
parse the cookie for a session id
[ "parse", "the", "cookie", "for", "a", "session", "id" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/util.js#L103-L111
43,765
bhoriuchi/vsphere-connect
archive/v1/util.js
log
function log(obj, message) { obj = obj || []; obj.push({ time: new Date(), log: message }); return obj; }
javascript
function log(obj, message) { obj = obj || []; obj.push({ time: new Date(), log: message }); return obj; }
[ "function", "log", "(", "obj", ",", "message", ")", "{", "obj", "=", "obj", "||", "[", "]", ";", "obj", ".", "push", "(", "{", "time", ":", "new", "Date", "(", ")", ",", "log", ":", "message", "}", ")", ";", "return", "obj", ";", "}" ]
keep a log of something
[ "keep", "a", "log", "of", "something" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/util.js#L121-L129
43,766
KirinJS/Kirin
javascript/lib/extensions/Facebook-android.js
function() { if(savedMessageFromLastFail) { // Last time we tried to publish there was a failure preventing it from ending up on the wall. // In such a case, we want to pre-populate the user's message with the same message from last time. // See 20552: ('Write Something..' text is lost on network error when attempting to share) wallPostObj.message = savedMessageFromLastFail; savedMessageFromLastFail = ""; } // The backend passes in the following: // wallPostObj: Contains the copy for the wall post // withThesePermissions: permissions needed to post on the wall // accessToken: the facebook token needed to set up the session // tokenExpiry: the date the facebook token expires // onSuccessCBToken: Callback method on success // onCancelledCBToken: When the user cancels post backend.handlePostRequest_({ facebookKeyValues: wallPostObj, accessToken: settings.get("facebook.access_token"), tokenExpire: settings.get("facebook.expires_at"), onSuccessCBToken: kirin.wrapCallback(function() { console.log("Publish successful"); successCallback(); }, "Facebook.", "publish."), onCancelledCBToken: kirin.wrapCallback(function() { console.log("Publish was cancelled"); if(_.isFunction(cancelCallback)) { cancelCallback(); } }, "Facebook.", "cancelled."), onFailureCBToken: kirin.wrapCallback(function(devErrMsg) { console.log("Publish failed"); showFacebookFailMsg(); failureCallback(devErrMsg); }, "Facebook.", "failure.") }); }
javascript
function() { if(savedMessageFromLastFail) { // Last time we tried to publish there was a failure preventing it from ending up on the wall. // In such a case, we want to pre-populate the user's message with the same message from last time. // See 20552: ('Write Something..' text is lost on network error when attempting to share) wallPostObj.message = savedMessageFromLastFail; savedMessageFromLastFail = ""; } // The backend passes in the following: // wallPostObj: Contains the copy for the wall post // withThesePermissions: permissions needed to post on the wall // accessToken: the facebook token needed to set up the session // tokenExpiry: the date the facebook token expires // onSuccessCBToken: Callback method on success // onCancelledCBToken: When the user cancels post backend.handlePostRequest_({ facebookKeyValues: wallPostObj, accessToken: settings.get("facebook.access_token"), tokenExpire: settings.get("facebook.expires_at"), onSuccessCBToken: kirin.wrapCallback(function() { console.log("Publish successful"); successCallback(); }, "Facebook.", "publish."), onCancelledCBToken: kirin.wrapCallback(function() { console.log("Publish was cancelled"); if(_.isFunction(cancelCallback)) { cancelCallback(); } }, "Facebook.", "cancelled."), onFailureCBToken: kirin.wrapCallback(function(devErrMsg) { console.log("Publish failed"); showFacebookFailMsg(); failureCallback(devErrMsg); }, "Facebook.", "failure.") }); }
[ "function", "(", ")", "{", "if", "(", "savedMessageFromLastFail", ")", "{", "// Last time we tried to publish there was a failure preventing it from ending up on the wall.", "// In such a case, we want to pre-populate the user's message with the same message from last time.", "// See 20552: ('Write Something..' text is lost on network error when attempting to share)", "wallPostObj", ".", "message", "=", "savedMessageFromLastFail", ";", "savedMessageFromLastFail", "=", "\"\"", ";", "}", "// The backend passes in the following:", "// wallPostObj: Contains the copy for the wall post", "// withThesePermissions: permissions needed to post on the wall", "// accessToken: the facebook token needed to set up the session", "// tokenExpiry: the date the facebook token expires", "// onSuccessCBToken: Callback method on success", "// onCancelledCBToken: When the user cancels post", "backend", ".", "handlePostRequest_", "(", "{", "facebookKeyValues", ":", "wallPostObj", ",", "accessToken", ":", "settings", ".", "get", "(", "\"facebook.access_token\"", ")", ",", "tokenExpire", ":", "settings", ".", "get", "(", "\"facebook.expires_at\"", ")", ",", "onSuccessCBToken", ":", "kirin", ".", "wrapCallback", "(", "function", "(", ")", "{", "console", ".", "log", "(", "\"Publish successful\"", ")", ";", "successCallback", "(", ")", ";", "}", ",", "\"Facebook.\"", ",", "\"publish.\"", ")", ",", "onCancelledCBToken", ":", "kirin", ".", "wrapCallback", "(", "function", "(", ")", "{", "console", ".", "log", "(", "\"Publish was cancelled\"", ")", ";", "if", "(", "_", ".", "isFunction", "(", "cancelCallback", ")", ")", "{", "cancelCallback", "(", ")", ";", "}", "}", ",", "\"Facebook.\"", ",", "\"cancelled.\"", ")", ",", "onFailureCBToken", ":", "kirin", ".", "wrapCallback", "(", "function", "(", "devErrMsg", ")", "{", "console", ".", "log", "(", "\"Publish failed\"", ")", ";", "showFacebookFailMsg", "(", ")", ";", "failureCallback", "(", "devErrMsg", ")", ";", "}", ",", "\"Facebook.\"", ",", "\"failure.\"", ")", "}", ")", ";", "}" ]
Function that deals with showing the preview popup and asking the user for their comment and confirmation for publishing. It will then post it with the mesasge once it gets user confirmation.
[ "Function", "that", "deals", "with", "showing", "the", "preview", "popup", "and", "asking", "the", "user", "for", "their", "comment", "and", "confirmation", "for", "publishing", ".", "It", "will", "then", "post", "it", "with", "the", "mesasge", "once", "it", "gets", "user", "confirmation", "." ]
d40e86ca89c40b5d3e0c129c24ff3b77ed3d28e1
https://github.com/KirinJS/Kirin/blob/d40e86ca89c40b5d3e0c129c24ff3b77ed3d28e1/javascript/lib/extensions/Facebook-android.js#L94-L130
43,767
messyfresh/hirez.js
src/sessions/sessionAPI.js
genSession
function genSession (baseUrl, devId, authHash, platform) { let url = baseUrl + 'createsessionjson/' + devId + '/' + authHash + '/' + util.getUtcTime() return new Promise((resolve, reject) => { request(url, (error, response, body) => { if (!error && response.statusCode === 200) { let sessionID = JSON.parse(body) switch (platform) { case 'smitePC': process.env.SMITE_PC_SESSION = sessionID.session_id resolve(sessionID) break case 'smiteXBOX': process.env.SMITE_XBOX_SESSION = sessionID.session_id resolve(sessionID) break case 'smitePS4': process.env.SMITE_PS4_SESSION = sessionID.session_id resolve(sessionID) break case 'paladinsPC': process.env.PALADINS_PC_SESSION = sessionID.session_id resolve(sessionID) break case 'paladinsXBOX': process.env.PALADINS_XBOX_SESSION = sessionID.session_id resolve(sessionID) break case 'paladinsPS4': process.env.PALADINS_PS4_SESSION = sessionID.session_id resolve(sessionID) } } else { reject(error) } }) }) }
javascript
function genSession (baseUrl, devId, authHash, platform) { let url = baseUrl + 'createsessionjson/' + devId + '/' + authHash + '/' + util.getUtcTime() return new Promise((resolve, reject) => { request(url, (error, response, body) => { if (!error && response.statusCode === 200) { let sessionID = JSON.parse(body) switch (platform) { case 'smitePC': process.env.SMITE_PC_SESSION = sessionID.session_id resolve(sessionID) break case 'smiteXBOX': process.env.SMITE_XBOX_SESSION = sessionID.session_id resolve(sessionID) break case 'smitePS4': process.env.SMITE_PS4_SESSION = sessionID.session_id resolve(sessionID) break case 'paladinsPC': process.env.PALADINS_PC_SESSION = sessionID.session_id resolve(sessionID) break case 'paladinsXBOX': process.env.PALADINS_XBOX_SESSION = sessionID.session_id resolve(sessionID) break case 'paladinsPS4': process.env.PALADINS_PS4_SESSION = sessionID.session_id resolve(sessionID) } } else { reject(error) } }) }) }
[ "function", "genSession", "(", "baseUrl", ",", "devId", ",", "authHash", ",", "platform", ")", "{", "let", "url", "=", "baseUrl", "+", "'createsessionjson/'", "+", "devId", "+", "'/'", "+", "authHash", "+", "'/'", "+", "util", ".", "getUtcTime", "(", ")", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "request", "(", "url", ",", "(", "error", ",", "response", ",", "body", ")", "=>", "{", "if", "(", "!", "error", "&&", "response", ".", "statusCode", "===", "200", ")", "{", "let", "sessionID", "=", "JSON", ".", "parse", "(", "body", ")", "switch", "(", "platform", ")", "{", "case", "'smitePC'", ":", "process", ".", "env", ".", "SMITE_PC_SESSION", "=", "sessionID", ".", "session_id", "resolve", "(", "sessionID", ")", "break", "case", "'smiteXBOX'", ":", "process", ".", "env", ".", "SMITE_XBOX_SESSION", "=", "sessionID", ".", "session_id", "resolve", "(", "sessionID", ")", "break", "case", "'smitePS4'", ":", "process", ".", "env", ".", "SMITE_PS4_SESSION", "=", "sessionID", ".", "session_id", "resolve", "(", "sessionID", ")", "break", "case", "'paladinsPC'", ":", "process", ".", "env", ".", "PALADINS_PC_SESSION", "=", "sessionID", ".", "session_id", "resolve", "(", "sessionID", ")", "break", "case", "'paladinsXBOX'", ":", "process", ".", "env", ".", "PALADINS_XBOX_SESSION", "=", "sessionID", ".", "session_id", "resolve", "(", "sessionID", ")", "break", "case", "'paladinsPS4'", ":", "process", ".", "env", ".", "PALADINS_PS4_SESSION", "=", "sessionID", ".", "session_id", "resolve", "(", "sessionID", ")", "}", "}", "else", "{", "reject", "(", "error", ")", "}", "}", ")", "}", ")", "}" ]
Generate a new Session
[ "Generate", "a", "new", "Session" ]
c849a887cf6141639896d4f0ee9e49145a12d6e2
https://github.com/messyfresh/hirez.js/blob/c849a887cf6141639896d4f0ee9e49145a12d6e2/src/sessions/sessionAPI.js#L63-L100
43,768
bhoriuchi/vsphere-connect
archive/v1/client/monitor.js
taskAsync
function taskAsync(args, result) { // format the result result = env.format(result); // if the delete should not be asyncronous and the task should be monitored if (args.async === false) { // set the polling period and timeout defaults args.delay = !isNaN(args.delay) ? args.delay : 1000; args.timeout = (!isNaN(args.timeout) && args.timeout >= 0) ? args.timeout : 0; // start the monitor return task(result.id, args.delay, args.timeout, (new Date()).valueOf()); } // return the result return result; }
javascript
function taskAsync(args, result) { // format the result result = env.format(result); // if the delete should not be asyncronous and the task should be monitored if (args.async === false) { // set the polling period and timeout defaults args.delay = !isNaN(args.delay) ? args.delay : 1000; args.timeout = (!isNaN(args.timeout) && args.timeout >= 0) ? args.timeout : 0; // start the monitor return task(result.id, args.delay, args.timeout, (new Date()).valueOf()); } // return the result return result; }
[ "function", "taskAsync", "(", "args", ",", "result", ")", "{", "// format the result", "result", "=", "env", ".", "format", "(", "result", ")", ";", "// if the delete should not be asyncronous and the task should be monitored", "if", "(", "args", ".", "async", "===", "false", ")", "{", "// set the polling period and timeout defaults", "args", ".", "delay", "=", "!", "isNaN", "(", "args", ".", "delay", ")", "?", "args", ".", "delay", ":", "1000", ";", "args", ".", "timeout", "=", "(", "!", "isNaN", "(", "args", ".", "timeout", ")", "&&", "args", ".", "timeout", ">=", "0", ")", "?", "args", ".", "timeout", ":", "0", ";", "// start the monitor", "return", "task", "(", "result", ".", "id", ",", "args", ".", "delay", ",", "args", ".", "timeout", ",", "(", "new", "Date", "(", ")", ")", ".", "valueOf", "(", ")", ")", ";", "}", "// return the result", "return", "result", ";", "}" ]
determine if the task should be monitored or to simply return the task id
[ "determine", "if", "the", "task", "should", "be", "monitored", "or", "to", "simply", "return", "the", "task", "id" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/client/monitor.js#L115-L133
43,769
bhoriuchi/vsphere-connect
archive/v.js
assignRequest
function assignRequest (target, source, obj = {}, term) { _.merge(target, _.omit(source, ['term']), obj) if (term == true) target.term = source.term }
javascript
function assignRequest (target, source, obj = {}, term) { _.merge(target, _.omit(source, ['term']), obj) if (term == true) target.term = source.term }
[ "function", "assignRequest", "(", "target", ",", "source", ",", "obj", "=", "{", "}", ",", "term", ")", "{", "_", ".", "merge", "(", "target", ",", "_", ".", "omit", "(", "source", ",", "[", "'term'", "]", ")", ",", "obj", ")", "if", "(", "term", "==", "true", ")", "target", ".", "term", "=", "source", ".", "term", "}" ]
returns a new request context built from the existing @param target @param source @param obj @param term
[ "returns", "a", "new", "request", "context", "built", "from", "the", "existing" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v.js#L16-L19
43,770
bhoriuchi/vsphere-connect
archive/v.js
processTerm
function processTerm (handler, obj = {}, isDefault) { let req = { term: this._request.term.then(value => { assignRequest(req, this._request, obj) if (this._request.error && !isDefault) return null if (isDefault) req.error = null return handler(value, req) }) } return new v(this._client, req) }
javascript
function processTerm (handler, obj = {}, isDefault) { let req = { term: this._request.term.then(value => { assignRequest(req, this._request, obj) if (this._request.error && !isDefault) return null if (isDefault) req.error = null return handler(value, req) }) } return new v(this._client, req) }
[ "function", "processTerm", "(", "handler", ",", "obj", "=", "{", "}", ",", "isDefault", ")", "{", "let", "req", "=", "{", "term", ":", "this", ".", "_request", ".", "term", ".", "then", "(", "value", "=>", "{", "assignRequest", "(", "req", ",", "this", ".", "_request", ",", "obj", ")", "if", "(", "this", ".", "_request", ".", "error", "&&", "!", "isDefault", ")", "return", "null", "if", "(", "isDefault", ")", "req", ".", "error", "=", "null", "return", "handler", "(", "value", ",", "req", ")", "}", ")", "}", "return", "new", "v", "(", "this", ".", "_client", ",", "req", ")", "}" ]
processes the current term promise and updates the context @param handler @param obj @return {v}
[ "processes", "the", "current", "term", "promise", "and", "updates", "the", "context" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v.js#L27-L37
43,771
bhoriuchi/vsphere-connect
archive/v.js
processBranch
function processBranch (args, resolve, reject) { let condition = args.shift() let val = args.shift() let las = _.last(args) return Promise.resolve(condition) .then(c => { if (c === true) { return Promise.resolve(_.isFunction(val) ? val() : val) .then(resolve, reject) } else if (args.length === 1) { return Promise.resolve(_.isFunction(las) ? las() : las) .then(resolve, reject) } else { return processBranch(args, resolve, reject) } }, reject) }
javascript
function processBranch (args, resolve, reject) { let condition = args.shift() let val = args.shift() let las = _.last(args) return Promise.resolve(condition) .then(c => { if (c === true) { return Promise.resolve(_.isFunction(val) ? val() : val) .then(resolve, reject) } else if (args.length === 1) { return Promise.resolve(_.isFunction(las) ? las() : las) .then(resolve, reject) } else { return processBranch(args, resolve, reject) } }, reject) }
[ "function", "processBranch", "(", "args", ",", "resolve", ",", "reject", ")", "{", "let", "condition", "=", "args", ".", "shift", "(", ")", "let", "val", "=", "args", ".", "shift", "(", ")", "let", "las", "=", "_", ".", "last", "(", "args", ")", "return", "Promise", ".", "resolve", "(", "condition", ")", ".", "then", "(", "c", "=>", "{", "if", "(", "c", "===", "true", ")", "{", "return", "Promise", ".", "resolve", "(", "_", ".", "isFunction", "(", "val", ")", "?", "val", "(", ")", ":", "val", ")", ".", "then", "(", "resolve", ",", "reject", ")", "}", "else", "if", "(", "args", ".", "length", "===", "1", ")", "{", "return", "Promise", ".", "resolve", "(", "_", ".", "isFunction", "(", "las", ")", "?", "las", "(", ")", ":", "las", ")", ".", "then", "(", "resolve", ",", "reject", ")", "}", "else", "{", "return", "processBranch", "(", "args", ",", "resolve", ",", "reject", ")", "}", "}", ",", "reject", ")", "}" ]
recursively processes the branch statements @param args @param resolve @param reject @return {*|Promise.<*>|Promise.<TResult>}
[ "recursively", "processes", "the", "branch", "statements" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v.js#L46-L63
43,772
bhoriuchi/vsphere-connect
archive/v.js
performRetrieve
function performRetrieve (req) { return this._client.retrieve(req.args, req.options) .then(result => { req.args = {} req.options = {} return result }) }
javascript
function performRetrieve (req) { return this._client.retrieve(req.args, req.options) .then(result => { req.args = {} req.options = {} return result }) }
[ "function", "performRetrieve", "(", "req", ")", "{", "return", "this", ".", "_client", ".", "retrieve", "(", "req", ".", "args", ",", "req", ".", "options", ")", ".", "then", "(", "result", "=>", "{", "req", ".", "args", "=", "{", "}", "req", ".", "options", "=", "{", "}", "return", "result", "}", ")", "}" ]
retrieves records and clears out the request context @param req @return {*|Promise.<*>}
[ "retrieves", "records", "and", "clears", "out", "the", "request", "context" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v.js#L70-L77
43,773
mmoulton/capture
index.js
function(url, done) { var urlParts = urlUtil.parse(url, true), filename = urlParts.pathname, auth = urlParts.auth; if (S(filename).endsWith("/")) filename += "index"; // Append var filePath = path.resolve( process.cwd(), outPath, S(urlParts.hostname).replaceAll("\\.", "-").s, "./" + filename + "." + format), args = [captureScript, url, filePath, '--username', username, '--password', password, '--paper-orientation', paperOrientation, '--paper-margin', paperMargin, '--paper-format', paperFormat, '--viewport-width', viewportWidth, '--viewport-height', viewportHeight]; var phantom = childProcess.execFile(phantomPath, args, function(err, stdout, stderr) { if (verbose && stdout) console.log("---\nPhantomJS process stdout [%s]:\n" + stdout + "\n---", phantom.pid); if (verbose && stderr) console.log("---\nPhantomJS process stderr [%s]:\n" + stderr + "\n---", phantom.pid); if (verbose) console.log("Rendered %s to %s", url, filePath); done(err); }); if (verbose) console.log("Spawning PhantomJS process [%s] to rasterize '%s' to '%s'", phantom.pid, url, filePath); }
javascript
function(url, done) { var urlParts = urlUtil.parse(url, true), filename = urlParts.pathname, auth = urlParts.auth; if (S(filename).endsWith("/")) filename += "index"; // Append var filePath = path.resolve( process.cwd(), outPath, S(urlParts.hostname).replaceAll("\\.", "-").s, "./" + filename + "." + format), args = [captureScript, url, filePath, '--username', username, '--password', password, '--paper-orientation', paperOrientation, '--paper-margin', paperMargin, '--paper-format', paperFormat, '--viewport-width', viewportWidth, '--viewport-height', viewportHeight]; var phantom = childProcess.execFile(phantomPath, args, function(err, stdout, stderr) { if (verbose && stdout) console.log("---\nPhantomJS process stdout [%s]:\n" + stdout + "\n---", phantom.pid); if (verbose && stderr) console.log("---\nPhantomJS process stderr [%s]:\n" + stderr + "\n---", phantom.pid); if (verbose) console.log("Rendered %s to %s", url, filePath); done(err); }); if (verbose) console.log("Spawning PhantomJS process [%s] to rasterize '%s' to '%s'", phantom.pid, url, filePath); }
[ "function", "(", "url", ",", "done", ")", "{", "var", "urlParts", "=", "urlUtil", ".", "parse", "(", "url", ",", "true", ")", ",", "filename", "=", "urlParts", ".", "pathname", ",", "auth", "=", "urlParts", ".", "auth", ";", "if", "(", "S", "(", "filename", ")", ".", "endsWith", "(", "\"/\"", ")", ")", "filename", "+=", "\"index\"", ";", "// Append", "var", "filePath", "=", "path", ".", "resolve", "(", "process", ".", "cwd", "(", ")", ",", "outPath", ",", "S", "(", "urlParts", ".", "hostname", ")", ".", "replaceAll", "(", "\"\\\\.\"", ",", "\"-\"", ")", ".", "s", ",", "\"./\"", "+", "filename", "+", "\".\"", "+", "format", ")", ",", "args", "=", "[", "captureScript", ",", "url", ",", "filePath", ",", "'--username'", ",", "username", ",", "'--password'", ",", "password", ",", "'--paper-orientation'", ",", "paperOrientation", ",", "'--paper-margin'", ",", "paperMargin", ",", "'--paper-format'", ",", "paperFormat", ",", "'--viewport-width'", ",", "viewportWidth", ",", "'--viewport-height'", ",", "viewportHeight", "]", ";", "var", "phantom", "=", "childProcess", ".", "execFile", "(", "phantomPath", ",", "args", ",", "function", "(", "err", ",", "stdout", ",", "stderr", ")", "{", "if", "(", "verbose", "&&", "stdout", ")", "console", ".", "log", "(", "\"---\\nPhantomJS process stdout [%s]:\\n\"", "+", "stdout", "+", "\"\\n---\"", ",", "phantom", ".", "pid", ")", ";", "if", "(", "verbose", "&&", "stderr", ")", "console", ".", "log", "(", "\"---\\nPhantomJS process stderr [%s]:\\n\"", "+", "stderr", "+", "\"\\n---\"", ",", "phantom", ".", "pid", ")", ";", "if", "(", "verbose", ")", "console", ".", "log", "(", "\"Rendered %s to %s\"", ",", "url", ",", "filePath", ")", ";", "done", "(", "err", ")", ";", "}", ")", ";", "if", "(", "verbose", ")", "console", ".", "log", "(", "\"Spawning PhantomJS process [%s] to rasterize '%s' to '%s'\"", ",", "phantom", ".", "pid", ",", "url", ",", "filePath", ")", ";", "}" ]
For each url
[ "For", "each", "url" ]
794a0542603c4ff1f908d5d00c1bd3cda5c490ec
https://github.com/mmoulton/capture/blob/794a0542603c4ff1f908d5d00c1bd3cda5c490ec/index.js#L54-L80
43,774
bhoriuchi/vsphere-connect
archive/v1/client/findByName.js
rootSearch
function rootSearch(args) { // get the datacenters return _client.retrieve({ type: 'Datacenter', properties: ['name', 'datastoreFolder', 'hostFolder', 'networkFolder', 'vmFolder'] }) .then(function(dcs) { // look through each of the dcs and map the return values return Promise.map(dcs, function(dc) { var folderId; // get the correct folder id to start search from or if searching if (args.type === 'Datastore') { folderId = dc.datastoreFolder; } else if (args.type === 'HostSystem') { folderId = dc.hostFolder; } else if (args.type === 'Network') { folderId = dc.networkFolder; } else if (args.type === 'VirtualMachine') { folderId = dc.vmFolder; } // return the entity details return { type: 'Folder', id: folderId }; }); }); }
javascript
function rootSearch(args) { // get the datacenters return _client.retrieve({ type: 'Datacenter', properties: ['name', 'datastoreFolder', 'hostFolder', 'networkFolder', 'vmFolder'] }) .then(function(dcs) { // look through each of the dcs and map the return values return Promise.map(dcs, function(dc) { var folderId; // get the correct folder id to start search from or if searching if (args.type === 'Datastore') { folderId = dc.datastoreFolder; } else if (args.type === 'HostSystem') { folderId = dc.hostFolder; } else if (args.type === 'Network') { folderId = dc.networkFolder; } else if (args.type === 'VirtualMachine') { folderId = dc.vmFolder; } // return the entity details return { type: 'Folder', id: folderId }; }); }); }
[ "function", "rootSearch", "(", "args", ")", "{", "// get the datacenters", "return", "_client", ".", "retrieve", "(", "{", "type", ":", "'Datacenter'", ",", "properties", ":", "[", "'name'", ",", "'datastoreFolder'", ",", "'hostFolder'", ",", "'networkFolder'", ",", "'vmFolder'", "]", "}", ")", ".", "then", "(", "function", "(", "dcs", ")", "{", "// look through each of the dcs and map the return values", "return", "Promise", ".", "map", "(", "dcs", ",", "function", "(", "dc", ")", "{", "var", "folderId", ";", "// get the correct folder id to start search from or if searching", "if", "(", "args", ".", "type", "===", "'Datastore'", ")", "{", "folderId", "=", "dc", ".", "datastoreFolder", ";", "}", "else", "if", "(", "args", ".", "type", "===", "'HostSystem'", ")", "{", "folderId", "=", "dc", ".", "hostFolder", ";", "}", "else", "if", "(", "args", ".", "type", "===", "'Network'", ")", "{", "folderId", "=", "dc", ".", "networkFolder", ";", "}", "else", "if", "(", "args", ".", "type", "===", "'VirtualMachine'", ")", "{", "folderId", "=", "dc", ".", "vmFolder", ";", "}", "// return the entity details", "return", "{", "type", ":", "'Folder'", ",", "id", ":", "folderId", "}", ";", "}", ")", ";", "}", ")", ";", "}" ]
search the top level folders in each datacenter
[ "search", "the", "top", "level", "folders", "in", "each", "datacenter" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/client/findByName.js#L23-L58
43,775
bhoriuchi/vsphere-connect
archive/v1/client/findByName.js
findByNameEx
function findByNameEx(args, matches) { // create a variable to store the matches matches = matches || []; // set option defaults args.name = Array.isArray(args.name) ? args.name : [args.name]; args.recursive = (typeof(args.recursive) === 'boolean') ? args.recursive : false; args.limit = !isNaN(args.limit) ? args.limit : 1; args.properties = args.properties || []; // check for a starting point, if one doesnt exist begin at the datacenter level if (!args.parent) { return rootSearch(args) .then(function(parents) { return findByNameEx({ type : args.type, name : args.name, properties : args.properties, parent : parents, recursive : args.recursive, limit : args.limit }, matches); }); } // convert the parent to an array if it is not one args.parent = Array.isArray(args.parent) ? args.parent : [args.parent]; // perform the search return Promise.each(args.parent, function(parent) { // check if the match limit is met if (matches.length >= args.limit) { return; } // perform the search on each name return Promise.each(args.name, function(name) { // check if the match limit is met if (matches.length >= args.limit) { return; } // perform the search return _client.getServiceContent({ method: 'FindChild', service: 'searchIndex', params: { entity: util.moRef(parent.type, parent.id), name: name } }) .then(function(result) { var id = _.get(result, '$value'); if (id) { matches.push(id); } }); }) .then(function() { // check if the match limit is met, if not and recursive // attempt to descend the child objects if (matches.length < args.limit && args.recursive) { // get the children of the current parent return _client.retrieve({ type: parent.type, id: parent.id, properties: ['childEntity'] }) .then(function(mo) { var parents = []; // get all of the child folders _.forEach(_.get(mo, '[0].childEntity'), function(child) { if (child.match(/^group-.*/)) { parents.push({ type: 'Folder', id: child }); } }); // if there were folders, recurse if (parents.length > 0) { return findByNameEx({ type : args.type, name : args.name, properties : args.properties, parent : parents, recursive : args.recursive, limit : args.limit }, matches); } }); } }); }) .then(function() { return matches; }); }
javascript
function findByNameEx(args, matches) { // create a variable to store the matches matches = matches || []; // set option defaults args.name = Array.isArray(args.name) ? args.name : [args.name]; args.recursive = (typeof(args.recursive) === 'boolean') ? args.recursive : false; args.limit = !isNaN(args.limit) ? args.limit : 1; args.properties = args.properties || []; // check for a starting point, if one doesnt exist begin at the datacenter level if (!args.parent) { return rootSearch(args) .then(function(parents) { return findByNameEx({ type : args.type, name : args.name, properties : args.properties, parent : parents, recursive : args.recursive, limit : args.limit }, matches); }); } // convert the parent to an array if it is not one args.parent = Array.isArray(args.parent) ? args.parent : [args.parent]; // perform the search return Promise.each(args.parent, function(parent) { // check if the match limit is met if (matches.length >= args.limit) { return; } // perform the search on each name return Promise.each(args.name, function(name) { // check if the match limit is met if (matches.length >= args.limit) { return; } // perform the search return _client.getServiceContent({ method: 'FindChild', service: 'searchIndex', params: { entity: util.moRef(parent.type, parent.id), name: name } }) .then(function(result) { var id = _.get(result, '$value'); if (id) { matches.push(id); } }); }) .then(function() { // check if the match limit is met, if not and recursive // attempt to descend the child objects if (matches.length < args.limit && args.recursive) { // get the children of the current parent return _client.retrieve({ type: parent.type, id: parent.id, properties: ['childEntity'] }) .then(function(mo) { var parents = []; // get all of the child folders _.forEach(_.get(mo, '[0].childEntity'), function(child) { if (child.match(/^group-.*/)) { parents.push({ type: 'Folder', id: child }); } }); // if there were folders, recurse if (parents.length > 0) { return findByNameEx({ type : args.type, name : args.name, properties : args.properties, parent : parents, recursive : args.recursive, limit : args.limit }, matches); } }); } }); }) .then(function() { return matches; }); }
[ "function", "findByNameEx", "(", "args", ",", "matches", ")", "{", "// create a variable to store the matches", "matches", "=", "matches", "||", "[", "]", ";", "// set option defaults", "args", ".", "name", "=", "Array", ".", "isArray", "(", "args", ".", "name", ")", "?", "args", ".", "name", ":", "[", "args", ".", "name", "]", ";", "args", ".", "recursive", "=", "(", "typeof", "(", "args", ".", "recursive", ")", "===", "'boolean'", ")", "?", "args", ".", "recursive", ":", "false", ";", "args", ".", "limit", "=", "!", "isNaN", "(", "args", ".", "limit", ")", "?", "args", ".", "limit", ":", "1", ";", "args", ".", "properties", "=", "args", ".", "properties", "||", "[", "]", ";", "// check for a starting point, if one doesnt exist begin at the datacenter level", "if", "(", "!", "args", ".", "parent", ")", "{", "return", "rootSearch", "(", "args", ")", ".", "then", "(", "function", "(", "parents", ")", "{", "return", "findByNameEx", "(", "{", "type", ":", "args", ".", "type", ",", "name", ":", "args", ".", "name", ",", "properties", ":", "args", ".", "properties", ",", "parent", ":", "parents", ",", "recursive", ":", "args", ".", "recursive", ",", "limit", ":", "args", ".", "limit", "}", ",", "matches", ")", ";", "}", ")", ";", "}", "// convert the parent to an array if it is not one", "args", ".", "parent", "=", "Array", ".", "isArray", "(", "args", ".", "parent", ")", "?", "args", ".", "parent", ":", "[", "args", ".", "parent", "]", ";", "// perform the search", "return", "Promise", ".", "each", "(", "args", ".", "parent", ",", "function", "(", "parent", ")", "{", "// check if the match limit is met", "if", "(", "matches", ".", "length", ">=", "args", ".", "limit", ")", "{", "return", ";", "}", "// perform the search on each name", "return", "Promise", ".", "each", "(", "args", ".", "name", ",", "function", "(", "name", ")", "{", "// check if the match limit is met", "if", "(", "matches", ".", "length", ">=", "args", ".", "limit", ")", "{", "return", ";", "}", "// perform the search", "return", "_client", ".", "getServiceContent", "(", "{", "method", ":", "'FindChild'", ",", "service", ":", "'searchIndex'", ",", "params", ":", "{", "entity", ":", "util", ".", "moRef", "(", "parent", ".", "type", ",", "parent", ".", "id", ")", ",", "name", ":", "name", "}", "}", ")", ".", "then", "(", "function", "(", "result", ")", "{", "var", "id", "=", "_", ".", "get", "(", "result", ",", "'$value'", ")", ";", "if", "(", "id", ")", "{", "matches", ".", "push", "(", "id", ")", ";", "}", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "// check if the match limit is met, if not and recursive", "// attempt to descend the child objects", "if", "(", "matches", ".", "length", "<", "args", ".", "limit", "&&", "args", ".", "recursive", ")", "{", "// get the children of the current parent", "return", "_client", ".", "retrieve", "(", "{", "type", ":", "parent", ".", "type", ",", "id", ":", "parent", ".", "id", ",", "properties", ":", "[", "'childEntity'", "]", "}", ")", ".", "then", "(", "function", "(", "mo", ")", "{", "var", "parents", "=", "[", "]", ";", "// get all of the child folders", "_", ".", "forEach", "(", "_", ".", "get", "(", "mo", ",", "'[0].childEntity'", ")", ",", "function", "(", "child", ")", "{", "if", "(", "child", ".", "match", "(", "/", "^group-.*", "/", ")", ")", "{", "parents", ".", "push", "(", "{", "type", ":", "'Folder'", ",", "id", ":", "child", "}", ")", ";", "}", "}", ")", ";", "// if there were folders, recurse", "if", "(", "parents", ".", "length", ">", "0", ")", "{", "return", "findByNameEx", "(", "{", "type", ":", "args", ".", "type", ",", "name", ":", "args", ".", "name", ",", "properties", ":", "args", ".", "properties", ",", "parent", ":", "parents", ",", "recursive", ":", "args", ".", "recursive", ",", "limit", ":", "args", ".", "limit", "}", ",", "matches", ")", ";", "}", "}", ")", ";", "}", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "return", "matches", ";", "}", ")", ";", "}" ]
recursive function to find matches
[ "recursive", "function", "to", "find", "matches" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/client/findByName.js#L64-L171
43,776
bhoriuchi/vsphere-connect
archive/v1/client/findByName.js
findByName
function findByName(args) { // validate the types if (!args.type || !_.includes(['Datastore', 'HostSystem', 'Network', 'VirtualMachine'], args.type)) { return new Promise(function(resolve, reject) { reject({ errorCode: 400, message: 'Invalid search type. Valid types are Datastore, HostSystem, Network, and VirtualMachine' }); }); } // start the search return findByNameEx(args).then(function(matches) { // if no matches return an empty array if (!matches || (Array.isArray(matches) && matches.length === 0)) { return []; } // check for an ID only response and format the matches as an array of objects else if (Array.isArray(args.properties) && (args.properties.length === 0 || args.properties[0] === 'id')) { return _.map(matches, function(id) { return {id: id}; }); } // otherwise add get the items with their properties return _client.retrieve({ type: args.type, id: matches, properties: args.properties }); }); }
javascript
function findByName(args) { // validate the types if (!args.type || !_.includes(['Datastore', 'HostSystem', 'Network', 'VirtualMachine'], args.type)) { return new Promise(function(resolve, reject) { reject({ errorCode: 400, message: 'Invalid search type. Valid types are Datastore, HostSystem, Network, and VirtualMachine' }); }); } // start the search return findByNameEx(args).then(function(matches) { // if no matches return an empty array if (!matches || (Array.isArray(matches) && matches.length === 0)) { return []; } // check for an ID only response and format the matches as an array of objects else if (Array.isArray(args.properties) && (args.properties.length === 0 || args.properties[0] === 'id')) { return _.map(matches, function(id) { return {id: id}; }); } // otherwise add get the items with their properties return _client.retrieve({ type: args.type, id: matches, properties: args.properties }); }); }
[ "function", "findByName", "(", "args", ")", "{", "// validate the types", "if", "(", "!", "args", ".", "type", "||", "!", "_", ".", "includes", "(", "[", "'Datastore'", ",", "'HostSystem'", ",", "'Network'", ",", "'VirtualMachine'", "]", ",", "args", ".", "type", ")", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "reject", "(", "{", "errorCode", ":", "400", ",", "message", ":", "'Invalid search type. Valid types are Datastore, HostSystem, Network, and VirtualMachine'", "}", ")", ";", "}", ")", ";", "}", "// start the search", "return", "findByNameEx", "(", "args", ")", ".", "then", "(", "function", "(", "matches", ")", "{", "// if no matches return an empty array", "if", "(", "!", "matches", "||", "(", "Array", ".", "isArray", "(", "matches", ")", "&&", "matches", ".", "length", "===", "0", ")", ")", "{", "return", "[", "]", ";", "}", "// check for an ID only response and format the matches as an array of objects", "else", "if", "(", "Array", ".", "isArray", "(", "args", ".", "properties", ")", "&&", "(", "args", ".", "properties", ".", "length", "===", "0", "||", "args", ".", "properties", "[", "0", "]", "===", "'id'", ")", ")", "{", "return", "_", ".", "map", "(", "matches", ",", "function", "(", "id", ")", "{", "return", "{", "id", ":", "id", "}", ";", "}", ")", ";", "}", "// otherwise add get the items with their properties", "return", "_client", ".", "retrieve", "(", "{", "type", ":", "args", ".", "type", ",", "id", ":", "matches", ",", "properties", ":", "args", ".", "properties", "}", ")", ";", "}", ")", ";", "}" ]
finds entities by name @param {Object} args - Arguments hash @param {string} args.type - Type of entity to search for @param {(string|string[])} args.name - Name or names to search for @param {(Object|Object[])} [args.parent] - Parent entity or array of parent enties to search from @param {string} [args.parent.type] - Parent type @param {string} [args.parent.id] - Parent id @param {boolean} [recursive=false] - Recursively search the parent @param {number} [limit=1] - Limit results
[ "finds", "entities", "by", "name" ]
2203b678847a57e3cb982f1a23277d44444f6de4
https://github.com/bhoriuchi/vsphere-connect/blob/2203b678847a57e3cb982f1a23277d44444f6de4/archive/v1/client/findByName.js#L185-L219
43,777
silas/swagger-framework
lib/resource.js
Resource
function Resource(spec, options) { if (!(this instanceof Resource)) { return new Resource(spec, options); } if (typeof spec !== 'object') { throw new Error('resource spec must be an object'); } debug('create resource %s', spec.path, spec); this.spec = spec; this.list = []; this.options = options || {}; this.middleware = {}; this.operations = {}; }
javascript
function Resource(spec, options) { if (!(this instanceof Resource)) { return new Resource(spec, options); } if (typeof spec !== 'object') { throw new Error('resource spec must be an object'); } debug('create resource %s', spec.path, spec); this.spec = spec; this.list = []; this.options = options || {}; this.middleware = {}; this.operations = {}; }
[ "function", "Resource", "(", "spec", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Resource", ")", ")", "{", "return", "new", "Resource", "(", "spec", ",", "options", ")", ";", "}", "if", "(", "typeof", "spec", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "'resource spec must be an object'", ")", ";", "}", "debug", "(", "'create resource %s'", ",", "spec", ".", "path", ",", "spec", ")", ";", "this", ".", "spec", "=", "spec", ";", "this", ".", "list", "=", "[", "]", ";", "this", ".", "options", "=", "options", "||", "{", "}", ";", "this", ".", "middleware", "=", "{", "}", ";", "this", ".", "operations", "=", "{", "}", ";", "}" ]
Initialize a new `Resource`. @param {Object} spec @param {Object} options @api public
[ "Initialize", "a", "new", "Resource", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/resource.js#L29-L46
43,778
theblacksmith/chai-param
lib/chai-param.js
c
function c(color, text) { if(chaiParam.config.disableColors) return text; return chalk[color](text); }
javascript
function c(color, text) { if(chaiParam.config.disableColors) return text; return chalk[color](text); }
[ "function", "c", "(", "color", ",", "text", ")", "{", "if", "(", "chaiParam", ".", "config", ".", "disableColors", ")", "return", "text", ";", "return", "chalk", "[", "color", "]", "(", "text", ")", ";", "}" ]
chalk wrapper for easy enabling and disabling colors
[ "chalk", "wrapper", "for", "easy", "enabling", "and", "disabling", "colors" ]
6a30ba4402afa988a38e392c56dec3d7864970ff
https://github.com/theblacksmith/chai-param/blob/6a30ba4402afa988a38e392c56dec3d7864970ff/lib/chai-param.js#L18-L23
43,779
opendxl/opendxl-client-javascript
lib/_cli/cli-util.js
fillEmptyOptionsFromPrompt
function fillEmptyOptionsFromPrompt (options, args, callback, startPosition) { if (typeof startPosition === 'undefined') { startPosition = 0 } if (startPosition < 0) { throw new RangeError('Start position must not be negative') } if (startPosition > args.length) { throw new RangeError('Start position (' + startPosition + ') is greater than length of args (' + args.length + ')') } if (startPosition === args.length) { callback(null, options) } else { var arg = args[startPosition] if (options[arg.name]) { fillEmptyOptionsFromPrompt(options, args, callback, startPosition + 1) } else { module.exports.getValueFromPrompt(arg.title || arg.name, arg.confirm, function (error, result) { if (error) { callback(error) } else { options[arg.name] = result fillEmptyOptionsFromPrompt(options, args, callback, startPosition + 1) } } ) } } }
javascript
function fillEmptyOptionsFromPrompt (options, args, callback, startPosition) { if (typeof startPosition === 'undefined') { startPosition = 0 } if (startPosition < 0) { throw new RangeError('Start position must not be negative') } if (startPosition > args.length) { throw new RangeError('Start position (' + startPosition + ') is greater than length of args (' + args.length + ')') } if (startPosition === args.length) { callback(null, options) } else { var arg = args[startPosition] if (options[arg.name]) { fillEmptyOptionsFromPrompt(options, args, callback, startPosition + 1) } else { module.exports.getValueFromPrompt(arg.title || arg.name, arg.confirm, function (error, result) { if (error) { callback(error) } else { options[arg.name] = result fillEmptyOptionsFromPrompt(options, args, callback, startPosition + 1) } } ) } } }
[ "function", "fillEmptyOptionsFromPrompt", "(", "options", ",", "args", ",", "callback", ",", "startPosition", ")", "{", "if", "(", "typeof", "startPosition", "===", "'undefined'", ")", "{", "startPosition", "=", "0", "}", "if", "(", "startPosition", "<", "0", ")", "{", "throw", "new", "RangeError", "(", "'Start position must not be negative'", ")", "}", "if", "(", "startPosition", ">", "args", ".", "length", ")", "{", "throw", "new", "RangeError", "(", "'Start position ('", "+", "startPosition", "+", "') is greater than length of args ('", "+", "args", ".", "length", "+", "')'", ")", "}", "if", "(", "startPosition", "===", "args", ".", "length", ")", "{", "callback", "(", "null", ",", "options", ")", "}", "else", "{", "var", "arg", "=", "args", "[", "startPosition", "]", "if", "(", "options", "[", "arg", ".", "name", "]", ")", "{", "fillEmptyOptionsFromPrompt", "(", "options", ",", "args", ",", "callback", ",", "startPosition", "+", "1", ")", "}", "else", "{", "module", ".", "exports", ".", "getValueFromPrompt", "(", "arg", ".", "title", "||", "arg", ".", "name", ",", "arg", ".", "confirm", ",", "function", "(", "error", ",", "result", ")", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", "}", "else", "{", "options", "[", "arg", ".", "name", "]", "=", "result", "fillEmptyOptionsFromPrompt", "(", "options", ",", "args", ",", "callback", ",", "startPosition", "+", "1", ")", "}", "}", ")", "}", "}", "}" ]
For each arg in the args object, check to see if a corresponding non-empty value is set in the options object. For any unset value, prompt the user on the console for a value to set into the options object. Argument input is processed asynchronously, with a call made to the function specified in the callback argument after all arguments have been processed. @param {Object} options - Object whose values should be non-empty for each name in the corresponding args object. @param {Array<Object>} args - Info for the key to check in the options object. @param {String} args.name - Name to match to a key in the options object. @param {String} args.title - Title to display to the user when prompting for a value to store in the options object. @param {Boolean} [args.confirm=false] - Whether or not the user should be prompted to enter the value twice for an option - to confirm the original value. @param {Function} callback - Function to invoke after all arguments have been processed. @param {Number} [startPosition=0] - Starting position (0-based) in the arguments array to process.
[ "For", "each", "arg", "in", "the", "args", "object", "check", "to", "see", "if", "a", "corresponding", "non", "-", "empty", "value", "is", "set", "in", "the", "options", "object", ".", "For", "any", "unset", "value", "prompt", "the", "user", "on", "the", "console", "for", "a", "value", "to", "set", "into", "the", "options", "object", ".", "Argument", "input", "is", "processed", "asynchronously", "with", "a", "call", "made", "to", "the", "function", "specified", "in", "the", "callback", "argument", "after", "all", "arguments", "have", "been", "processed", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_cli/cli-util.js#L33-L63
43,780
opendxl/opendxl-client-javascript
lib/_cli/cli-util.js
function (program) { var verbosity = program.verbose if (program.quiet) { verbosity = 0 } else if (typeof verbosity === 'undefined') { verbosity = 1 } return verbosity }
javascript
function (program) { var verbosity = program.verbose if (program.quiet) { verbosity = 0 } else if (typeof verbosity === 'undefined') { verbosity = 1 } return verbosity }
[ "function", "(", "program", ")", "{", "var", "verbosity", "=", "program", ".", "verbose", "if", "(", "program", ".", "quiet", ")", "{", "verbosity", "=", "0", "}", "else", "if", "(", "typeof", "verbosity", "===", "'undefined'", ")", "{", "verbosity", "=", "1", "}", "return", "verbosity", "}" ]
Determines the logging verbosity for the specified Commander program object. @param {Program} program - Commander program / command. @returns {Number} Verbosity level where 0 = silence to N = most verbose.
[ "Determines", "the", "logging", "verbosity", "for", "the", "specified", "Commander", "program", "object", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_cli/cli-util.js#L72-L80
43,781
opendxl/opendxl-client-javascript
lib/_cli/cli-util.js
function (title, confirm, callback) { var fullTitle = title.indexOf('Confirm') === 0 ? title : 'Enter ' + title fullTitle += ':' read({ prompt: fullTitle, silent: true }, function (error, result) { if (error) { process.stdout.write('\n') callback(provisionUtil.createFormattedDxlError( 'Error obtaining value for prompt: ' + title)) } else if (result) { if (confirm) { module.exports.getValueFromPrompt('Confirm ' + title, false, function (error, confirmationResult) { if (error) { process.stdout.write('\n') callback(provisionUtil.createFormattedDxlError( 'Error obtaining confirmation value for prompt: ' + title)) } else if (result === confirmationResult) { callback(null, result) } else { process.stdout.write('Values for ' + title + ' do not match. Try again.\n') module.exports.getValueFromPrompt(title, true, callback) } } ) } else { callback(null, result) } } else { process.stdout.write('Value cannot be empty. Try again.\n') module.exports.getValueFromPrompt(title, confirm, callback) } }) }
javascript
function (title, confirm, callback) { var fullTitle = title.indexOf('Confirm') === 0 ? title : 'Enter ' + title fullTitle += ':' read({ prompt: fullTitle, silent: true }, function (error, result) { if (error) { process.stdout.write('\n') callback(provisionUtil.createFormattedDxlError( 'Error obtaining value for prompt: ' + title)) } else if (result) { if (confirm) { module.exports.getValueFromPrompt('Confirm ' + title, false, function (error, confirmationResult) { if (error) { process.stdout.write('\n') callback(provisionUtil.createFormattedDxlError( 'Error obtaining confirmation value for prompt: ' + title)) } else if (result === confirmationResult) { callback(null, result) } else { process.stdout.write('Values for ' + title + ' do not match. Try again.\n') module.exports.getValueFromPrompt(title, true, callback) } } ) } else { callback(null, result) } } else { process.stdout.write('Value cannot be empty. Try again.\n') module.exports.getValueFromPrompt(title, confirm, callback) } }) }
[ "function", "(", "title", ",", "confirm", ",", "callback", ")", "{", "var", "fullTitle", "=", "title", ".", "indexOf", "(", "'Confirm'", ")", "===", "0", "?", "title", ":", "'Enter '", "+", "title", "fullTitle", "+=", "':'", "read", "(", "{", "prompt", ":", "fullTitle", ",", "silent", ":", "true", "}", ",", "function", "(", "error", ",", "result", ")", "{", "if", "(", "error", ")", "{", "process", ".", "stdout", ".", "write", "(", "'\\n'", ")", "callback", "(", "provisionUtil", ".", "createFormattedDxlError", "(", "'Error obtaining value for prompt: '", "+", "title", ")", ")", "}", "else", "if", "(", "result", ")", "{", "if", "(", "confirm", ")", "{", "module", ".", "exports", ".", "getValueFromPrompt", "(", "'Confirm '", "+", "title", ",", "false", ",", "function", "(", "error", ",", "confirmationResult", ")", "{", "if", "(", "error", ")", "{", "process", ".", "stdout", ".", "write", "(", "'\\n'", ")", "callback", "(", "provisionUtil", ".", "createFormattedDxlError", "(", "'Error obtaining confirmation value for prompt: '", "+", "title", ")", ")", "}", "else", "if", "(", "result", "===", "confirmationResult", ")", "{", "callback", "(", "null", ",", "result", ")", "}", "else", "{", "process", ".", "stdout", ".", "write", "(", "'Values for '", "+", "title", "+", "' do not match. Try again.\\n'", ")", "module", ".", "exports", ".", "getValueFromPrompt", "(", "title", ",", "true", ",", "callback", ")", "}", "}", ")", "}", "else", "{", "callback", "(", "null", ",", "result", ")", "}", "}", "else", "{", "process", ".", "stdout", ".", "write", "(", "'Value cannot be empty. Try again.\\n'", ")", "module", ".", "exports", ".", "getValueFromPrompt", "(", "title", ",", "confirm", ",", "callback", ")", "}", "}", ")", "}" ]
Reads a value from standard input. The characters entered by the user are not echoed to the console. @param {String} title - Prompt string title to display. @param {Boolean} confirm - Whether or not to prompt the user to enter the value a second time before using it. This could be used for validating the user's selection for sensitive values like passwords. @param {Function} callback - Callback function to invoke with the value entered by the user.
[ "Reads", "a", "value", "from", "standard", "input", ".", "The", "characters", "entered", "by", "the", "user", "are", "not", "echoed", "to", "the", "console", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_cli/cli-util.js#L91-L127
43,782
opendxl/opendxl-client-javascript
lib/_cli/cli-util.js
function (hostname, command) { var hostInfo = {hostname: hostname, user: '', password: ''} var hostInfoKeys = ['port', 'user', 'password', 'truststore'] hostInfoKeys.forEach(function (hostInfoKey) { if (command[hostInfoKey]) { hostInfo[hostInfoKey] = command[hostInfoKey] delete command[hostInfoKey] } }) return hostInfo }
javascript
function (hostname, command) { var hostInfo = {hostname: hostname, user: '', password: ''} var hostInfoKeys = ['port', 'user', 'password', 'truststore'] hostInfoKeys.forEach(function (hostInfoKey) { if (command[hostInfoKey]) { hostInfo[hostInfoKey] = command[hostInfoKey] delete command[hostInfoKey] } }) return hostInfo }
[ "function", "(", "hostname", ",", "command", ")", "{", "var", "hostInfo", "=", "{", "hostname", ":", "hostname", ",", "user", ":", "''", ",", "password", ":", "''", "}", "var", "hostInfoKeys", "=", "[", "'port'", ",", "'user'", ",", "'password'", ",", "'truststore'", "]", "hostInfoKeys", ".", "forEach", "(", "function", "(", "hostInfoKey", ")", "{", "if", "(", "command", "[", "hostInfoKey", "]", ")", "{", "hostInfo", "[", "hostInfoKey", "]", "=", "command", "[", "hostInfoKey", "]", "delete", "command", "[", "hostInfoKey", "]", "}", "}", ")", "return", "hostInfo", "}" ]
Extract host info from the supplied Commander-based command. Host-info keys are removed from the command. @param {String} hostname - Name of the management service host. @param {Command} command - The Commander command to extract host info from. @returns {ManagementServiceHostInfo} The host info.
[ "Extract", "host", "info", "from", "the", "supplied", "Commander", "-", "based", "command", ".", "Host", "-", "info", "keys", "are", "removed", "from", "the", "command", "." ]
eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997
https://github.com/opendxl/opendxl-client-javascript/blob/eb947dcba18b9c34f5ccb3f0f6cccf2db70b4997/lib/_cli/cli-util.js#L171-L181
43,783
silas/swagger-framework
lib/api.js
Api
function Api(spec, options) { if (!(this instanceof Api)) { return new Api(spec, options); } if (typeof spec !== 'object') { throw new Error('api spec must be an object'); } options = options || {}; // path alias for both resourcePath and doc path if (spec.path) { if (!spec.resourcePath) spec.resourcePath = spec.path; if (!options.path) options.path = spec.path; delete spec.path; } // allow user to pass description in spec if (spec.description) { if (!options.description) options.description = spec.description; delete spec.description; } // user resourcePath for doc path if not set if (!options.path && spec.resourcePath) { options.path = spec.resourcePath; } debug('create api %s', spec.resourcePath, spec); this.env = new Environment(); this.spec = spec; this.list = []; this.options = options; this.middleware = {}; this.models = {}; this.nicknames = {}; this.resources = {}; }
javascript
function Api(spec, options) { if (!(this instanceof Api)) { return new Api(spec, options); } if (typeof spec !== 'object') { throw new Error('api spec must be an object'); } options = options || {}; // path alias for both resourcePath and doc path if (spec.path) { if (!spec.resourcePath) spec.resourcePath = spec.path; if (!options.path) options.path = spec.path; delete spec.path; } // allow user to pass description in spec if (spec.description) { if (!options.description) options.description = spec.description; delete spec.description; } // user resourcePath for doc path if not set if (!options.path && spec.resourcePath) { options.path = spec.resourcePath; } debug('create api %s', spec.resourcePath, spec); this.env = new Environment(); this.spec = spec; this.list = []; this.options = options; this.middleware = {}; this.models = {}; this.nicknames = {}; this.resources = {}; }
[ "function", "Api", "(", "spec", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Api", ")", ")", "{", "return", "new", "Api", "(", "spec", ",", "options", ")", ";", "}", "if", "(", "typeof", "spec", "!==", "'object'", ")", "{", "throw", "new", "Error", "(", "'api spec must be an object'", ")", ";", "}", "options", "=", "options", "||", "{", "}", ";", "// path alias for both resourcePath and doc path", "if", "(", "spec", ".", "path", ")", "{", "if", "(", "!", "spec", ".", "resourcePath", ")", "spec", ".", "resourcePath", "=", "spec", ".", "path", ";", "if", "(", "!", "options", ".", "path", ")", "options", ".", "path", "=", "spec", ".", "path", ";", "delete", "spec", ".", "path", ";", "}", "// allow user to pass description in spec", "if", "(", "spec", ".", "description", ")", "{", "if", "(", "!", "options", ".", "description", ")", "options", ".", "description", "=", "spec", ".", "description", ";", "delete", "spec", ".", "description", ";", "}", "// user resourcePath for doc path if not set", "if", "(", "!", "options", ".", "path", "&&", "spec", ".", "resourcePath", ")", "{", "options", ".", "path", "=", "spec", ".", "resourcePath", ";", "}", "debug", "(", "'create api %s'", ",", "spec", ".", "resourcePath", ",", "spec", ")", ";", "this", ".", "env", "=", "new", "Environment", "(", ")", ";", "this", ".", "spec", "=", "spec", ";", "this", ".", "list", "=", "[", "]", ";", "this", ".", "options", "=", "options", ";", "this", ".", "middleware", "=", "{", "}", ";", "this", ".", "models", "=", "{", "}", ";", "this", ".", "nicknames", "=", "{", "}", ";", "this", ".", "resources", "=", "{", "}", ";", "}" ]
Initialize a new `Api`. @param {Object} spec @param {Object} options @api public
[ "Initialize", "a", "new", "Api", "." ]
d5b5bcb30feafc5e37b431ec09e494f9b6303950
https://github.com/silas/swagger-framework/blob/d5b5bcb30feafc5e37b431ec09e494f9b6303950/lib/api.js#L28-L69
43,784
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(self, obj) { self.stack = ''; for(var key in obj) { self[key] = obj[key]; } }
javascript
function(self, obj) { self.stack = ''; for(var key in obj) { self[key] = obj[key]; } }
[ "function", "(", "self", ",", "obj", ")", "{", "self", ".", "stack", "=", "''", ";", "for", "(", "var", "key", "in", "obj", ")", "{", "self", "[", "key", "]", "=", "obj", "[", "key", "]", ";", "}", "}" ]
used by Exception
[ "used", "by", "Exception" ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L2023-L2030
43,785
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(s, p, o) { if(p in s) { if(s[p].constructor === Array) { s[p].push(o); } else { s[p] = [s[p], o]; } } else { s[p] = o; } }
javascript
function(s, p, o) { if(p in s) { if(s[p].constructor === Array) { s[p].push(o); } else { s[p] = [s[p], o]; } } else { s[p] = o; } }
[ "function", "(", "s", ",", "p", ",", "o", ")", "{", "if", "(", "p", "in", "s", ")", "{", "if", "(", "s", "[", "p", "]", ".", "constructor", "===", "Array", ")", "{", "s", "[", "p", "]", ".", "push", "(", "o", ")", ";", "}", "else", "{", "s", "[", "p", "]", "=", "[", "s", "[", "p", "]", ",", "o", "]", ";", "}", "}", "else", "{", "s", "[", "p", "]", "=", "o", ";", "}", "}" ]
Sets a subject's property to the given object value. If a value already exists, it will be appended to an array. @param s the subject. @param p the property. @param o the object.
[ "Sets", "a", "subject", "s", "property", "to", "the", "given", "object", "value", ".", "If", "a", "value", "already", "exists", "it", "will", "be", "appended", "to", "an", "array", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L2150-L2167
43,786
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(ctx) { // TODO: reduce calls to this function by caching keywords in processor // state var rval = { '@id': '@id', '@language': '@language', '@literal': '@literal', '@type': '@type' }; if(ctx) { // gather keyword aliases from context var keywords = {}; for(var key in ctx) { if(ctx[key].constructor === String && ctx[key] in rval) { keywords[ctx[key]] = key; } } // overwrite keywords for(var key in keywords) { rval[key] = keywords[key]; } } return rval; }
javascript
function(ctx) { // TODO: reduce calls to this function by caching keywords in processor // state var rval = { '@id': '@id', '@language': '@language', '@literal': '@literal', '@type': '@type' }; if(ctx) { // gather keyword aliases from context var keywords = {}; for(var key in ctx) { if(ctx[key].constructor === String && ctx[key] in rval) { keywords[ctx[key]] = key; } } // overwrite keywords for(var key in keywords) { rval[key] = keywords[key]; } } return rval; }
[ "function", "(", "ctx", ")", "{", "// TODO: reduce calls to this function by caching keywords in processor", "// state", "var", "rval", "=", "{", "'@id'", ":", "'@id'", ",", "'@language'", ":", "'@language'", ",", "'@literal'", ":", "'@literal'", ",", "'@type'", ":", "'@type'", "}", ";", "if", "(", "ctx", ")", "{", "// gather keyword aliases from context", "var", "keywords", "=", "{", "}", ";", "for", "(", "var", "key", "in", "ctx", ")", "{", "if", "(", "ctx", "[", "key", "]", ".", "constructor", "===", "String", "&&", "ctx", "[", "key", "]", "in", "rval", ")", "{", "keywords", "[", "ctx", "[", "key", "]", "]", "=", "key", ";", "}", "}", "// overwrite keywords", "for", "(", "var", "key", "in", "keywords", ")", "{", "rval", "[", "key", "]", "=", "keywords", "[", "key", "]", ";", "}", "}", "return", "rval", ";", "}" ]
Gets the keywords from a context. @param ctx the context. @return the keywords.
[ "Gets", "the", "keywords", "from", "a", "context", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L2214-L2247
43,787
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(ctx, term) { var rval = null; if(term in ctx) { if(ctx[term].constructor === String) { rval = ctx[term]; } else if(ctx[term].constructor === Object && '@id' in ctx[term]) { rval = ctx[term]['@id']; } } return rval; }
javascript
function(ctx, term) { var rval = null; if(term in ctx) { if(ctx[term].constructor === String) { rval = ctx[term]; } else if(ctx[term].constructor === Object && '@id' in ctx[term]) { rval = ctx[term]['@id']; } } return rval; }
[ "function", "(", "ctx", ",", "term", ")", "{", "var", "rval", "=", "null", ";", "if", "(", "term", "in", "ctx", ")", "{", "if", "(", "ctx", "[", "term", "]", ".", "constructor", "===", "String", ")", "{", "rval", "=", "ctx", "[", "term", "]", ";", "}", "else", "if", "(", "ctx", "[", "term", "]", ".", "constructor", "===", "Object", "&&", "'@id'", "in", "ctx", "[", "term", "]", ")", "{", "rval", "=", "ctx", "[", "term", "]", "[", "'@id'", "]", ";", "}", "}", "return", "rval", ";", "}" ]
Gets the iri associated with a term. @param ctx the context. @param term the term. @return the iri or NULL.
[ "Gets", "the", "iri", "associated", "with", "a", "term", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L2257-L2272
43,788
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(ctx, iri, usedCtx) { var rval = null; // check the context for a term that could shorten the IRI // (give preference to terms over prefixes) for(var key in ctx) { // skip special context keys (start with '@') if(key.length > 0 && key[0] !== '@') { // compact to a term if(iri === _getTermIri(ctx, key)) { rval = key; if(usedCtx !== null) { usedCtx[key] = _clone(ctx[key]); } break; } } } // term not found, if term is @type, use keyword if(rval === null && iri === '@type') { rval = _getKeywords(ctx)['@type']; } // term not found, check the context for a prefix if(rval === null) { for(var key in ctx) { // skip special context keys (start with '@') if(key.length > 0 && key[0] !== '@') { // see if IRI begins with the next IRI from the context var ctxIri = _getTermIri(ctx, key); if(ctxIri !== null) { var idx = iri.indexOf(ctxIri); // compact to a prefix if(idx === 0 && iri.length > ctxIri.length) { rval = key + ':' + iri.substr(ctxIri.length); if(usedCtx !== null) { usedCtx[key] = _clone(ctx[key]); } break; } } } } } // could not compact IRI if(rval === null) { rval = iri; } return rval; }
javascript
function(ctx, iri, usedCtx) { var rval = null; // check the context for a term that could shorten the IRI // (give preference to terms over prefixes) for(var key in ctx) { // skip special context keys (start with '@') if(key.length > 0 && key[0] !== '@') { // compact to a term if(iri === _getTermIri(ctx, key)) { rval = key; if(usedCtx !== null) { usedCtx[key] = _clone(ctx[key]); } break; } } } // term not found, if term is @type, use keyword if(rval === null && iri === '@type') { rval = _getKeywords(ctx)['@type']; } // term not found, check the context for a prefix if(rval === null) { for(var key in ctx) { // skip special context keys (start with '@') if(key.length > 0 && key[0] !== '@') { // see if IRI begins with the next IRI from the context var ctxIri = _getTermIri(ctx, key); if(ctxIri !== null) { var idx = iri.indexOf(ctxIri); // compact to a prefix if(idx === 0 && iri.length > ctxIri.length) { rval = key + ':' + iri.substr(ctxIri.length); if(usedCtx !== null) { usedCtx[key] = _clone(ctx[key]); } break; } } } } } // could not compact IRI if(rval === null) { rval = iri; } return rval; }
[ "function", "(", "ctx", ",", "iri", ",", "usedCtx", ")", "{", "var", "rval", "=", "null", ";", "// check the context for a term that could shorten the IRI", "// (give preference to terms over prefixes)", "for", "(", "var", "key", "in", "ctx", ")", "{", "// skip special context keys (start with '@')", "if", "(", "key", ".", "length", ">", "0", "&&", "key", "[", "0", "]", "!==", "'@'", ")", "{", "// compact to a term", "if", "(", "iri", "===", "_getTermIri", "(", "ctx", ",", "key", ")", ")", "{", "rval", "=", "key", ";", "if", "(", "usedCtx", "!==", "null", ")", "{", "usedCtx", "[", "key", "]", "=", "_clone", "(", "ctx", "[", "key", "]", ")", ";", "}", "break", ";", "}", "}", "}", "// term not found, if term is @type, use keyword", "if", "(", "rval", "===", "null", "&&", "iri", "===", "'@type'", ")", "{", "rval", "=", "_getKeywords", "(", "ctx", ")", "[", "'@type'", "]", ";", "}", "// term not found, check the context for a prefix", "if", "(", "rval", "===", "null", ")", "{", "for", "(", "var", "key", "in", "ctx", ")", "{", "// skip special context keys (start with '@')", "if", "(", "key", ".", "length", ">", "0", "&&", "key", "[", "0", "]", "!==", "'@'", ")", "{", "// see if IRI begins with the next IRI from the context", "var", "ctxIri", "=", "_getTermIri", "(", "ctx", ",", "key", ")", ";", "if", "(", "ctxIri", "!==", "null", ")", "{", "var", "idx", "=", "iri", ".", "indexOf", "(", "ctxIri", ")", ";", "// compact to a prefix", "if", "(", "idx", "===", "0", "&&", "iri", ".", "length", ">", "ctxIri", ".", "length", ")", "{", "rval", "=", "key", "+", "':'", "+", "iri", ".", "substr", "(", "ctxIri", ".", "length", ")", ";", "if", "(", "usedCtx", "!==", "null", ")", "{", "usedCtx", "[", "key", "]", "=", "_clone", "(", "ctx", "[", "key", "]", ")", ";", "}", "break", ";", "}", "}", "}", "}", "}", "// could not compact IRI", "if", "(", "rval", "===", "null", ")", "{", "rval", "=", "iri", ";", "}", "return", "rval", ";", "}" ]
Compacts an IRI into a term or prefix if it can be. IRIs will not be compacted to relative IRIs if they match the given context's default vocabulary. @param ctx the context to use. @param iri the IRI to compact. @param usedCtx a context to update if a value was used from "ctx". @return the compacted IRI as a term or prefix or the original IRI.
[ "Compacts", "an", "IRI", "into", "a", "term", "or", "prefix", "if", "it", "can", "be", ".", "IRIs", "will", "not", "be", "compacted", "to", "relative", "IRIs", "if", "they", "match", "the", "given", "context", "s", "default", "vocabulary", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L2285-L2351
43,789
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(ctx, term, usedCtx) { var rval = term; // get JSON-LD keywords var keywords = _getKeywords(ctx); // 1. If the property has a colon, it is a prefix or an absolute IRI: var idx = term.indexOf(':'); if(idx !== -1) { // get the potential prefix var prefix = term.substr(0, idx); // expand term if prefix is in context, otherwise leave it be if(prefix in ctx) { // prefix found, expand property to absolute IRI var iri = _getTermIri(ctx, prefix); rval = iri + term.substr(idx + 1); if(usedCtx !== null) { usedCtx[prefix] = _clone(ctx[prefix]); } } } // 2. If the property is in the context, then it's a term. else if(term in ctx) { rval = _getTermIri(ctx, term); if(usedCtx !== null) { usedCtx[term] = _clone(ctx[term]); } } // 3. The property is a keyword. else { for(var key in keywords) { if(term === keywords[key]) { rval = key; break; } } } return rval; }
javascript
function(ctx, term, usedCtx) { var rval = term; // get JSON-LD keywords var keywords = _getKeywords(ctx); // 1. If the property has a colon, it is a prefix or an absolute IRI: var idx = term.indexOf(':'); if(idx !== -1) { // get the potential prefix var prefix = term.substr(0, idx); // expand term if prefix is in context, otherwise leave it be if(prefix in ctx) { // prefix found, expand property to absolute IRI var iri = _getTermIri(ctx, prefix); rval = iri + term.substr(idx + 1); if(usedCtx !== null) { usedCtx[prefix] = _clone(ctx[prefix]); } } } // 2. If the property is in the context, then it's a term. else if(term in ctx) { rval = _getTermIri(ctx, term); if(usedCtx !== null) { usedCtx[term] = _clone(ctx[term]); } } // 3. The property is a keyword. else { for(var key in keywords) { if(term === keywords[key]) { rval = key; break; } } } return rval; }
[ "function", "(", "ctx", ",", "term", ",", "usedCtx", ")", "{", "var", "rval", "=", "term", ";", "// get JSON-LD keywords", "var", "keywords", "=", "_getKeywords", "(", "ctx", ")", ";", "// 1. If the property has a colon, it is a prefix or an absolute IRI:", "var", "idx", "=", "term", ".", "indexOf", "(", "':'", ")", ";", "if", "(", "idx", "!==", "-", "1", ")", "{", "// get the potential prefix", "var", "prefix", "=", "term", ".", "substr", "(", "0", ",", "idx", ")", ";", "// expand term if prefix is in context, otherwise leave it be", "if", "(", "prefix", "in", "ctx", ")", "{", "// prefix found, expand property to absolute IRI", "var", "iri", "=", "_getTermIri", "(", "ctx", ",", "prefix", ")", ";", "rval", "=", "iri", "+", "term", ".", "substr", "(", "idx", "+", "1", ")", ";", "if", "(", "usedCtx", "!==", "null", ")", "{", "usedCtx", "[", "prefix", "]", "=", "_clone", "(", "ctx", "[", "prefix", "]", ")", ";", "}", "}", "}", "// 2. If the property is in the context, then it's a term.", "else", "if", "(", "term", "in", "ctx", ")", "{", "rval", "=", "_getTermIri", "(", "ctx", ",", "term", ")", ";", "if", "(", "usedCtx", "!==", "null", ")", "{", "usedCtx", "[", "term", "]", "=", "_clone", "(", "ctx", "[", "term", "]", ")", ";", "}", "}", "// 3. The property is a keyword.", "else", "{", "for", "(", "var", "key", "in", "keywords", ")", "{", "if", "(", "term", "===", "keywords", "[", "key", "]", ")", "{", "rval", "=", "key", ";", "break", ";", "}", "}", "}", "return", "rval", ";", "}" ]
Expands a term into an absolute IRI. The term may be a regular term, a prefix, a relative IRI, or an absolute IRI. In any case, the associated absolute IRI will be returned. @param ctx the context to use. @param term the term to expand. @param usedCtx a context to update if a value was used from "ctx". @return the expanded term as an absolute IRI.
[ "Expands", "a", "term", "into", "an", "absolute", "IRI", ".", "The", "term", "may", "be", "a", "regular", "term", "a", "prefix", "a", "relative", "IRI", "or", "an", "absolute", "IRI", ".", "In", "any", "case", "the", "associated", "absolute", "IRI", "will", "be", "returned", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L2364-L2413
43,790
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(ctx) { // sort keys var rval = {}; var keys = Object.keys(ctx).sort(); for(var k in keys) { var key = keys[k]; rval[key] = ctx[key]; } return rval; }
javascript
function(ctx) { // sort keys var rval = {}; var keys = Object.keys(ctx).sort(); for(var k in keys) { var key = keys[k]; rval[key] = ctx[key]; } return rval; }
[ "function", "(", "ctx", ")", "{", "// sort keys", "var", "rval", "=", "{", "}", ";", "var", "keys", "=", "Object", ".", "keys", "(", "ctx", ")", ".", "sort", "(", ")", ";", "for", "(", "var", "k", "in", "keys", ")", "{", "var", "key", "=", "keys", "[", "k", "]", ";", "rval", "[", "key", "]", "=", "ctx", "[", "key", "]", ";", "}", "return", "rval", ";", "}" ]
Sorts the keys in a context. @param ctx the context to sort. @return the sorted context.
[ "Sorts", "the", "keys", "in", "a", "context", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L2422-L2433
43,791
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(value) { var rval = false; // Note: A value is a subject if all of these hold true: // 1. It is an Object. // 2. It is not a literal. // 3. It has more than 1 key OR any existing key is not '@id'. if(value !== null && value.constructor === Object && !('@literal' in value)) { var keyCount = Object.keys(value).length; rval = (keyCount > 1 || !('@id' in value)); } return rval; }
javascript
function(value) { var rval = false; // Note: A value is a subject if all of these hold true: // 1. It is an Object. // 2. It is not a literal. // 3. It has more than 1 key OR any existing key is not '@id'. if(value !== null && value.constructor === Object && !('@literal' in value)) { var keyCount = Object.keys(value).length; rval = (keyCount > 1 || !('@id' in value)); } return rval; }
[ "function", "(", "value", ")", "{", "var", "rval", "=", "false", ";", "// Note: A value is a subject if all of these hold true:", "// 1. It is an Object.", "// 2. It is not a literal.", "// 3. It has more than 1 key OR any existing key is not '@id'.", "if", "(", "value", "!==", "null", "&&", "value", ".", "constructor", "===", "Object", "&&", "!", "(", "'@literal'", "in", "value", ")", ")", "{", "var", "keyCount", "=", "Object", ".", "keys", "(", "value", ")", ".", "length", ";", "rval", "=", "(", "keyCount", ">", "1", "||", "!", "(", "'@id'", "in", "value", ")", ")", ";", "}", "return", "rval", ";", "}" ]
Gets whether or not a value is a subject with properties. @param value the value to check. @return true if the value is a subject with properties, false if not.
[ "Gets", "whether", "or", "not", "a", "value", "is", "a", "subject", "with", "properties", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L2462-L2477
43,792
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(v1, v2) { var rval = 0; if(v1.constructor === Array && v2.constructor === Array) { for(var i = 0; i < v1.length && rval === 0; ++i) { rval = _compare(v1[i], v2[i]); } } else { rval = (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); } return rval; }
javascript
function(v1, v2) { var rval = 0; if(v1.constructor === Array && v2.constructor === Array) { for(var i = 0; i < v1.length && rval === 0; ++i) { rval = _compare(v1[i], v2[i]); } } else { rval = (v1 < v2 ? -1 : (v1 > v2 ? 1 : 0)); } return rval; }
[ "function", "(", "v1", ",", "v2", ")", "{", "var", "rval", "=", "0", ";", "if", "(", "v1", ".", "constructor", "===", "Array", "&&", "v2", ".", "constructor", "===", "Array", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "v1", ".", "length", "&&", "rval", "===", "0", ";", "++", "i", ")", "{", "rval", "=", "_compare", "(", "v1", "[", "i", "]", ",", "v2", "[", "i", "]", ")", ";", "}", "}", "else", "{", "rval", "=", "(", "v1", "<", "v2", "?", "-", "1", ":", "(", "v1", ">", "v2", "?", "1", ":", "0", ")", ")", ";", "}", "return", "rval", ";", "}" ]
Compares two values. @param v1 the first value. @param v2 the second value. @return -1 if v1 < v2, 0 if v1 == v2, 1 if v1 > v2.
[ "Compares", "two", "values", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L3370-L3387
43,793
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(o1, o2, key) { var rval = 0; if(key in o1) { if(key in o2) { rval = _compare(o1[key], o2[key]); } else { rval = -1; } } else if(key in o2) { rval = 1; } return rval; }
javascript
function(o1, o2, key) { var rval = 0; if(key in o1) { if(key in o2) { rval = _compare(o1[key], o2[key]); } else { rval = -1; } } else if(key in o2) { rval = 1; } return rval; }
[ "function", "(", "o1", ",", "o2", ",", "key", ")", "{", "var", "rval", "=", "0", ";", "if", "(", "key", "in", "o1", ")", "{", "if", "(", "key", "in", "o2", ")", "{", "rval", "=", "_compare", "(", "o1", "[", "key", "]", ",", "o2", "[", "key", "]", ")", ";", "}", "else", "{", "rval", "=", "-", "1", ";", "}", "}", "else", "if", "(", "key", "in", "o2", ")", "{", "rval", "=", "1", ";", "}", "return", "rval", ";", "}" ]
Compares two keys in an object. If the key exists in one object and not the other, the object with the key is less. If the key exists in both objects, then the one with the lesser value is less. @param o1 the first object. @param o2 the second object. @param key the key. @return -1 if o1 < o2, 0 if o1 == o2, 1 if o1 > o2.
[ "Compares", "two", "keys", "in", "an", "object", ".", "If", "the", "key", "exists", "in", "one", "object", "and", "not", "the", "other", "the", "object", "with", "the", "key", "is", "less", ".", "If", "the", "key", "exists", "in", "both", "objects", "then", "the", "one", "with", "the", "lesser", "value", "is", "less", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L3400-L3419
43,794
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(o1, o2) { var rval = 0; if(o1.constructor === String) { if(o2.constructor !== String) { rval = -1; } else { rval = _compare(o1, o2); } } else if(o2.constructor === String) { rval = 1; } else { rval = _compareObjectKeys(o1, o2, '@literal'); if(rval === 0) { if('@literal' in o1) { rval = _compareObjectKeys(o1, o2, '@type'); if(rval === 0) { rval = _compareObjectKeys(o1, o2, '@language'); } } // both are '@id' objects else { rval = _compare(o1['@id'], o2['@id']); } } } return rval; }
javascript
function(o1, o2) { var rval = 0; if(o1.constructor === String) { if(o2.constructor !== String) { rval = -1; } else { rval = _compare(o1, o2); } } else if(o2.constructor === String) { rval = 1; } else { rval = _compareObjectKeys(o1, o2, '@literal'); if(rval === 0) { if('@literal' in o1) { rval = _compareObjectKeys(o1, o2, '@type'); if(rval === 0) { rval = _compareObjectKeys(o1, o2, '@language'); } } // both are '@id' objects else { rval = _compare(o1['@id'], o2['@id']); } } } return rval; }
[ "function", "(", "o1", ",", "o2", ")", "{", "var", "rval", "=", "0", ";", "if", "(", "o1", ".", "constructor", "===", "String", ")", "{", "if", "(", "o2", ".", "constructor", "!==", "String", ")", "{", "rval", "=", "-", "1", ";", "}", "else", "{", "rval", "=", "_compare", "(", "o1", ",", "o2", ")", ";", "}", "}", "else", "if", "(", "o2", ".", "constructor", "===", "String", ")", "{", "rval", "=", "1", ";", "}", "else", "{", "rval", "=", "_compareObjectKeys", "(", "o1", ",", "o2", ",", "'@literal'", ")", ";", "if", "(", "rval", "===", "0", ")", "{", "if", "(", "'@literal'", "in", "o1", ")", "{", "rval", "=", "_compareObjectKeys", "(", "o1", ",", "o2", ",", "'@type'", ")", ";", "if", "(", "rval", "===", "0", ")", "{", "rval", "=", "_compareObjectKeys", "(", "o1", ",", "o2", ",", "'@language'", ")", ";", "}", "}", "// both are '@id' objects", "else", "{", "rval", "=", "_compare", "(", "o1", "[", "'@id'", "]", ",", "o2", "[", "'@id'", "]", ")", ";", "}", "}", "}", "return", "rval", ";", "}" ]
Compares two object values. @param o1 the first object. @param o2 the second object. @return -1 if o1 < o2, 0 if o1 == o2, 1 if o1 > o2.
[ "Compares", "two", "object", "values", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L3429-L3470
43,795
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(a, b) { var rval = 0; /* 3. For each property, compare sorted object values. 3.1. The bnode with fewer objects is first. 3.2. For each object value, compare only literals and non-bnodes. 3.2.1. The bnode with fewer non-bnodes is first. 3.2.2. The bnode with a string object is first. 3.2.3. The bnode with the alphabetically-first string is first. 3.2.4. The bnode with a @literal is first. 3.2.5. The bnode with the alphabetically-first @literal is first. 3.2.6. The bnode with the alphabetically-first @type is first. 3.2.7. The bnode with a @language is first. 3.2.8. The bnode with the alphabetically-first @language is first. 3.2.9. The bnode with the alphabetically-first @id is first. */ for(var p in a) { // skip IDs (IRIs) if(p !== '@id') { // step #3.1 var lenA = (a[p].constructor === Array) ? a[p].length : 1; var lenB = (b[p].constructor === Array) ? b[p].length : 1; rval = _compare(lenA, lenB); // step #3.2.1 if(rval === 0) { // normalize objects to an array var objsA = a[p]; var objsB = b[p]; if(objsA.constructor !== Array) { objsA = [objsA]; objsB = [objsB]; } // compare non-bnodes (remove bnodes from comparison) objsA = objsA.filter(function(e) {return !_isNamedBlankNode(e);}); objsB = objsB.filter(function(e) {return !_isNamedBlankNode(e);}); rval = _compare(objsA.length, objsB.length); } // steps #3.2.2-3.2.9 if(rval === 0) { objsA.sort(_compareObjects); objsB.sort(_compareObjects); for(var i = 0; i < objsA.length && rval === 0; ++i) { rval = _compareObjects(objsA[i], objsB[i]); } } if(rval !== 0) { break; } } } return rval; }
javascript
function(a, b) { var rval = 0; /* 3. For each property, compare sorted object values. 3.1. The bnode with fewer objects is first. 3.2. For each object value, compare only literals and non-bnodes. 3.2.1. The bnode with fewer non-bnodes is first. 3.2.2. The bnode with a string object is first. 3.2.3. The bnode with the alphabetically-first string is first. 3.2.4. The bnode with a @literal is first. 3.2.5. The bnode with the alphabetically-first @literal is first. 3.2.6. The bnode with the alphabetically-first @type is first. 3.2.7. The bnode with a @language is first. 3.2.8. The bnode with the alphabetically-first @language is first. 3.2.9. The bnode with the alphabetically-first @id is first. */ for(var p in a) { // skip IDs (IRIs) if(p !== '@id') { // step #3.1 var lenA = (a[p].constructor === Array) ? a[p].length : 1; var lenB = (b[p].constructor === Array) ? b[p].length : 1; rval = _compare(lenA, lenB); // step #3.2.1 if(rval === 0) { // normalize objects to an array var objsA = a[p]; var objsB = b[p]; if(objsA.constructor !== Array) { objsA = [objsA]; objsB = [objsB]; } // compare non-bnodes (remove bnodes from comparison) objsA = objsA.filter(function(e) {return !_isNamedBlankNode(e);}); objsB = objsB.filter(function(e) {return !_isNamedBlankNode(e);}); rval = _compare(objsA.length, objsB.length); } // steps #3.2.2-3.2.9 if(rval === 0) { objsA.sort(_compareObjects); objsB.sort(_compareObjects); for(var i = 0; i < objsA.length && rval === 0; ++i) { rval = _compareObjects(objsA[i], objsB[i]); } } if(rval !== 0) { break; } } } return rval; }
[ "function", "(", "a", ",", "b", ")", "{", "var", "rval", "=", "0", ";", "/*\n 3. For each property, compare sorted object values.\n 3.1. The bnode with fewer objects is first.\n 3.2. For each object value, compare only literals and non-bnodes.\n 3.2.1. The bnode with fewer non-bnodes is first.\n 3.2.2. The bnode with a string object is first.\n 3.2.3. The bnode with the alphabetically-first string is first.\n 3.2.4. The bnode with a @literal is first.\n 3.2.5. The bnode with the alphabetically-first @literal is first.\n 3.2.6. The bnode with the alphabetically-first @type is first.\n 3.2.7. The bnode with a @language is first.\n 3.2.8. The bnode with the alphabetically-first @language is first.\n 3.2.9. The bnode with the alphabetically-first @id is first.\n */", "for", "(", "var", "p", "in", "a", ")", "{", "// skip IDs (IRIs)", "if", "(", "p", "!==", "'@id'", ")", "{", "// step #3.1", "var", "lenA", "=", "(", "a", "[", "p", "]", ".", "constructor", "===", "Array", ")", "?", "a", "[", "p", "]", ".", "length", ":", "1", ";", "var", "lenB", "=", "(", "b", "[", "p", "]", ".", "constructor", "===", "Array", ")", "?", "b", "[", "p", "]", ".", "length", ":", "1", ";", "rval", "=", "_compare", "(", "lenA", ",", "lenB", ")", ";", "// step #3.2.1", "if", "(", "rval", "===", "0", ")", "{", "// normalize objects to an array", "var", "objsA", "=", "a", "[", "p", "]", ";", "var", "objsB", "=", "b", "[", "p", "]", ";", "if", "(", "objsA", ".", "constructor", "!==", "Array", ")", "{", "objsA", "=", "[", "objsA", "]", ";", "objsB", "=", "[", "objsB", "]", ";", "}", "// compare non-bnodes (remove bnodes from comparison)", "objsA", "=", "objsA", ".", "filter", "(", "function", "(", "e", ")", "{", "return", "!", "_isNamedBlankNode", "(", "e", ")", ";", "}", ")", ";", "objsB", "=", "objsB", ".", "filter", "(", "function", "(", "e", ")", "{", "return", "!", "_isNamedBlankNode", "(", "e", ")", ";", "}", ")", ";", "rval", "=", "_compare", "(", "objsA", ".", "length", ",", "objsB", ".", "length", ")", ";", "}", "// steps #3.2.2-3.2.9", "if", "(", "rval", "===", "0", ")", "{", "objsA", ".", "sort", "(", "_compareObjects", ")", ";", "objsB", ".", "sort", "(", "_compareObjects", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "objsA", ".", "length", "&&", "rval", "===", "0", ";", "++", "i", ")", "{", "rval", "=", "_compareObjects", "(", "objsA", "[", "i", "]", ",", "objsB", "[", "i", "]", ")", ";", "}", "}", "if", "(", "rval", "!==", "0", ")", "{", "break", ";", "}", "}", "}", "return", "rval", ";", "}" ]
Compares the object values between two bnodes. @param a the first bnode. @param b the second bnode. @return -1 if a < b, 0 if a == b, 1 if a > b.
[ "Compares", "the", "object", "values", "between", "two", "bnodes", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L3480-L3546
43,796
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(prefix) { var count = -1; var ng = { next: function() { ++count; return ng.current(); }, current: function() { return '_:' + prefix + count; }, inNamespace: function(iri) { return iri.indexOf('_:' + prefix) === 0; } }; return ng; }
javascript
function(prefix) { var count = -1; var ng = { next: function() { ++count; return ng.current(); }, current: function() { return '_:' + prefix + count; }, inNamespace: function(iri) { return iri.indexOf('_:' + prefix) === 0; } }; return ng; }
[ "function", "(", "prefix", ")", "{", "var", "count", "=", "-", "1", ";", "var", "ng", "=", "{", "next", ":", "function", "(", ")", "{", "++", "count", ";", "return", "ng", ".", "current", "(", ")", ";", "}", ",", "current", ":", "function", "(", ")", "{", "return", "'_:'", "+", "prefix", "+", "count", ";", "}", ",", "inNamespace", ":", "function", "(", "iri", ")", "{", "return", "iri", ".", "indexOf", "(", "'_:'", "+", "prefix", ")", "===", "0", ";", "}", "}", ";", "return", "ng", ";", "}" ]
Creates a blank node name generator using the given prefix for the blank nodes. @param prefix the prefix to use. @return the blank node name generator.
[ "Creates", "a", "blank", "node", "name", "generator", "using", "the", "given", "prefix", "for", "the", "blank", "nodes", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L3556-L3575
43,797
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(parent, parentProperty, value, subjects) { var flattened = null; if(value === null) { // drop null values } else if(value.constructor === Array) { // list of objects or a disjoint graph for(var i in value) { _flatten(parent, parentProperty, value[i], subjects); } } else if(value.constructor === Object) { // already-expanded value or special-case reference-only @type if('@literal' in value || parentProperty === '@type') { flattened = _clone(value); } // graph literal/disjoint graph else if(value['@id'].constructor === Array) { // cannot flatten embedded graph literals if(parent !== null) { throw { message: 'Embedded graph literals cannot be flattened.' }; } // top-level graph literal for(var idx in value['@id']) { _flatten(parent, parentProperty, value['@id'][idx], subjects); } } // regular subject else { // create or fetch existing subject var subject; if(value['@id'] in subjects) { // FIXME: '@id' might be a graph literal (as {}) subject = subjects[value['@id']]; } else { // FIXME: '@id' might be a graph literal (as {}) subject = {'@id': value['@id']}; subjects[value['@id']] = subject; } flattened = {'@id': subject['@id']}; // flatten embeds for(var key in value) { var v = value[key]; // drop null values, skip @id (it is already set above) if(v !== null && key !== '@id') { if(key in subject) { if(subject[key].constructor !== Array) { subject[key] = [subject[key]]; } } else { subject[key] = []; } _flatten(subject[key], key, v, subjects); if(subject[key].length === 1) { // convert subject[key] to object if it has only 1 subject[key] = subject[key][0]; } } } } } // string value else { flattened = value; } // add flattened value to parent if(flattened !== null && parent !== null) { if(parent.constructor === Array) { // do not add duplicate IRIs for the same property var duplicate = false; if(flattened.constructor === Object && '@id' in flattened) { duplicate = (parent.filter(function(e) { return (e.constructor === Object && '@id' in e && e['@id'] === flattened['@id']); }).length > 0); } if(!duplicate) { parent.push(flattened); } } else { parent[parentProperty] = flattened; } } }
javascript
function(parent, parentProperty, value, subjects) { var flattened = null; if(value === null) { // drop null values } else if(value.constructor === Array) { // list of objects or a disjoint graph for(var i in value) { _flatten(parent, parentProperty, value[i], subjects); } } else if(value.constructor === Object) { // already-expanded value or special-case reference-only @type if('@literal' in value || parentProperty === '@type') { flattened = _clone(value); } // graph literal/disjoint graph else if(value['@id'].constructor === Array) { // cannot flatten embedded graph literals if(parent !== null) { throw { message: 'Embedded graph literals cannot be flattened.' }; } // top-level graph literal for(var idx in value['@id']) { _flatten(parent, parentProperty, value['@id'][idx], subjects); } } // regular subject else { // create or fetch existing subject var subject; if(value['@id'] in subjects) { // FIXME: '@id' might be a graph literal (as {}) subject = subjects[value['@id']]; } else { // FIXME: '@id' might be a graph literal (as {}) subject = {'@id': value['@id']}; subjects[value['@id']] = subject; } flattened = {'@id': subject['@id']}; // flatten embeds for(var key in value) { var v = value[key]; // drop null values, skip @id (it is already set above) if(v !== null && key !== '@id') { if(key in subject) { if(subject[key].constructor !== Array) { subject[key] = [subject[key]]; } } else { subject[key] = []; } _flatten(subject[key], key, v, subjects); if(subject[key].length === 1) { // convert subject[key] to object if it has only 1 subject[key] = subject[key][0]; } } } } } // string value else { flattened = value; } // add flattened value to parent if(flattened !== null && parent !== null) { if(parent.constructor === Array) { // do not add duplicate IRIs for the same property var duplicate = false; if(flattened.constructor === Object && '@id' in flattened) { duplicate = (parent.filter(function(e) { return (e.constructor === Object && '@id' in e && e['@id'] === flattened['@id']); }).length > 0); } if(!duplicate) { parent.push(flattened); } } else { parent[parentProperty] = flattened; } } }
[ "function", "(", "parent", ",", "parentProperty", ",", "value", ",", "subjects", ")", "{", "var", "flattened", "=", "null", ";", "if", "(", "value", "===", "null", ")", "{", "// drop null values", "}", "else", "if", "(", "value", ".", "constructor", "===", "Array", ")", "{", "// list of objects or a disjoint graph", "for", "(", "var", "i", "in", "value", ")", "{", "_flatten", "(", "parent", ",", "parentProperty", ",", "value", "[", "i", "]", ",", "subjects", ")", ";", "}", "}", "else", "if", "(", "value", ".", "constructor", "===", "Object", ")", "{", "// already-expanded value or special-case reference-only @type", "if", "(", "'@literal'", "in", "value", "||", "parentProperty", "===", "'@type'", ")", "{", "flattened", "=", "_clone", "(", "value", ")", ";", "}", "// graph literal/disjoint graph", "else", "if", "(", "value", "[", "'@id'", "]", ".", "constructor", "===", "Array", ")", "{", "// cannot flatten embedded graph literals", "if", "(", "parent", "!==", "null", ")", "{", "throw", "{", "message", ":", "'Embedded graph literals cannot be flattened.'", "}", ";", "}", "// top-level graph literal", "for", "(", "var", "idx", "in", "value", "[", "'@id'", "]", ")", "{", "_flatten", "(", "parent", ",", "parentProperty", ",", "value", "[", "'@id'", "]", "[", "idx", "]", ",", "subjects", ")", ";", "}", "}", "// regular subject", "else", "{", "// create or fetch existing subject", "var", "subject", ";", "if", "(", "value", "[", "'@id'", "]", "in", "subjects", ")", "{", "// FIXME: '@id' might be a graph literal (as {})", "subject", "=", "subjects", "[", "value", "[", "'@id'", "]", "]", ";", "}", "else", "{", "// FIXME: '@id' might be a graph literal (as {})", "subject", "=", "{", "'@id'", ":", "value", "[", "'@id'", "]", "}", ";", "subjects", "[", "value", "[", "'@id'", "]", "]", "=", "subject", ";", "}", "flattened", "=", "{", "'@id'", ":", "subject", "[", "'@id'", "]", "}", ";", "// flatten embeds", "for", "(", "var", "key", "in", "value", ")", "{", "var", "v", "=", "value", "[", "key", "]", ";", "// drop null values, skip @id (it is already set above)", "if", "(", "v", "!==", "null", "&&", "key", "!==", "'@id'", ")", "{", "if", "(", "key", "in", "subject", ")", "{", "if", "(", "subject", "[", "key", "]", ".", "constructor", "!==", "Array", ")", "{", "subject", "[", "key", "]", "=", "[", "subject", "[", "key", "]", "]", ";", "}", "}", "else", "{", "subject", "[", "key", "]", "=", "[", "]", ";", "}", "_flatten", "(", "subject", "[", "key", "]", ",", "key", ",", "v", ",", "subjects", ")", ";", "if", "(", "subject", "[", "key", "]", ".", "length", "===", "1", ")", "{", "// convert subject[key] to object if it has only 1", "subject", "[", "key", "]", "=", "subject", "[", "key", "]", "[", "0", "]", ";", "}", "}", "}", "}", "}", "// string value", "else", "{", "flattened", "=", "value", ";", "}", "// add flattened value to parent", "if", "(", "flattened", "!==", "null", "&&", "parent", "!==", "null", ")", "{", "if", "(", "parent", ".", "constructor", "===", "Array", ")", "{", "// do not add duplicate IRIs for the same property", "var", "duplicate", "=", "false", ";", "if", "(", "flattened", ".", "constructor", "===", "Object", "&&", "'@id'", "in", "flattened", ")", "{", "duplicate", "=", "(", "parent", ".", "filter", "(", "function", "(", "e", ")", "{", "return", "(", "e", ".", "constructor", "===", "Object", "&&", "'@id'", "in", "e", "&&", "e", "[", "'@id'", "]", "===", "flattened", "[", "'@id'", "]", ")", ";", "}", ")", ".", "length", ">", "0", ")", ";", "}", "if", "(", "!", "duplicate", ")", "{", "parent", ".", "push", "(", "flattened", ")", ";", "}", "}", "else", "{", "parent", "[", "parentProperty", "]", "=", "flattened", ";", "}", "}", "}" ]
Flattens the given value into a map of unique subjects. It is assumed that all blank nodes have been uniquely named before this call. Array values for properties will be sorted. @param parent the value's parent, NULL for none. @param parentProperty the property relating the value to the parent. @param value the value to flatten. @param subjects the map of subjects to write to.
[ "Flattens", "the", "given", "value", "into", "a", "map", "of", "unique", "subjects", ".", "It", "is", "assumed", "that", "all", "blank", "nodes", "have", "been", "uniquely", "named", "before", "this", "call", ".", "Array", "values", "for", "properties", "will", "be", "sorted", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L3637-L3756
43,798
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(b) { var rval = ''; var first = true; for(var p in b) { if(p !== '@id') { if(first) { first = false; } else { rval += '|'; } // property rval += '<' + p + '>'; // object(s) var objs = (b[p].constructor === Array) ? b[p] : [b[p]]; for(var oi in objs) { var o = objs[oi]; if(o.constructor === Object) { // ID (IRI) if('@id' in o) { if(_isBlankNodeIri(o['@id'])) { rval += '_:'; } else { rval += '<' + o['@id'] + '>'; } } // literal else { rval += '"' + o['@literal'] + '"'; // type literal if('@type' in o) { rval += '^^<' + o['@type'] + '>'; } // language literal else if('@language' in o) { rval += '@' + o['@language']; } } } // plain literal else { rval += '"' + o + '"'; } } } } return rval; }
javascript
function(b) { var rval = ''; var first = true; for(var p in b) { if(p !== '@id') { if(first) { first = false; } else { rval += '|'; } // property rval += '<' + p + '>'; // object(s) var objs = (b[p].constructor === Array) ? b[p] : [b[p]]; for(var oi in objs) { var o = objs[oi]; if(o.constructor === Object) { // ID (IRI) if('@id' in o) { if(_isBlankNodeIri(o['@id'])) { rval += '_:'; } else { rval += '<' + o['@id'] + '>'; } } // literal else { rval += '"' + o['@literal'] + '"'; // type literal if('@type' in o) { rval += '^^<' + o['@type'] + '>'; } // language literal else if('@language' in o) { rval += '@' + o['@language']; } } } // plain literal else { rval += '"' + o + '"'; } } } } return rval; }
[ "function", "(", "b", ")", "{", "var", "rval", "=", "''", ";", "var", "first", "=", "true", ";", "for", "(", "var", "p", "in", "b", ")", "{", "if", "(", "p", "!==", "'@id'", ")", "{", "if", "(", "first", ")", "{", "first", "=", "false", ";", "}", "else", "{", "rval", "+=", "'|'", ";", "}", "// property", "rval", "+=", "'<'", "+", "p", "+", "'>'", ";", "// object(s)", "var", "objs", "=", "(", "b", "[", "p", "]", ".", "constructor", "===", "Array", ")", "?", "b", "[", "p", "]", ":", "[", "b", "[", "p", "]", "]", ";", "for", "(", "var", "oi", "in", "objs", ")", "{", "var", "o", "=", "objs", "[", "oi", "]", ";", "if", "(", "o", ".", "constructor", "===", "Object", ")", "{", "// ID (IRI)", "if", "(", "'@id'", "in", "o", ")", "{", "if", "(", "_isBlankNodeIri", "(", "o", "[", "'@id'", "]", ")", ")", "{", "rval", "+=", "'_:'", ";", "}", "else", "{", "rval", "+=", "'<'", "+", "o", "[", "'@id'", "]", "+", "'>'", ";", "}", "}", "// literal", "else", "{", "rval", "+=", "'\"'", "+", "o", "[", "'@literal'", "]", "+", "'\"'", ";", "// type literal", "if", "(", "'@type'", "in", "o", ")", "{", "rval", "+=", "'^^<'", "+", "o", "[", "'@type'", "]", "+", "'>'", ";", "}", "// language literal", "else", "if", "(", "'@language'", "in", "o", ")", "{", "rval", "+=", "'@'", "+", "o", "[", "'@language'", "]", ";", "}", "}", "}", "// plain literal", "else", "{", "rval", "+=", "'\"'", "+", "o", "+", "'\"'", ";", "}", "}", "}", "}", "return", "rval", ";", "}" ]
Serializes the properties of the given bnode for its relation serialization. @param b the blank node. @return the serialized properties.
[ "Serializes", "the", "properties", "of", "the", "given", "bnode", "for", "its", "relation", "serialization", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L4088-L4155
43,799
aaaristo/grunt-html-builder
tasks/rdfstore/index.js
function(input, frame) { var rval = false; // check if type(s) are specified in frame and input var type = '@type'; if('@type' in frame && input.constructor === Object && type in input) { var tmp = (input[type].constructor === Array) ? input[type] : [input[type]]; var types = (frame[type].constructor === Array) ? frame[type] : [frame[type]]; for(var t = 0; t < types.length && !rval; ++t) { type = types[t]; for(var i in tmp) { if(tmp[i] === type) { rval = true; break; } } } } return rval; }
javascript
function(input, frame) { var rval = false; // check if type(s) are specified in frame and input var type = '@type'; if('@type' in frame && input.constructor === Object && type in input) { var tmp = (input[type].constructor === Array) ? input[type] : [input[type]]; var types = (frame[type].constructor === Array) ? frame[type] : [frame[type]]; for(var t = 0; t < types.length && !rval; ++t) { type = types[t]; for(var i in tmp) { if(tmp[i] === type) { rval = true; break; } } } } return rval; }
[ "function", "(", "input", ",", "frame", ")", "{", "var", "rval", "=", "false", ";", "// check if type(s) are specified in frame and input", "var", "type", "=", "'@type'", ";", "if", "(", "'@type'", "in", "frame", "&&", "input", ".", "constructor", "===", "Object", "&&", "type", "in", "input", ")", "{", "var", "tmp", "=", "(", "input", "[", "type", "]", ".", "constructor", "===", "Array", ")", "?", "input", "[", "type", "]", ":", "[", "input", "[", "type", "]", "]", ";", "var", "types", "=", "(", "frame", "[", "type", "]", ".", "constructor", "===", "Array", ")", "?", "frame", "[", "type", "]", ":", "[", "frame", "[", "type", "]", "]", ";", "for", "(", "var", "t", "=", "0", ";", "t", "<", "types", ".", "length", "&&", "!", "rval", ";", "++", "t", ")", "{", "type", "=", "types", "[", "t", "]", ";", "for", "(", "var", "i", "in", "tmp", ")", "{", "if", "(", "tmp", "[", "i", "]", "===", "type", ")", "{", "rval", "=", "true", ";", "break", ";", "}", "}", "}", "}", "return", "rval", ";", "}" ]
Returns true if the given input is a subject and has one of the given types in the given frame. @param input the input. @param frame the frame with types to look for. @return true if the input has one of the given types.
[ "Returns", "true", "if", "the", "given", "input", "is", "a", "subject", "and", "has", "one", "of", "the", "given", "types", "in", "the", "given", "frame", "." ]
9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1
https://github.com/aaaristo/grunt-html-builder/blob/9ab9ffb5c3d3395b7b097d906ea20c1e4fd09da1/tasks/rdfstore/index.js#L4716-L4744