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
16,500
bitovi/syn
src/drag.js
function(dataFlavor){ for (var i = 0; i < this.data.length; i++){ var tempdata = this.data[i]; if (tempdata.dataFlavor === dataFlavor){ return tempdata.val; } } }
javascript
function(dataFlavor){ for (var i = 0; i < this.data.length; i++){ var tempdata = this.data[i]; if (tempdata.dataFlavor === dataFlavor){ return tempdata.val; } } }
[ "function", "(", "dataFlavor", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "data", ".", "length", ";", "i", "++", ")", "{", "var", "tempdata", "=", "this", ".", "data", "[", "i", "]", ";", "if", "(", "tempdata", ".", "dataFlavor", "===", "dataFlavor", ")", "{", "return", "tempdata", ".", "val", ";", "}", "}", "}" ]
getData fetches the dragValue based on the input dataFlavor provided.
[ "getData", "fetches", "the", "dragValue", "based", "on", "the", "input", "dataFlavor", "provided", "." ]
f04e87b18bee9b4308838db04682d3ce2b98afaa
https://github.com/bitovi/syn/blob/f04e87b18bee9b4308838db04682d3ce2b98afaa/src/drag.js#L184-L191
16,501
bitovi/syn
src/synthetic.js
function (el, type) { while (el && el.nodeName.toLowerCase() !== type.toLowerCase()) { el = el.parentNode; } return el; }
javascript
function (el, type) { while (el && el.nodeName.toLowerCase() !== type.toLowerCase()) { el = el.parentNode; } return el; }
[ "function", "(", "el", ",", "type", ")", "{", "while", "(", "el", "&&", "el", ".", "nodeName", ".", "toLowerCase", "(", ")", "!==", "type", ".", "toLowerCase", "(", ")", ")", "{", "el", "=", "el", ".", "parentNode", ";", "}", "return", "el", ";", "}" ]
Returns the closest element of a particular type. @hide @param {Object} el @param {Object} type
[ "Returns", "the", "closest", "element", "of", "a", "particular", "type", "." ]
f04e87b18bee9b4308838db04682d3ce2b98afaa
https://github.com/bitovi/syn/blob/f04e87b18bee9b4308838db04682d3ce2b98afaa/src/synthetic.js#L302-L307
16,502
bitovi/syn
src/synthetic.js
function (el, func) { var res; while (el && res !== false) { res = func(el); el = el.parentNode; } return el; }
javascript
function (el, func) { var res; while (el && res !== false) { res = func(el); el = el.parentNode; } return el; }
[ "function", "(", "el", ",", "func", ")", "{", "var", "res", ";", "while", "(", "el", "&&", "res", "!==", "false", ")", "{", "res", "=", "func", "(", "el", ")", ";", "el", "=", "el", ".", "parentNode", ";", "}", "return", "el", ";", "}" ]
Calls a function on the element and all parents of the element until the function returns false. @hide @param {Object} el @param {Object} func
[ "Calls", "a", "function", "on", "the", "element", "and", "all", "parents", "of", "the", "element", "until", "the", "function", "returns", "false", "." ]
f04e87b18bee9b4308838db04682d3ce2b98afaa
https://github.com/bitovi/syn/blob/f04e87b18bee9b4308838db04682d3ce2b98afaa/src/synthetic.js#L337-L344
16,503
bitovi/syn
src/synthetic.js
function (elem) { var attributeNode; // IE8 Standards doesn't like this on some elements if (elem.getAttributeNode) { attributeNode = elem.getAttributeNode("tabIndex"); } return this.focusable.test(elem.nodeName) || (attributeNode && attributeNode.specified) && syn.isVisible(elem); }
javascript
function (elem) { var attributeNode; // IE8 Standards doesn't like this on some elements if (elem.getAttributeNode) { attributeNode = elem.getAttributeNode("tabIndex"); } return this.focusable.test(elem.nodeName) || (attributeNode && attributeNode.specified) && syn.isVisible(elem); }
[ "function", "(", "elem", ")", "{", "var", "attributeNode", ";", "// IE8 Standards doesn't like this on some elements", "if", "(", "elem", ".", "getAttributeNode", ")", "{", "attributeNode", "=", "elem", ".", "getAttributeNode", "(", "\"tabIndex\"", ")", ";", "}", "return", "this", ".", "focusable", ".", "test", "(", "elem", ".", "nodeName", ")", "||", "(", "attributeNode", "&&", "attributeNode", ".", "specified", ")", "&&", "syn", ".", "isVisible", "(", "elem", ")", ";", "}" ]
Returns if an element is focusable @hide @param {Object} elem
[ "Returns", "if", "an", "element", "is", "focusable" ]
f04e87b18bee9b4308838db04682d3ce2b98afaa
https://github.com/bitovi/syn/blob/f04e87b18bee9b4308838db04682d3ce2b98afaa/src/synthetic.js#L352-L363
16,504
bitovi/syn
src/synthetic.js
function (elem) { var attributeNode = elem.getAttributeNode("tabIndex"); return attributeNode && attributeNode.specified && (parseInt(elem.getAttribute('tabIndex')) || 0); }
javascript
function (elem) { var attributeNode = elem.getAttributeNode("tabIndex"); return attributeNode && attributeNode.specified && (parseInt(elem.getAttribute('tabIndex')) || 0); }
[ "function", "(", "elem", ")", "{", "var", "attributeNode", "=", "elem", ".", "getAttributeNode", "(", "\"tabIndex\"", ")", ";", "return", "attributeNode", "&&", "attributeNode", ".", "specified", "&&", "(", "parseInt", "(", "elem", ".", "getAttribute", "(", "'tabIndex'", ")", ")", "||", "0", ")", ";", "}" ]
Gets the tabIndex as a number or null @hide @param {Object} elem
[ "Gets", "the", "tabIndex", "as", "a", "number", "or", "null" ]
f04e87b18bee9b4308838db04682d3ce2b98afaa
https://github.com/bitovi/syn/blob/f04e87b18bee9b4308838db04682d3ce2b98afaa/src/synthetic.js#L377-L380
16,505
marlove/react-native-geocoding
Geocoder.js
toQueryParams
function toQueryParams(object){ return Object.keys(object) .filter(key => !!object[key]) .map(key => key + "=" + encodeURIComponent(object[key])) .join("&") }
javascript
function toQueryParams(object){ return Object.keys(object) .filter(key => !!object[key]) .map(key => key + "=" + encodeURIComponent(object[key])) .join("&") }
[ "function", "toQueryParams", "(", "object", ")", "{", "return", "Object", ".", "keys", "(", "object", ")", ".", "filter", "(", "key", "=>", "!", "!", "object", "[", "key", "]", ")", ".", "map", "(", "key", "=>", "key", "+", "\"=\"", "+", "encodeURIComponent", "(", "object", "[", "key", "]", ")", ")", ".", "join", "(", "\"&\"", ")", "}" ]
Convert an object into query parameters. @param {Object} object Object to convert. @returns {string} Encoded query parameters.
[ "Convert", "an", "object", "into", "query", "parameters", "." ]
90433d23ffd4a11d50bf8cc2f6852f8c4521a3b2
https://github.com/marlove/react-native-geocoding/blob/90433d23ffd4a11d50bf8cc2f6852f8c4521a3b2/Geocoder.js#L192-L197
16,506
benbaran/adal-angular4
gulpfile.js
copy
function copy(cb) { gulp.src(['adal-angular.d.ts']).pipe(gulp.dest('./dist/')); console.log('adal-angular.d.ts Copied to Dist Directory'); gulp.src(['README.md']).pipe(gulp.dest('./dist/')); console.log('README.md Copied to Dist Directory'); cb(); }
javascript
function copy(cb) { gulp.src(['adal-angular.d.ts']).pipe(gulp.dest('./dist/')); console.log('adal-angular.d.ts Copied to Dist Directory'); gulp.src(['README.md']).pipe(gulp.dest('./dist/')); console.log('README.md Copied to Dist Directory'); cb(); }
[ "function", "copy", "(", "cb", ")", "{", "gulp", ".", "src", "(", "[", "'adal-angular.d.ts'", "]", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "'./dist/'", ")", ")", ";", "console", ".", "log", "(", "'adal-angular.d.ts Copied to Dist Directory'", ")", ";", "gulp", ".", "src", "(", "[", "'README.md'", "]", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "'./dist/'", ")", ")", ";", "console", ".", "log", "(", "'README.md Copied to Dist Directory'", ")", ";", "cb", "(", ")", ";", "}" ]
4. include type definition file for adal-angular
[ "4", ".", "include", "type", "definition", "file", "for", "adal", "-", "angular" ]
72794492c6ff3f2be0b96d9394126e53c8e45b5a
https://github.com/benbaran/adal-angular4/blob/72794492c6ff3f2be0b96d9394126e53c8e45b5a/gulpfile.js#L44-L52
16,507
benbaran/adal-angular4
gulpfile.js
replace_d
function replace_d(cb) { gulp.src('./dist/adal.service.d.ts') .pipe(replace('../adal-angular.d.ts', './adal-angular.d.ts')) .pipe(gulp.dest('./dist/')); console.log('adal.service.d.ts Path Updated'); cb(); }
javascript
function replace_d(cb) { gulp.src('./dist/adal.service.d.ts') .pipe(replace('../adal-angular.d.ts', './adal-angular.d.ts')) .pipe(gulp.dest('./dist/')); console.log('adal.service.d.ts Path Updated'); cb(); }
[ "function", "replace_d", "(", "cb", ")", "{", "gulp", ".", "src", "(", "'./dist/adal.service.d.ts'", ")", ".", "pipe", "(", "replace", "(", "'../adal-angular.d.ts'", ",", "'./adal-angular.d.ts'", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "'./dist/'", ")", ")", ";", "console", ".", "log", "(", "'adal.service.d.ts Path Updated'", ")", ";", "cb", "(", ")", ";", "}" ]
5. rewrite type definition file path for adal-angular in adal.service.d.ts
[ "5", ".", "rewrite", "type", "definition", "file", "path", "for", "adal", "-", "angular", "in", "adal", ".", "service", ".", "d", ".", "ts" ]
72794492c6ff3f2be0b96d9394126e53c8e45b5a
https://github.com/benbaran/adal-angular4/blob/72794492c6ff3f2be0b96d9394126e53c8e45b5a/gulpfile.js#L55-L61
16,508
benbaran/adal-angular4
gulpfile.js
bump_version
function bump_version(cb) { gulp.src('./package.json') .pipe(bump({ type: 'patch' })) .pipe(gulp.dest('./')); console.log('Version Bumped'); cb(); }
javascript
function bump_version(cb) { gulp.src('./package.json') .pipe(bump({ type: 'patch' })) .pipe(gulp.dest('./')); console.log('Version Bumped'); cb(); }
[ "function", "bump_version", "(", "cb", ")", "{", "gulp", ".", "src", "(", "'./package.json'", ")", ".", "pipe", "(", "bump", "(", "{", "type", ":", "'patch'", "}", ")", ")", ".", "pipe", "(", "gulp", ".", "dest", "(", "'./'", ")", ")", ";", "console", ".", "log", "(", "'Version Bumped'", ")", ";", "cb", "(", ")", ";", "}" ]
6. increase the version in package.json
[ "6", ".", "increase", "the", "version", "in", "package", ".", "json" ]
72794492c6ff3f2be0b96d9394126e53c8e45b5a
https://github.com/benbaran/adal-angular4/blob/72794492c6ff3f2be0b96d9394126e53c8e45b5a/gulpfile.js#L64-L72
16,509
benbaran/adal-angular4
gulpfile.js
git_commit
function git_commit(cb) { var package = require('./package.json'); exec('git commit -m "Version ' + package.version + ' release."', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); cb(err); }); }
javascript
function git_commit(cb) { var package = require('./package.json'); exec('git commit -m "Version ' + package.version + ' release."', function (err, stdout, stderr) { console.log(stdout); console.log(stderr); cb(err); }); }
[ "function", "git_commit", "(", "cb", ")", "{", "var", "package", "=", "require", "(", "'./package.json'", ")", ";", "exec", "(", "'git commit -m \"Version '", "+", "package", ".", "version", "+", "' release.\"'", ",", "function", "(", "err", ",", "stdout", ",", "stderr", ")", "{", "console", ".", "log", "(", "stdout", ")", ";", "console", ".", "log", "(", "stderr", ")", ";", "cb", "(", "err", ")", ";", "}", ")", ";", "}" ]
8. git commit
[ "8", ".", "git", "commit" ]
72794492c6ff3f2be0b96d9394126e53c8e45b5a
https://github.com/benbaran/adal-angular4/blob/72794492c6ff3f2be0b96d9394126e53c8e45b5a/gulpfile.js#L84-L91
16,510
RxNT/react-jsonschema-form-conditionals
src/actions/uiOverride.js
doOverride
function doOverride(uiSchema, params) { Object.keys(params).forEach(field => { let appendVal = params[field]; let fieldUiSchema = uiSchema[field]; if (!fieldUiSchema) { uiSchema[field] = appendVal; } else if (typeof appendVal === "object" && !Array.isArray(appendVal)) { doOverride(fieldUiSchema, appendVal); } else { uiSchema[field] = appendVal; } }); }
javascript
function doOverride(uiSchema, params) { Object.keys(params).forEach(field => { let appendVal = params[field]; let fieldUiSchema = uiSchema[field]; if (!fieldUiSchema) { uiSchema[field] = appendVal; } else if (typeof appendVal === "object" && !Array.isArray(appendVal)) { doOverride(fieldUiSchema, appendVal); } else { uiSchema[field] = appendVal; } }); }
[ "function", "doOverride", "(", "uiSchema", ",", "params", ")", "{", "Object", ".", "keys", "(", "params", ")", ".", "forEach", "(", "field", "=>", "{", "let", "appendVal", "=", "params", "[", "field", "]", ";", "let", "fieldUiSchema", "=", "uiSchema", "[", "field", "]", ";", "if", "(", "!", "fieldUiSchema", ")", "{", "uiSchema", "[", "field", "]", "=", "appendVal", ";", "}", "else", "if", "(", "typeof", "appendVal", "===", "\"object\"", "&&", "!", "Array", ".", "isArray", "(", "appendVal", ")", ")", "{", "doOverride", "(", "fieldUiSchema", ",", "appendVal", ")", ";", "}", "else", "{", "uiSchema", "[", "field", "]", "=", "appendVal", ";", "}", "}", ")", ";", "}" ]
Override original field in uiSchema with defined configuration @param field @param schema @param uiSchema @param conf @returns {{schema: *, uiSchema: *}}
[ "Override", "original", "field", "in", "uiSchema", "with", "defined", "configuration" ]
c834a961d45a09ccbe23bfc30d87fee2a2c22aa9
https://github.com/RxNT/react-jsonschema-form-conditionals/blob/c834a961d45a09ccbe23bfc30d87fee2a2c22aa9/src/actions/uiOverride.js#L13-L25
16,511
RxNT/react-jsonschema-form-conditionals
src/actions/uiAppend.js
doAppend
function doAppend(uiSchema, params) { Object.keys(params).forEach(field => { let appendVal = params[field]; let fieldUiSchema = uiSchema[field]; if (!fieldUiSchema) { uiSchema[field] = appendVal; } else if (Array.isArray(fieldUiSchema)) { toArray(appendVal) .filter(v => !fieldUiSchema.includes(v)) .forEach(v => fieldUiSchema.push(v)); } else if (typeof appendVal === "object" && !Array.isArray(appendVal)) { doAppend(fieldUiSchema, appendVal); } else if (typeof fieldUiSchema === "string") { if (!fieldUiSchema.includes(appendVal)) { uiSchema[field] = fieldUiSchema + " " + appendVal; } } else { uiSchema[field] = appendVal; } }); }
javascript
function doAppend(uiSchema, params) { Object.keys(params).forEach(field => { let appendVal = params[field]; let fieldUiSchema = uiSchema[field]; if (!fieldUiSchema) { uiSchema[field] = appendVal; } else if (Array.isArray(fieldUiSchema)) { toArray(appendVal) .filter(v => !fieldUiSchema.includes(v)) .forEach(v => fieldUiSchema.push(v)); } else if (typeof appendVal === "object" && !Array.isArray(appendVal)) { doAppend(fieldUiSchema, appendVal); } else if (typeof fieldUiSchema === "string") { if (!fieldUiSchema.includes(appendVal)) { uiSchema[field] = fieldUiSchema + " " + appendVal; } } else { uiSchema[field] = appendVal; } }); }
[ "function", "doAppend", "(", "uiSchema", ",", "params", ")", "{", "Object", ".", "keys", "(", "params", ")", ".", "forEach", "(", "field", "=>", "{", "let", "appendVal", "=", "params", "[", "field", "]", ";", "let", "fieldUiSchema", "=", "uiSchema", "[", "field", "]", ";", "if", "(", "!", "fieldUiSchema", ")", "{", "uiSchema", "[", "field", "]", "=", "appendVal", ";", "}", "else", "if", "(", "Array", ".", "isArray", "(", "fieldUiSchema", ")", ")", "{", "toArray", "(", "appendVal", ")", ".", "filter", "(", "v", "=>", "!", "fieldUiSchema", ".", "includes", "(", "v", ")", ")", ".", "forEach", "(", "v", "=>", "fieldUiSchema", ".", "push", "(", "v", ")", ")", ";", "}", "else", "if", "(", "typeof", "appendVal", "===", "\"object\"", "&&", "!", "Array", ".", "isArray", "(", "appendVal", ")", ")", "{", "doAppend", "(", "fieldUiSchema", ",", "appendVal", ")", ";", "}", "else", "if", "(", "typeof", "fieldUiSchema", "===", "\"string\"", ")", "{", "if", "(", "!", "fieldUiSchema", ".", "includes", "(", "appendVal", ")", ")", "{", "uiSchema", "[", "field", "]", "=", "fieldUiSchema", "+", "\" \"", "+", "appendVal", ";", "}", "}", "else", "{", "uiSchema", "[", "field", "]", "=", "appendVal", ";", "}", "}", ")", ";", "}" ]
Append original field in uiSchema with external configuration @param field @param schema @param uiSchema @param conf @returns {{schema: *, uiSchema: *}}
[ "Append", "original", "field", "in", "uiSchema", "with", "external", "configuration" ]
c834a961d45a09ccbe23bfc30d87fee2a2c22aa9
https://github.com/RxNT/react-jsonschema-form-conditionals/blob/c834a961d45a09ccbe23bfc30d87fee2a2c22aa9/src/actions/uiAppend.js#L14-L34
16,512
Availity/availity-reactstrap-validation
src/AvValidator/pattern.js
asRegExp
function asRegExp(pattern) { // if regex then return it if (isRegExp(pattern)) { return pattern; } // if string then test for valid regex then convert to regex and return const match = pattern.match(REGEX); if (match) { return new RegExp(match[1], match[2]); } return new RegExp(pattern); }
javascript
function asRegExp(pattern) { // if regex then return it if (isRegExp(pattern)) { return pattern; } // if string then test for valid regex then convert to regex and return const match = pattern.match(REGEX); if (match) { return new RegExp(match[1], match[2]); } return new RegExp(pattern); }
[ "function", "asRegExp", "(", "pattern", ")", "{", "// if regex then return it", "if", "(", "isRegExp", "(", "pattern", ")", ")", "{", "return", "pattern", ";", "}", "// if string then test for valid regex then convert to regex and return", "const", "match", "=", "pattern", ".", "match", "(", "REGEX", ")", ";", "if", "(", "match", ")", "{", "return", "new", "RegExp", "(", "match", "[", "1", "]", ",", "match", "[", "2", "]", ")", ";", "}", "return", "new", "RegExp", "(", "pattern", ")", ";", "}" ]
regular expression to test a regular expression
[ "regular", "expression", "to", "test", "a", "regular", "expression" ]
cae0221a60b3a02053e13a3946299555d02517e0
https://github.com/Availity/availity-reactstrap-validation/blob/cae0221a60b3a02053e13a3946299555d02517e0/src/AvValidator/pattern.js#L6-L19
16,513
heroku/heroku-cli-util
lib/styled.js
styledJSON
function styledJSON (obj) { let json = JSON.stringify(obj, null, 2) if (cli.color.enabled) { let cardinal = require('cardinal') let theme = require('cardinal/themes/jq') cli.log(cardinal.highlight(json, {json: true, theme: theme})) } else { cli.log(json) } }
javascript
function styledJSON (obj) { let json = JSON.stringify(obj, null, 2) if (cli.color.enabled) { let cardinal = require('cardinal') let theme = require('cardinal/themes/jq') cli.log(cardinal.highlight(json, {json: true, theme: theme})) } else { cli.log(json) } }
[ "function", "styledJSON", "(", "obj", ")", "{", "let", "json", "=", "JSON", ".", "stringify", "(", "obj", ",", "null", ",", "2", ")", "if", "(", "cli", ".", "color", ".", "enabled", ")", "{", "let", "cardinal", "=", "require", "(", "'cardinal'", ")", "let", "theme", "=", "require", "(", "'cardinal/themes/jq'", ")", "cli", ".", "log", "(", "cardinal", ".", "highlight", "(", "json", ",", "{", "json", ":", "true", ",", "theme", ":", "theme", "}", ")", ")", "}", "else", "{", "cli", ".", "log", "(", "json", ")", "}", "}" ]
styledJSON prints out colored, indented JSON @example styledHeader({foo: 'bar'}) # Outputs === { "foo": "bar" } @param {obj} object data to display @returns {null}
[ "styledJSON", "prints", "out", "colored", "indented", "JSON" ]
d214cd4279da2cabc39cec6df391696eed735dfd
https://github.com/heroku/heroku-cli-util/blob/d214cd4279da2cabc39cec6df391696eed735dfd/lib/styled.js#L17-L26
16,514
heroku/heroku-cli-util
lib/styled.js
styledHeader
function styledHeader (header) { cli.log(cli.color.dim('=== ') + cli.color.bold(header)) }
javascript
function styledHeader (header) { cli.log(cli.color.dim('=== ') + cli.color.bold(header)) }
[ "function", "styledHeader", "(", "header", ")", "{", "cli", ".", "log", "(", "cli", ".", "color", ".", "dim", "(", "'=== '", ")", "+", "cli", ".", "color", ".", "bold", "(", "header", ")", ")", "}" ]
styledHeader logs in a consistent header style @example styledHeader('MyApp') # Outputs === MyApp @param {header} header text @returns {null}
[ "styledHeader", "logs", "in", "a", "consistent", "header", "style" ]
d214cd4279da2cabc39cec6df391696eed735dfd
https://github.com/heroku/heroku-cli-util/blob/d214cd4279da2cabc39cec6df391696eed735dfd/lib/styled.js#L37-L39
16,515
heroku/heroku-cli-util
lib/styled.js
styledObject
function styledObject (obj, keys) { let keyLengths = Object.keys(obj).map(key => key.toString().length) let maxKeyLength = Math.max.apply(Math, keyLengths) + 2 function pp (obj) { if (typeof obj === 'string' || typeof obj === 'number') { return obj } else if (typeof obj === 'object') { return Object.keys(obj).map(k => k + ': ' + util.inspect(obj[k])).join(', ') } else { return util.inspect(obj) } } function logKeyValue (key, value) { cli.log(`${key}:` + ' '.repeat(maxKeyLength - key.length - 1) + pp(value)) } for (var key of (keys || Object.keys(obj).sort())) { let value = obj[key] if (Array.isArray(value)) { if (value.length > 0) { logKeyValue(key, value[0]) for (var e of value.slice(1)) { cli.log(' '.repeat(maxKeyLength) + pp(e)) } } } else if (value !== null && value !== undefined) { logKeyValue(key, value) } } }
javascript
function styledObject (obj, keys) { let keyLengths = Object.keys(obj).map(key => key.toString().length) let maxKeyLength = Math.max.apply(Math, keyLengths) + 2 function pp (obj) { if (typeof obj === 'string' || typeof obj === 'number') { return obj } else if (typeof obj === 'object') { return Object.keys(obj).map(k => k + ': ' + util.inspect(obj[k])).join(', ') } else { return util.inspect(obj) } } function logKeyValue (key, value) { cli.log(`${key}:` + ' '.repeat(maxKeyLength - key.length - 1) + pp(value)) } for (var key of (keys || Object.keys(obj).sort())) { let value = obj[key] if (Array.isArray(value)) { if (value.length > 0) { logKeyValue(key, value[0]) for (var e of value.slice(1)) { cli.log(' '.repeat(maxKeyLength) + pp(e)) } } } else if (value !== null && value !== undefined) { logKeyValue(key, value) } } }
[ "function", "styledObject", "(", "obj", ",", "keys", ")", "{", "let", "keyLengths", "=", "Object", ".", "keys", "(", "obj", ")", ".", "map", "(", "key", "=>", "key", ".", "toString", "(", ")", ".", "length", ")", "let", "maxKeyLength", "=", "Math", ".", "max", ".", "apply", "(", "Math", ",", "keyLengths", ")", "+", "2", "function", "pp", "(", "obj", ")", "{", "if", "(", "typeof", "obj", "===", "'string'", "||", "typeof", "obj", "===", "'number'", ")", "{", "return", "obj", "}", "else", "if", "(", "typeof", "obj", "===", "'object'", ")", "{", "return", "Object", ".", "keys", "(", "obj", ")", ".", "map", "(", "k", "=>", "k", "+", "': '", "+", "util", ".", "inspect", "(", "obj", "[", "k", "]", ")", ")", ".", "join", "(", "', '", ")", "}", "else", "{", "return", "util", ".", "inspect", "(", "obj", ")", "}", "}", "function", "logKeyValue", "(", "key", ",", "value", ")", "{", "cli", ".", "log", "(", "`", "${", "key", "}", "`", "+", "' '", ".", "repeat", "(", "maxKeyLength", "-", "key", ".", "length", "-", "1", ")", "+", "pp", "(", "value", ")", ")", "}", "for", "(", "var", "key", "of", "(", "keys", "||", "Object", ".", "keys", "(", "obj", ")", ".", "sort", "(", ")", ")", ")", "{", "let", "value", "=", "obj", "[", "key", "]", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "if", "(", "value", ".", "length", ">", "0", ")", "{", "logKeyValue", "(", "key", ",", "value", "[", "0", "]", ")", "for", "(", "var", "e", "of", "value", ".", "slice", "(", "1", ")", ")", "{", "cli", ".", "log", "(", "' '", ".", "repeat", "(", "maxKeyLength", ")", "+", "pp", "(", "e", ")", ")", "}", "}", "}", "else", "if", "(", "value", "!==", "null", "&&", "value", "!==", "undefined", ")", "{", "logKeyValue", "(", "key", ",", "value", ")", "}", "}", "}" ]
styledObject logs an object in a consistent columnar style @example styledObject({name: "myapp", collaborators: ["user1@example.com", "user2@example.com"]}) Collaborators: user1@example.com user2@example.com Name: myapp @param {obj} object data to print @param {keys} optional array of keys to sort/filter output @returns {null}
[ "styledObject", "logs", "an", "object", "in", "a", "consistent", "columnar", "style" ]
d214cd4279da2cabc39cec6df391696eed735dfd
https://github.com/heroku/heroku-cli-util/blob/d214cd4279da2cabc39cec6df391696eed735dfd/lib/styled.js#L54-L82
16,516
heroku/heroku-cli-util
lib/preauth.js
preauth
function preauth (app, heroku, secondFactor) { return heroku.request({ method: 'PUT', path: `/apps/${app}/pre-authorizations`, headers: { 'Heroku-Two-Factor-Code': secondFactor } }) }
javascript
function preauth (app, heroku, secondFactor) { return heroku.request({ method: 'PUT', path: `/apps/${app}/pre-authorizations`, headers: { 'Heroku-Two-Factor-Code': secondFactor } }) }
[ "function", "preauth", "(", "app", ",", "heroku", ",", "secondFactor", ")", "{", "return", "heroku", ".", "request", "(", "{", "method", ":", "'PUT'", ",", "path", ":", "`", "${", "app", "}", "`", ",", "headers", ":", "{", "'Heroku-Two-Factor-Code'", ":", "secondFactor", "}", "}", ")", "}" ]
preauth will make an API call to preauth a user for an app this makes it so the user will not have to enter a 2fa code for the next few minutes on the specified app. You need this if your command is going to make multiple API calls since otherwise the secondFactor key would only work one time for yubikeys. @param {String} app the app to preauth against @param {Heroku} heroku a heroku api client @param {String} secondFactor a second factor code @return {Promise} A promise fulfilled when the preauth is complete
[ "preauth", "will", "make", "an", "API", "call", "to", "preauth", "a", "user", "for", "an", "app", "this", "makes", "it", "so", "the", "user", "will", "not", "have", "to", "enter", "a", "2fa", "code", "for", "the", "next", "few", "minutes", "on", "the", "specified", "app", "." ]
d214cd4279da2cabc39cec6df391696eed735dfd
https://github.com/heroku/heroku-cli-util/blob/d214cd4279da2cabc39cec6df391696eed735dfd/lib/preauth.js#L18-L24
16,517
heroku/heroku-cli-util
lib/util.js
promiseOrCallback
function promiseOrCallback (fn) { return function () { if (typeof arguments[arguments.length - 1] === 'function') { let args = Array.prototype.slice.call(arguments) let callback = args.pop() fn.apply(null, args).then(function () { let args = Array.prototype.slice.call(arguments) args.unshift(null) callback.apply(null, args) }).catch(function (err) { callback(err) }) } else { return fn.apply(null, arguments) } } }
javascript
function promiseOrCallback (fn) { return function () { if (typeof arguments[arguments.length - 1] === 'function') { let args = Array.prototype.slice.call(arguments) let callback = args.pop() fn.apply(null, args).then(function () { let args = Array.prototype.slice.call(arguments) args.unshift(null) callback.apply(null, args) }).catch(function (err) { callback(err) }) } else { return fn.apply(null, arguments) } } }
[ "function", "promiseOrCallback", "(", "fn", ")", "{", "return", "function", "(", ")", "{", "if", "(", "typeof", "arguments", "[", "arguments", ".", "length", "-", "1", "]", "===", "'function'", ")", "{", "let", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", "let", "callback", "=", "args", ".", "pop", "(", ")", "fn", ".", "apply", "(", "null", ",", "args", ")", ".", "then", "(", "function", "(", ")", "{", "let", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", "args", ".", "unshift", "(", "null", ")", "callback", ".", "apply", "(", "null", ",", "args", ")", "}", ")", ".", "catch", "(", "function", "(", "err", ")", "{", "callback", "(", "err", ")", "}", ")", "}", "else", "{", "return", "fn", ".", "apply", "(", "null", ",", "arguments", ")", "}", "}", "}" ]
promiseOrCallback will convert a function that returns a promise into one that will either make a node-style callback or return a promise based on whether or not a callback is passed in. @example prompt('input? ').then(function (input) { // deal with input }) var prompt2 = promiseOrCallback(prompt) prompt('input? ', function (err, input) { // deal with input }) @param {Function} fn a promise returning function to wrap @returns {Function} a function that behaves like before unless called with a callback
[ "promiseOrCallback", "will", "convert", "a", "function", "that", "returns", "a", "promise", "into", "one", "that", "will", "either", "make", "a", "node", "-", "style", "callback", "or", "return", "a", "promise", "based", "on", "whether", "or", "not", "a", "callback", "is", "passed", "in", "." ]
d214cd4279da2cabc39cec6df391696eed735dfd
https://github.com/heroku/heroku-cli-util/blob/d214cd4279da2cabc39cec6df391696eed735dfd/lib/util.js#L20-L36
16,518
assetgraph/assetgraph
lib/transforms/subsetFonts.js
groupTextsByFontFamilyProps
function groupTextsByFontFamilyProps( textByPropsArray, availableFontFaceDeclarations ) { const snappedTexts = _.flatMapDeep(textByPropsArray, textAndProps => { const family = textAndProps.props['font-family']; if (family === undefined) { return []; } // Find all the families in the traced font-family that we have @font-face declarations for: const families = fontFamily .parse(family) .filter(family => availableFontFaceDeclarations.some( fontFace => fontFace['font-family'].toLowerCase() === family.toLowerCase() ) ); return families.map(family => { const activeFontFaceDeclaration = fontSnapper( availableFontFaceDeclarations, { ...textAndProps.props, 'font-family': fontFamily.stringify([family]) } ); if (!activeFontFaceDeclaration) { return []; } const { relations, ...props } = activeFontFaceDeclaration; const fontUrl = getPreferredFontUrl(relations); return { text: textAndProps.text, props, fontRelations: relations, fontUrl }; }); }).filter(textByProps => textByProps && textByProps.fontUrl); const textsByFontUrl = _.groupBy(snappedTexts, 'fontUrl'); return _.map(textsByFontUrl, (textsPropsArray, fontUrl) => { const texts = textsPropsArray.map(obj => obj.text); const fontFamilies = new Set( textsPropsArray.map(obj => obj.props['font-family']) ); const pageText = _.uniq(texts.join('')) .sort() .join(''); let smallestOriginalSize; let smallestOriginalFormat; for (const relation of textsPropsArray[0].fontRelations) { if (relation.to.isLoaded) { const size = relation.to.rawSrc.length; if (smallestOriginalSize === undefined || size < smallestOriginalSize) { smallestOriginalSize = size; smallestOriginalFormat = relation.to.type.toLowerCase(); } } } return { smallestOriginalSize, smallestOriginalFormat, texts, pageText, text: pageText, props: { ...textsPropsArray[0].props }, fontUrl, fontFamilies }; }); }
javascript
function groupTextsByFontFamilyProps( textByPropsArray, availableFontFaceDeclarations ) { const snappedTexts = _.flatMapDeep(textByPropsArray, textAndProps => { const family = textAndProps.props['font-family']; if (family === undefined) { return []; } // Find all the families in the traced font-family that we have @font-face declarations for: const families = fontFamily .parse(family) .filter(family => availableFontFaceDeclarations.some( fontFace => fontFace['font-family'].toLowerCase() === family.toLowerCase() ) ); return families.map(family => { const activeFontFaceDeclaration = fontSnapper( availableFontFaceDeclarations, { ...textAndProps.props, 'font-family': fontFamily.stringify([family]) } ); if (!activeFontFaceDeclaration) { return []; } const { relations, ...props } = activeFontFaceDeclaration; const fontUrl = getPreferredFontUrl(relations); return { text: textAndProps.text, props, fontRelations: relations, fontUrl }; }); }).filter(textByProps => textByProps && textByProps.fontUrl); const textsByFontUrl = _.groupBy(snappedTexts, 'fontUrl'); return _.map(textsByFontUrl, (textsPropsArray, fontUrl) => { const texts = textsPropsArray.map(obj => obj.text); const fontFamilies = new Set( textsPropsArray.map(obj => obj.props['font-family']) ); const pageText = _.uniq(texts.join('')) .sort() .join(''); let smallestOriginalSize; let smallestOriginalFormat; for (const relation of textsPropsArray[0].fontRelations) { if (relation.to.isLoaded) { const size = relation.to.rawSrc.length; if (smallestOriginalSize === undefined || size < smallestOriginalSize) { smallestOriginalSize = size; smallestOriginalFormat = relation.to.type.toLowerCase(); } } } return { smallestOriginalSize, smallestOriginalFormat, texts, pageText, text: pageText, props: { ...textsPropsArray[0].props }, fontUrl, fontFamilies }; }); }
[ "function", "groupTextsByFontFamilyProps", "(", "textByPropsArray", ",", "availableFontFaceDeclarations", ")", "{", "const", "snappedTexts", "=", "_", ".", "flatMapDeep", "(", "textByPropsArray", ",", "textAndProps", "=>", "{", "const", "family", "=", "textAndProps", ".", "props", "[", "'font-family'", "]", ";", "if", "(", "family", "===", "undefined", ")", "{", "return", "[", "]", ";", "}", "// Find all the families in the traced font-family that we have @font-face declarations for:", "const", "families", "=", "fontFamily", ".", "parse", "(", "family", ")", ".", "filter", "(", "family", "=>", "availableFontFaceDeclarations", ".", "some", "(", "fontFace", "=>", "fontFace", "[", "'font-family'", "]", ".", "toLowerCase", "(", ")", "===", "family", ".", "toLowerCase", "(", ")", ")", ")", ";", "return", "families", ".", "map", "(", "family", "=>", "{", "const", "activeFontFaceDeclaration", "=", "fontSnapper", "(", "availableFontFaceDeclarations", ",", "{", "...", "textAndProps", ".", "props", ",", "'font-family'", ":", "fontFamily", ".", "stringify", "(", "[", "family", "]", ")", "}", ")", ";", "if", "(", "!", "activeFontFaceDeclaration", ")", "{", "return", "[", "]", ";", "}", "const", "{", "relations", ",", "...", "props", "}", "=", "activeFontFaceDeclaration", ";", "const", "fontUrl", "=", "getPreferredFontUrl", "(", "relations", ")", ";", "return", "{", "text", ":", "textAndProps", ".", "text", ",", "props", ",", "fontRelations", ":", "relations", ",", "fontUrl", "}", ";", "}", ")", ";", "}", ")", ".", "filter", "(", "textByProps", "=>", "textByProps", "&&", "textByProps", ".", "fontUrl", ")", ";", "const", "textsByFontUrl", "=", "_", ".", "groupBy", "(", "snappedTexts", ",", "'fontUrl'", ")", ";", "return", "_", ".", "map", "(", "textsByFontUrl", ",", "(", "textsPropsArray", ",", "fontUrl", ")", "=>", "{", "const", "texts", "=", "textsPropsArray", ".", "map", "(", "obj", "=>", "obj", ".", "text", ")", ";", "const", "fontFamilies", "=", "new", "Set", "(", "textsPropsArray", ".", "map", "(", "obj", "=>", "obj", ".", "props", "[", "'font-family'", "]", ")", ")", ";", "const", "pageText", "=", "_", ".", "uniq", "(", "texts", ".", "join", "(", "''", ")", ")", ".", "sort", "(", ")", ".", "join", "(", "''", ")", ";", "let", "smallestOriginalSize", ";", "let", "smallestOriginalFormat", ";", "for", "(", "const", "relation", "of", "textsPropsArray", "[", "0", "]", ".", "fontRelations", ")", "{", "if", "(", "relation", ".", "to", ".", "isLoaded", ")", "{", "const", "size", "=", "relation", ".", "to", ".", "rawSrc", ".", "length", ";", "if", "(", "smallestOriginalSize", "===", "undefined", "||", "size", "<", "smallestOriginalSize", ")", "{", "smallestOriginalSize", "=", "size", ";", "smallestOriginalFormat", "=", "relation", ".", "to", ".", "type", ".", "toLowerCase", "(", ")", ";", "}", "}", "}", "return", "{", "smallestOriginalSize", ",", "smallestOriginalFormat", ",", "texts", ",", "pageText", ",", "text", ":", "pageText", ",", "props", ":", "{", "...", "textsPropsArray", "[", "0", "]", ".", "props", "}", ",", "fontUrl", ",", "fontFamilies", "}", ";", "}", ")", ";", "}" ]
Takes the output of fontTracer
[ "Takes", "the", "output", "of", "fontTracer" ]
43e00db43619d8fa74eca22d41c87e6f14f03639
https://github.com/assetgraph/assetgraph/blob/43e00db43619d8fa74eca22d41c87e6f14f03639/lib/transforms/subsetFonts.js#L79-L158
16,519
assetgraph/assetgraph
lib/transforms/bundleSystemJs.js
getSharedProperties
function getSharedProperties(configA, configB) { const bKeys = Object.keys(configB); return Object.keys(configA).filter(p => bKeys.includes(p)); }
javascript
function getSharedProperties(configA, configB) { const bKeys = Object.keys(configB); return Object.keys(configA).filter(p => bKeys.includes(p)); }
[ "function", "getSharedProperties", "(", "configA", ",", "configB", ")", "{", "const", "bKeys", "=", "Object", ".", "keys", "(", "configB", ")", ";", "return", "Object", ".", "keys", "(", "configA", ")", ".", "filter", "(", "p", "=>", "bKeys", ".", "includes", "(", "p", ")", ")", ";", "}" ]
meta, packages deep
[ "meta", "packages", "deep" ]
43e00db43619d8fa74eca22d41c87e6f14f03639
https://github.com/assetgraph/assetgraph/blob/43e00db43619d8fa74eca22d41c87e6f14f03639/lib/transforms/bundleSystemJs.js#L66-L69
16,520
assetgraph/assetgraph
lib/transforms/bundleSystemJs.js
generateBundleName
function generateBundleName(name, modules, conditionValueOrVariationObject) { // first check if the given modules already matches an existing bundle let existingBundleName; for (const bundleName of Object.keys(bundles)) { const bundleModules = bundles[bundleName].modules; if ( containsModules(modules, bundleModules) && containsModules(bundleModules, modules) ) { existingBundleName = bundleName; } } if (existingBundleName) { return existingBundleName; } let shortName = name.split('/').pop(); const dotIndex = shortName.lastIndexOf('.'); if (dotIndex > 0) { shortName = shortName.substr(0, dotIndex); } let bundleName = shortName.replace(/[ .]/g, '').toLowerCase(); if (conditionValueOrVariationObject) { if (typeof conditionValueOrVariationObject === 'string') { bundleName += `-${conditionValueOrVariationObject}`; } else { for (const condition of Object.keys(conditionValueOrVariationObject)) { bundleName += `-${conditionValueOrVariationObject[condition]}`; } } } let i; if (bundles[bundleName]) { i = 1; while (bundles[`${bundleName}-${i}`]) { i += 1; } } return bundleName + (i ? `-${i}` : ''); }
javascript
function generateBundleName(name, modules, conditionValueOrVariationObject) { // first check if the given modules already matches an existing bundle let existingBundleName; for (const bundleName of Object.keys(bundles)) { const bundleModules = bundles[bundleName].modules; if ( containsModules(modules, bundleModules) && containsModules(bundleModules, modules) ) { existingBundleName = bundleName; } } if (existingBundleName) { return existingBundleName; } let shortName = name.split('/').pop(); const dotIndex = shortName.lastIndexOf('.'); if (dotIndex > 0) { shortName = shortName.substr(0, dotIndex); } let bundleName = shortName.replace(/[ .]/g, '').toLowerCase(); if (conditionValueOrVariationObject) { if (typeof conditionValueOrVariationObject === 'string') { bundleName += `-${conditionValueOrVariationObject}`; } else { for (const condition of Object.keys(conditionValueOrVariationObject)) { bundleName += `-${conditionValueOrVariationObject[condition]}`; } } } let i; if (bundles[bundleName]) { i = 1; while (bundles[`${bundleName}-${i}`]) { i += 1; } } return bundleName + (i ? `-${i}` : ''); }
[ "function", "generateBundleName", "(", "name", ",", "modules", ",", "conditionValueOrVariationObject", ")", "{", "// first check if the given modules already matches an existing bundle", "let", "existingBundleName", ";", "for", "(", "const", "bundleName", "of", "Object", ".", "keys", "(", "bundles", ")", ")", "{", "const", "bundleModules", "=", "bundles", "[", "bundleName", "]", ".", "modules", ";", "if", "(", "containsModules", "(", "modules", ",", "bundleModules", ")", "&&", "containsModules", "(", "bundleModules", ",", "modules", ")", ")", "{", "existingBundleName", "=", "bundleName", ";", "}", "}", "if", "(", "existingBundleName", ")", "{", "return", "existingBundleName", ";", "}", "let", "shortName", "=", "name", ".", "split", "(", "'/'", ")", ".", "pop", "(", ")", ";", "const", "dotIndex", "=", "shortName", ".", "lastIndexOf", "(", "'.'", ")", ";", "if", "(", "dotIndex", ">", "0", ")", "{", "shortName", "=", "shortName", ".", "substr", "(", "0", ",", "dotIndex", ")", ";", "}", "let", "bundleName", "=", "shortName", ".", "replace", "(", "/", "[ .]", "/", "g", ",", "''", ")", ".", "toLowerCase", "(", ")", ";", "if", "(", "conditionValueOrVariationObject", ")", "{", "if", "(", "typeof", "conditionValueOrVariationObject", "===", "'string'", ")", "{", "bundleName", "+=", "`", "${", "conditionValueOrVariationObject", "}", "`", ";", "}", "else", "{", "for", "(", "const", "condition", "of", "Object", ".", "keys", "(", "conditionValueOrVariationObject", ")", ")", "{", "bundleName", "+=", "`", "${", "conditionValueOrVariationObject", "[", "condition", "]", "}", "`", ";", "}", "}", "}", "let", "i", ";", "if", "(", "bundles", "[", "bundleName", "]", ")", "{", "i", "=", "1", ";", "while", "(", "bundles", "[", "`", "${", "bundleName", "}", "${", "i", "}", "`", "]", ")", "{", "i", "+=", "1", ";", "}", "}", "return", "bundleName", "+", "(", "i", "?", "`", "${", "i", "}", "`", ":", "''", ")", ";", "}" ]
simple random bundle name generation with duplication avoidance
[ "simple", "random", "bundle", "name", "generation", "with", "duplication", "avoidance" ]
43e00db43619d8fa74eca22d41c87e6f14f03639
https://github.com/assetgraph/assetgraph/blob/43e00db43619d8fa74eca22d41c87e6f14f03639/lib/transforms/bundleSystemJs.js#L240-L282
16,521
assetgraph/assetgraph
lib/transforms/bundleSystemJs.js
intersectModules
function intersectModules(modulesA, modulesB) { const intersection = []; for (const module of modulesA) { if (modulesB.includes(module)) { intersection.push(module); } } return intersection; }
javascript
function intersectModules(modulesA, modulesB) { const intersection = []; for (const module of modulesA) { if (modulesB.includes(module)) { intersection.push(module); } } return intersection; }
[ "function", "intersectModules", "(", "modulesA", ",", "modulesB", ")", "{", "const", "intersection", "=", "[", "]", ";", "for", "(", "const", "module", "of", "modulesA", ")", "{", "if", "(", "modulesB", ".", "includes", "(", "module", ")", ")", "{", "intersection", ".", "push", "(", "module", ")", ";", "}", "}", "return", "intersection", ";", "}" ]
intersect two arrays
[ "intersect", "two", "arrays" ]
43e00db43619d8fa74eca22d41c87e6f14f03639
https://github.com/assetgraph/assetgraph/blob/43e00db43619d8fa74eca22d41c87e6f14f03639/lib/transforms/bundleSystemJs.js#L285-L293
16,522
assetgraph/assetgraph
lib/transforms/bundleSystemJs.js
subtractModules
function subtractModules(modulesA, modulesB) { const subtracted = []; for (const module of modulesA) { if (!modulesB.includes(module)) { subtracted.push(module); } } return subtracted; }
javascript
function subtractModules(modulesA, modulesB) { const subtracted = []; for (const module of modulesA) { if (!modulesB.includes(module)) { subtracted.push(module); } } return subtracted; }
[ "function", "subtractModules", "(", "modulesA", ",", "modulesB", ")", "{", "const", "subtracted", "=", "[", "]", ";", "for", "(", "const", "module", "of", "modulesA", ")", "{", "if", "(", "!", "modulesB", ".", "includes", "(", "module", ")", ")", "{", "subtracted", ".", "push", "(", "module", ")", ";", "}", "}", "return", "subtracted", ";", "}" ]
remove elements of arrayB from arrayA
[ "remove", "elements", "of", "arrayB", "from", "arrayA" ]
43e00db43619d8fa74eca22d41c87e6f14f03639
https://github.com/assetgraph/assetgraph/blob/43e00db43619d8fa74eca22d41c87e6f14f03639/lib/transforms/bundleSystemJs.js#L296-L304
16,523
assetgraph/assetgraph
lib/util/fonts/downloadGoogleFonts.js
downloadGoogleFonts
async function downloadGoogleFonts( fontProps, { formats = ['woff2', 'woff'], fontDisplay = 'swap', text } = {} ) { const sortedFormats = []; for (const format of formatOrder) { if (formats.includes(format)) { sortedFormats.push(format); } } const result = {}; const googleFontId = getGoogleIdForFontProps(fontProps); let fontCssUrl = `https://fonts.googleapis.com/css?family=${googleFontId}`; if (text) { fontCssUrl += `&text=${encodeURIComponent(text)}`; } result.src = await Promise.all( sortedFormats.map(async format => { const assetGraph = new AssetGraph(); assetGraph.teepee.headers['User-Agent'] = formatAgents[format]; const [cssAsset] = await assetGraph.loadAssets(fontCssUrl); await assetGraph.populate(); const [fontRelation] = assetGraph.findRelations({ from: cssAsset, type: 'CssFontFaceSrc' }); fontRelation.node.each(decl => { if (decl.prop !== 'src') { result[decl.prop] = decl.value; } }); return [fontRelation.to, fontRelation.format]; }) ); if (!('unicode-range' in result)) { const font = result.src[0][0]; result['unicode-range'] = unicodeRange( fontkit.create(font.rawSrc).characterSet ); } result['font-display'] = fontDisplay; // Output font face declaration object as CSS const declarationStrings = []; for (const [property, value] of Object.entries(result)) { if (property !== 'src') { declarationStrings.push(` ${property}: ${value};`); } } const sources = result.src.map(([font, format]) => { return `url('${font.dataUrl}') format('${format}')`; }); declarationStrings.push(` src: \n ${sources.join(',\n ')};`); return ['@font-face {', ...declarationStrings, '}'].join('\n'); }
javascript
async function downloadGoogleFonts( fontProps, { formats = ['woff2', 'woff'], fontDisplay = 'swap', text } = {} ) { const sortedFormats = []; for (const format of formatOrder) { if (formats.includes(format)) { sortedFormats.push(format); } } const result = {}; const googleFontId = getGoogleIdForFontProps(fontProps); let fontCssUrl = `https://fonts.googleapis.com/css?family=${googleFontId}`; if (text) { fontCssUrl += `&text=${encodeURIComponent(text)}`; } result.src = await Promise.all( sortedFormats.map(async format => { const assetGraph = new AssetGraph(); assetGraph.teepee.headers['User-Agent'] = formatAgents[format]; const [cssAsset] = await assetGraph.loadAssets(fontCssUrl); await assetGraph.populate(); const [fontRelation] = assetGraph.findRelations({ from: cssAsset, type: 'CssFontFaceSrc' }); fontRelation.node.each(decl => { if (decl.prop !== 'src') { result[decl.prop] = decl.value; } }); return [fontRelation.to, fontRelation.format]; }) ); if (!('unicode-range' in result)) { const font = result.src[0][0]; result['unicode-range'] = unicodeRange( fontkit.create(font.rawSrc).characterSet ); } result['font-display'] = fontDisplay; // Output font face declaration object as CSS const declarationStrings = []; for (const [property, value] of Object.entries(result)) { if (property !== 'src') { declarationStrings.push(` ${property}: ${value};`); } } const sources = result.src.map(([font, format]) => { return `url('${font.dataUrl}') format('${format}')`; }); declarationStrings.push(` src: \n ${sources.join(',\n ')};`); return ['@font-face {', ...declarationStrings, '}'].join('\n'); }
[ "async", "function", "downloadGoogleFonts", "(", "fontProps", ",", "{", "formats", "=", "[", "'woff2'", ",", "'woff'", "]", ",", "fontDisplay", "=", "'swap'", ",", "text", "}", "=", "{", "}", ")", "{", "const", "sortedFormats", "=", "[", "]", ";", "for", "(", "const", "format", "of", "formatOrder", ")", "{", "if", "(", "formats", ".", "includes", "(", "format", ")", ")", "{", "sortedFormats", ".", "push", "(", "format", ")", ";", "}", "}", "const", "result", "=", "{", "}", ";", "const", "googleFontId", "=", "getGoogleIdForFontProps", "(", "fontProps", ")", ";", "let", "fontCssUrl", "=", "`", "${", "googleFontId", "}", "`", ";", "if", "(", "text", ")", "{", "fontCssUrl", "+=", "`", "${", "encodeURIComponent", "(", "text", ")", "}", "`", ";", "}", "result", ".", "src", "=", "await", "Promise", ".", "all", "(", "sortedFormats", ".", "map", "(", "async", "format", "=>", "{", "const", "assetGraph", "=", "new", "AssetGraph", "(", ")", ";", "assetGraph", ".", "teepee", ".", "headers", "[", "'User-Agent'", "]", "=", "formatAgents", "[", "format", "]", ";", "const", "[", "cssAsset", "]", "=", "await", "assetGraph", ".", "loadAssets", "(", "fontCssUrl", ")", ";", "await", "assetGraph", ".", "populate", "(", ")", ";", "const", "[", "fontRelation", "]", "=", "assetGraph", ".", "findRelations", "(", "{", "from", ":", "cssAsset", ",", "type", ":", "'CssFontFaceSrc'", "}", ")", ";", "fontRelation", ".", "node", ".", "each", "(", "decl", "=>", "{", "if", "(", "decl", ".", "prop", "!==", "'src'", ")", "{", "result", "[", "decl", ".", "prop", "]", "=", "decl", ".", "value", ";", "}", "}", ")", ";", "return", "[", "fontRelation", ".", "to", ",", "fontRelation", ".", "format", "]", ";", "}", ")", ")", ";", "if", "(", "!", "(", "'unicode-range'", "in", "result", ")", ")", "{", "const", "font", "=", "result", ".", "src", "[", "0", "]", "[", "0", "]", ";", "result", "[", "'unicode-range'", "]", "=", "unicodeRange", "(", "fontkit", ".", "create", "(", "font", ".", "rawSrc", ")", ".", "characterSet", ")", ";", "}", "result", "[", "'font-display'", "]", "=", "fontDisplay", ";", "// Output font face declaration object as CSS", "const", "declarationStrings", "=", "[", "]", ";", "for", "(", "const", "[", "property", ",", "value", "]", "of", "Object", ".", "entries", "(", "result", ")", ")", "{", "if", "(", "property", "!==", "'src'", ")", "{", "declarationStrings", ".", "push", "(", "`", "${", "property", "}", "${", "value", "}", "`", ")", ";", "}", "}", "const", "sources", "=", "result", ".", "src", ".", "map", "(", "(", "[", "font", ",", "format", "]", ")", "=>", "{", "return", "`", "${", "font", ".", "dataUrl", "}", "${", "format", "}", "`", ";", "}", ")", ";", "declarationStrings", ".", "push", "(", "`", "\\n", "${", "sources", ".", "join", "(", "',\\n '", ")", "}", "`", ")", ";", "return", "[", "'@font-face {'", ",", "...", "declarationStrings", ",", "'}'", "]", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Download google fonts for self-hosting @async @param {FontProps} fontProps CSS font properties to get font for @param {Object} options @param {String[]} [options.formats=['woff2', 'woff']] List of formats that should be inclued in the output @param {String} [options.fontDisplay='swap'] CSS font-display value in returned CSS blocks @param {String} [options.text] Text to create a subset with @return {String} CSS asset with inlined google fonts
[ "Download", "google", "fonts", "for", "self", "-", "hosting" ]
43e00db43619d8fa74eca22d41c87e6f14f03639
https://github.com/assetgraph/assetgraph/blob/43e00db43619d8fa74eca22d41c87e6f14f03639/lib/util/fonts/downloadGoogleFonts.js#L43-L112
16,524
assetgraph/assetgraph
lib/util/fonts/findCustomPropertyDefinitions.js
findCustomPropertyDefinitions
function findCustomPropertyDefinitions(cssAssets) { const definitionsByProp = {}; const incomingReferencesByProp = {}; for (const cssAsset of cssAssets) { cssAsset.eachRuleInParseTree(cssRule => { if ( cssRule.parent.type === 'rule' && cssRule.type === 'decl' && /^--/.test(cssRule.prop) ) { (definitionsByProp[cssRule.prop] = definitionsByProp[cssRule.prop] || new Set()).add(cssRule); for (const customPropertyName of extractReferencedCustomPropertyNames( cssRule.value )) { (incomingReferencesByProp[cssRule.prop] = incomingReferencesByProp[cssRule.prop] || new Set()).add( customPropertyName ); } } }); } const expandedDefinitionsByProp = {}; for (const prop of Object.keys(definitionsByProp)) { expandedDefinitionsByProp[prop] = new Set(); const seenProps = new Set(); const queue = [prop]; while (queue.length > 0) { const referencedProp = queue.shift(); if (!seenProps.has(referencedProp)) { seenProps.add(referencedProp); if (definitionsByProp[referencedProp]) { for (const cssRule of definitionsByProp[referencedProp]) { expandedDefinitionsByProp[prop].add(cssRule); } } const incomingReferences = incomingReferencesByProp[referencedProp]; if (incomingReferences) { for (const incomingReference of incomingReferences) { queue.push(incomingReference); } } } } } return expandedDefinitionsByProp; }
javascript
function findCustomPropertyDefinitions(cssAssets) { const definitionsByProp = {}; const incomingReferencesByProp = {}; for (const cssAsset of cssAssets) { cssAsset.eachRuleInParseTree(cssRule => { if ( cssRule.parent.type === 'rule' && cssRule.type === 'decl' && /^--/.test(cssRule.prop) ) { (definitionsByProp[cssRule.prop] = definitionsByProp[cssRule.prop] || new Set()).add(cssRule); for (const customPropertyName of extractReferencedCustomPropertyNames( cssRule.value )) { (incomingReferencesByProp[cssRule.prop] = incomingReferencesByProp[cssRule.prop] || new Set()).add( customPropertyName ); } } }); } const expandedDefinitionsByProp = {}; for (const prop of Object.keys(definitionsByProp)) { expandedDefinitionsByProp[prop] = new Set(); const seenProps = new Set(); const queue = [prop]; while (queue.length > 0) { const referencedProp = queue.shift(); if (!seenProps.has(referencedProp)) { seenProps.add(referencedProp); if (definitionsByProp[referencedProp]) { for (const cssRule of definitionsByProp[referencedProp]) { expandedDefinitionsByProp[prop].add(cssRule); } } const incomingReferences = incomingReferencesByProp[referencedProp]; if (incomingReferences) { for (const incomingReference of incomingReferences) { queue.push(incomingReference); } } } } } return expandedDefinitionsByProp; }
[ "function", "findCustomPropertyDefinitions", "(", "cssAssets", ")", "{", "const", "definitionsByProp", "=", "{", "}", ";", "const", "incomingReferencesByProp", "=", "{", "}", ";", "for", "(", "const", "cssAsset", "of", "cssAssets", ")", "{", "cssAsset", ".", "eachRuleInParseTree", "(", "cssRule", "=>", "{", "if", "(", "cssRule", ".", "parent", ".", "type", "===", "'rule'", "&&", "cssRule", ".", "type", "===", "'decl'", "&&", "/", "^--", "/", ".", "test", "(", "cssRule", ".", "prop", ")", ")", "{", "(", "definitionsByProp", "[", "cssRule", ".", "prop", "]", "=", "definitionsByProp", "[", "cssRule", ".", "prop", "]", "||", "new", "Set", "(", ")", ")", ".", "add", "(", "cssRule", ")", ";", "for", "(", "const", "customPropertyName", "of", "extractReferencedCustomPropertyNames", "(", "cssRule", ".", "value", ")", ")", "{", "(", "incomingReferencesByProp", "[", "cssRule", ".", "prop", "]", "=", "incomingReferencesByProp", "[", "cssRule", ".", "prop", "]", "||", "new", "Set", "(", ")", ")", ".", "add", "(", "customPropertyName", ")", ";", "}", "}", "}", ")", ";", "}", "const", "expandedDefinitionsByProp", "=", "{", "}", ";", "for", "(", "const", "prop", "of", "Object", ".", "keys", "(", "definitionsByProp", ")", ")", "{", "expandedDefinitionsByProp", "[", "prop", "]", "=", "new", "Set", "(", ")", ";", "const", "seenProps", "=", "new", "Set", "(", ")", ";", "const", "queue", "=", "[", "prop", "]", ";", "while", "(", "queue", ".", "length", ">", "0", ")", "{", "const", "referencedProp", "=", "queue", ".", "shift", "(", ")", ";", "if", "(", "!", "seenProps", ".", "has", "(", "referencedProp", ")", ")", "{", "seenProps", ".", "add", "(", "referencedProp", ")", ";", "if", "(", "definitionsByProp", "[", "referencedProp", "]", ")", "{", "for", "(", "const", "cssRule", "of", "definitionsByProp", "[", "referencedProp", "]", ")", "{", "expandedDefinitionsByProp", "[", "prop", "]", ".", "add", "(", "cssRule", ")", ";", "}", "}", "const", "incomingReferences", "=", "incomingReferencesByProp", "[", "referencedProp", "]", ";", "if", "(", "incomingReferences", ")", "{", "for", "(", "const", "incomingReference", "of", "incomingReferences", ")", "{", "queue", ".", "push", "(", "incomingReference", ")", ";", "}", "}", "}", "}", "}", "return", "expandedDefinitionsByProp", ";", "}" ]
Find all custom property definitions grouped by the custom properties they contribute to
[ "Find", "all", "custom", "property", "definitions", "grouped", "by", "the", "custom", "properties", "they", "contribute", "to" ]
43e00db43619d8fa74eca22d41c87e6f14f03639
https://github.com/assetgraph/assetgraph/blob/43e00db43619d8fa74eca22d41c87e6f14f03639/lib/util/fonts/findCustomPropertyDefinitions.js#L4-L52
16,525
assetgraph/assetgraph
lib/transforms/inlineAssetsPerQueryString.js
getMinimumIeVersionUsage
function getMinimumIeVersionUsage(asset, stack = []) { if (asset.type === 'Html') { return 1; } if (minimumIeVersionByAsset.has(asset)) { return minimumIeVersionByAsset.get(asset); } stack.push(asset); const minimumIeVersion = Math.min( ...asset.incomingRelations .filter(incomingRelation => !stack.includes(incomingRelation.from)) .map(incomingRelation => { let matchCondition; if (incomingRelation.type === 'HtmlConditionalComment') { matchCondition = incomingRelation.condition.match( /^(gte?|lte?)\s+IE\s+(\d+)$/i ); } else if ( incomingRelation.conditionalComments && incomingRelation.conditionalComments.length > 0 ) { matchCondition = incomingRelation.conditionalComments[0].nodeValue.match( /^\[if\s+(gte?|lte?)\s+IE\s+(\d+)\s*\]\s*>\s*<\s*!\s*$/i ); } if (matchCondition) { if (matchCondition[1].substr(0, 2) === 'lt') { return 1; } else { return ( parseInt(matchCondition[2], 10) + (matchCondition[1].toLowerCase() === 'gt' ? 1 : 0) ); } } else { return getMinimumIeVersionUsage(incomingRelation.from, stack); } }) ); minimumIeVersionByAsset.set(asset, minimumIeVersion); return minimumIeVersion; }
javascript
function getMinimumIeVersionUsage(asset, stack = []) { if (asset.type === 'Html') { return 1; } if (minimumIeVersionByAsset.has(asset)) { return minimumIeVersionByAsset.get(asset); } stack.push(asset); const minimumIeVersion = Math.min( ...asset.incomingRelations .filter(incomingRelation => !stack.includes(incomingRelation.from)) .map(incomingRelation => { let matchCondition; if (incomingRelation.type === 'HtmlConditionalComment') { matchCondition = incomingRelation.condition.match( /^(gte?|lte?)\s+IE\s+(\d+)$/i ); } else if ( incomingRelation.conditionalComments && incomingRelation.conditionalComments.length > 0 ) { matchCondition = incomingRelation.conditionalComments[0].nodeValue.match( /^\[if\s+(gte?|lte?)\s+IE\s+(\d+)\s*\]\s*>\s*<\s*!\s*$/i ); } if (matchCondition) { if (matchCondition[1].substr(0, 2) === 'lt') { return 1; } else { return ( parseInt(matchCondition[2], 10) + (matchCondition[1].toLowerCase() === 'gt' ? 1 : 0) ); } } else { return getMinimumIeVersionUsage(incomingRelation.from, stack); } }) ); minimumIeVersionByAsset.set(asset, minimumIeVersion); return minimumIeVersion; }
[ "function", "getMinimumIeVersionUsage", "(", "asset", ",", "stack", "=", "[", "]", ")", "{", "if", "(", "asset", ".", "type", "===", "'Html'", ")", "{", "return", "1", ";", "}", "if", "(", "minimumIeVersionByAsset", ".", "has", "(", "asset", ")", ")", "{", "return", "minimumIeVersionByAsset", ".", "get", "(", "asset", ")", ";", "}", "stack", ".", "push", "(", "asset", ")", ";", "const", "minimumIeVersion", "=", "Math", ".", "min", "(", "...", "asset", ".", "incomingRelations", ".", "filter", "(", "incomingRelation", "=>", "!", "stack", ".", "includes", "(", "incomingRelation", ".", "from", ")", ")", ".", "map", "(", "incomingRelation", "=>", "{", "let", "matchCondition", ";", "if", "(", "incomingRelation", ".", "type", "===", "'HtmlConditionalComment'", ")", "{", "matchCondition", "=", "incomingRelation", ".", "condition", ".", "match", "(", "/", "^(gte?|lte?)\\s+IE\\s+(\\d+)$", "/", "i", ")", ";", "}", "else", "if", "(", "incomingRelation", ".", "conditionalComments", "&&", "incomingRelation", ".", "conditionalComments", ".", "length", ">", "0", ")", "{", "matchCondition", "=", "incomingRelation", ".", "conditionalComments", "[", "0", "]", ".", "nodeValue", ".", "match", "(", "/", "^\\[if\\s+(gte?|lte?)\\s+IE\\s+(\\d+)\\s*\\]\\s*>\\s*<\\s*!\\s*$", "/", "i", ")", ";", "}", "if", "(", "matchCondition", ")", "{", "if", "(", "matchCondition", "[", "1", "]", ".", "substr", "(", "0", ",", "2", ")", "===", "'lt'", ")", "{", "return", "1", ";", "}", "else", "{", "return", "(", "parseInt", "(", "matchCondition", "[", "2", "]", ",", "10", ")", "+", "(", "matchCondition", "[", "1", "]", ".", "toLowerCase", "(", ")", "===", "'gt'", "?", "1", ":", "0", ")", ")", ";", "}", "}", "else", "{", "return", "getMinimumIeVersionUsage", "(", "incomingRelation", ".", "from", ",", "stack", ")", ";", "}", "}", ")", ")", ";", "minimumIeVersionByAsset", ".", "set", "(", "asset", ",", "minimumIeVersion", ")", ";", "return", "minimumIeVersion", ";", "}" ]
Asset => minimumIeVersion
[ "Asset", "=", ">", "minimumIeVersion" ]
43e00db43619d8fa74eca22d41c87e6f14f03639
https://github.com/assetgraph/assetgraph/blob/43e00db43619d8fa74eca22d41c87e6f14f03639/lib/transforms/inlineAssetsPerQueryString.js#L20-L61
16,526
mixmaxhq/mongo-cursor-pagination
src/utils/resolveFields.js
fieldsFromMongo
function fieldsFromMongo(projection = {}, includeIdDefault = false) { const fields = _.reduce(projection, (memo, value, key) => { if (key !== '_id' && value !== undefined && !value) { throw new TypeError('projection includes exclusion, but we do not support that'); } if (value || (key === '_id' && value === undefined && includeIdDefault)) { memo.push(key); } return memo; }, []); return ProjectionFieldSet.fromDotted(fields); }
javascript
function fieldsFromMongo(projection = {}, includeIdDefault = false) { const fields = _.reduce(projection, (memo, value, key) => { if (key !== '_id' && value !== undefined && !value) { throw new TypeError('projection includes exclusion, but we do not support that'); } if (value || (key === '_id' && value === undefined && includeIdDefault)) { memo.push(key); } return memo; }, []); return ProjectionFieldSet.fromDotted(fields); }
[ "function", "fieldsFromMongo", "(", "projection", "=", "{", "}", ",", "includeIdDefault", "=", "false", ")", "{", "const", "fields", "=", "_", ".", "reduce", "(", "projection", ",", "(", "memo", ",", "value", ",", "key", ")", "=>", "{", "if", "(", "key", "!==", "'_id'", "&&", "value", "!==", "undefined", "&&", "!", "value", ")", "{", "throw", "new", "TypeError", "(", "'projection includes exclusion, but we do not support that'", ")", ";", "}", "if", "(", "value", "||", "(", "key", "===", "'_id'", "&&", "value", "===", "undefined", "&&", "includeIdDefault", ")", ")", "{", "memo", ".", "push", "(", "key", ")", ";", "}", "return", "memo", ";", "}", ",", "[", "]", ")", ";", "return", "ProjectionFieldSet", ".", "fromDotted", "(", "fields", ")", ";", "}" ]
Produce a ProjectionFieldSet from the given mongo projection, after validating it to ensure it doesn't have exclusion rules. @param {Object<String, *>} projection The projected fields. @param {Boolean=} includeIdDefault Whether to include _id by default (mongo's default behavior). @returns {ProjectionFieldSet} The synthesized field set.
[ "Produce", "a", "ProjectionFieldSet", "from", "the", "given", "mongo", "projection", "after", "validating", "it", "to", "ensure", "it", "doesn", "t", "have", "exclusion", "rules", "." ]
fa7d2c81012cd0cd08c9338e86bcbfa242f7dd42
https://github.com/mixmaxhq/mongo-cursor-pagination/blob/fa7d2c81012cd0cd08c9338e86bcbfa242f7dd42/src/utils/resolveFields.js#L12-L25
16,527
mixmaxhq/mongo-cursor-pagination
src/utils/resolveFields.js
resolveFields
function resolveFields(desiredFields, allowedFields, overrideFields) { if (desiredFields != null && !Array.isArray(desiredFields)) { throw new TypeError('expected nullable array for desiredFields'); } if (allowedFields != null && !_.isObject(allowedFields)) { throw new TypeError('expected nullable plain object for allowedFields'); } if (overrideFields !== undefined && !_.isObject(overrideFields)) { throw new TypeError('expected optional plain object for overrideFields'); } // If no desired fields are specified, we treat that as wanting the default set of fields. const desiredFieldset = _.isEmpty(desiredFields) ? new ProjectionFieldSet([[]]) : ProjectionFieldSet.fromDotted(desiredFields); // If allowedFields isn't provided, we treat that as not having restrictions. However, if it's an // empty array, we treat that as have no valid fields. const allowedFieldset = allowedFields ? fieldsFromMongo(allowedFields) : new ProjectionFieldSet([[]]); // Don't trust fields passed in the querystring, so whitelist them against the // fields defined in parameters. Add override fields from parameters. const fields = desiredFieldset.intersect(allowedFieldset).union(fieldsFromMongo(overrideFields)); if (fields.isEmpty()) { // This projection isn't representable as a mongo projection - nor should it be. We don't want // to query mongo for zero fields. return null; } // Generate the mongo projection. const projection = fields.toMongo(); // Whether overrideFields explicitly removes _id. const disableIdOverride = overrideFields && overrideFields._id !== undefined && !overrideFields._id; // Explicitly exclude the _id field (which mongo includes by default) if we don't allow it, or // if we've disabled it in the override. if (!fields.contains(['_id']) || disableIdOverride) { // If the override excludes _id, then enforce that here. All other fields will be included by // default, so we don't need to specify them individually, as we only support whitelisting // fields, and do not support field blacklists. projection._id = 0; } return projection; }
javascript
function resolveFields(desiredFields, allowedFields, overrideFields) { if (desiredFields != null && !Array.isArray(desiredFields)) { throw new TypeError('expected nullable array for desiredFields'); } if (allowedFields != null && !_.isObject(allowedFields)) { throw new TypeError('expected nullable plain object for allowedFields'); } if (overrideFields !== undefined && !_.isObject(overrideFields)) { throw new TypeError('expected optional plain object for overrideFields'); } // If no desired fields are specified, we treat that as wanting the default set of fields. const desiredFieldset = _.isEmpty(desiredFields) ? new ProjectionFieldSet([[]]) : ProjectionFieldSet.fromDotted(desiredFields); // If allowedFields isn't provided, we treat that as not having restrictions. However, if it's an // empty array, we treat that as have no valid fields. const allowedFieldset = allowedFields ? fieldsFromMongo(allowedFields) : new ProjectionFieldSet([[]]); // Don't trust fields passed in the querystring, so whitelist them against the // fields defined in parameters. Add override fields from parameters. const fields = desiredFieldset.intersect(allowedFieldset).union(fieldsFromMongo(overrideFields)); if (fields.isEmpty()) { // This projection isn't representable as a mongo projection - nor should it be. We don't want // to query mongo for zero fields. return null; } // Generate the mongo projection. const projection = fields.toMongo(); // Whether overrideFields explicitly removes _id. const disableIdOverride = overrideFields && overrideFields._id !== undefined && !overrideFields._id; // Explicitly exclude the _id field (which mongo includes by default) if we don't allow it, or // if we've disabled it in the override. if (!fields.contains(['_id']) || disableIdOverride) { // If the override excludes _id, then enforce that here. All other fields will be included by // default, so we don't need to specify them individually, as we only support whitelisting // fields, and do not support field blacklists. projection._id = 0; } return projection; }
[ "function", "resolveFields", "(", "desiredFields", ",", "allowedFields", ",", "overrideFields", ")", "{", "if", "(", "desiredFields", "!=", "null", "&&", "!", "Array", ".", "isArray", "(", "desiredFields", ")", ")", "{", "throw", "new", "TypeError", "(", "'expected nullable array for desiredFields'", ")", ";", "}", "if", "(", "allowedFields", "!=", "null", "&&", "!", "_", ".", "isObject", "(", "allowedFields", ")", ")", "{", "throw", "new", "TypeError", "(", "'expected nullable plain object for allowedFields'", ")", ";", "}", "if", "(", "overrideFields", "!==", "undefined", "&&", "!", "_", ".", "isObject", "(", "overrideFields", ")", ")", "{", "throw", "new", "TypeError", "(", "'expected optional plain object for overrideFields'", ")", ";", "}", "// If no desired fields are specified, we treat that as wanting the default set of fields.", "const", "desiredFieldset", "=", "_", ".", "isEmpty", "(", "desiredFields", ")", "?", "new", "ProjectionFieldSet", "(", "[", "[", "]", "]", ")", ":", "ProjectionFieldSet", ".", "fromDotted", "(", "desiredFields", ")", ";", "// If allowedFields isn't provided, we treat that as not having restrictions. However, if it's an", "// empty array, we treat that as have no valid fields.", "const", "allowedFieldset", "=", "allowedFields", "?", "fieldsFromMongo", "(", "allowedFields", ")", ":", "new", "ProjectionFieldSet", "(", "[", "[", "]", "]", ")", ";", "// Don't trust fields passed in the querystring, so whitelist them against the", "// fields defined in parameters. Add override fields from parameters.", "const", "fields", "=", "desiredFieldset", ".", "intersect", "(", "allowedFieldset", ")", ".", "union", "(", "fieldsFromMongo", "(", "overrideFields", ")", ")", ";", "if", "(", "fields", ".", "isEmpty", "(", ")", ")", "{", "// This projection isn't representable as a mongo projection - nor should it be. We don't want", "// to query mongo for zero fields.", "return", "null", ";", "}", "// Generate the mongo projection.", "const", "projection", "=", "fields", ".", "toMongo", "(", ")", ";", "// Whether overrideFields explicitly removes _id.", "const", "disableIdOverride", "=", "overrideFields", "&&", "overrideFields", ".", "_id", "!==", "undefined", "&&", "!", "overrideFields", ".", "_id", ";", "// Explicitly exclude the _id field (which mongo includes by default) if we don't allow it, or", "// if we've disabled it in the override.", "if", "(", "!", "fields", ".", "contains", "(", "[", "'_id'", "]", ")", "||", "disableIdOverride", ")", "{", "// If the override excludes _id, then enforce that here. All other fields will be included by", "// default, so we don't need to specify them individually, as we only support whitelisting", "// fields, and do not support field blacklists.", "projection", ".", "_id", "=", "0", ";", "}", "return", "projection", ";", "}" ]
Resolve the fields object, given potentially untrusted fields the user has provided, permitted fields defined by the application, and override fields that should always be provided. @param {String[]} desiredFields The fields in the request. @param {?Object<String, *>=} allowedFields A shallow fields object defining the fields permitted in desiredFields. If not provided, we just allow any field. @param {Object<String, *>=} overrideFields A shallow fields object defining fields that should always be configured as specified. @returns {?Object<String, *>=} The resolved fields declaration.
[ "Resolve", "the", "fields", "object", "given", "potentially", "untrusted", "fields", "the", "user", "has", "provided", "permitted", "fields", "defined", "by", "the", "application", "and", "override", "fields", "that", "should", "always", "be", "provided", "." ]
fa7d2c81012cd0cd08c9338e86bcbfa242f7dd42
https://github.com/mixmaxhq/mongo-cursor-pagination/blob/fa7d2c81012cd0cd08c9338e86bcbfa242f7dd42/src/utils/resolveFields.js#L38-L85
16,528
MitocGroup/deep-framework
src/deep-validation/lib/Helpers/vogelsPolyfill.js
_joiVector
function _joiVector(proto) { let arr = Joi.array(); if (arr.includes) { return arr.includes(proto); } return arr.items(proto); }
javascript
function _joiVector(proto) { let arr = Joi.array(); if (arr.includes) { return arr.includes(proto); } return arr.items(proto); }
[ "function", "_joiVector", "(", "proto", ")", "{", "let", "arr", "=", "Joi", ".", "array", "(", ")", ";", "if", "(", "arr", ".", "includes", ")", "{", "return", "arr", ".", "includes", "(", "proto", ")", ";", "}", "return", "arr", ".", "items", "(", "proto", ")", ";", "}" ]
Fixes weird joi exception! @param {Object} proto @returns {Object} @private
[ "Fixes", "weird", "joi", "exception!" ]
f13b01efefedb3701d10d33138224574dc3189b9
https://github.com/MitocGroup/deep-framework/blob/f13b01efefedb3701d10d33138224574dc3189b9/src/deep-validation/lib/Helpers/vogelsPolyfill.js#L18-L26
16,529
MitocGroup/deep-framework
src/deep-core/lib/Generic/require1k.js
deepLoad
function deepLoad(module, callback, parentLocation, id) { // If this module is already loading then don't proceed. // This is a bug. // If a module is requested but not loaded then the module isn't ready, // but we callback as if it is. Oh well, 1k! if (module.g) { return callback(module.e, module); } var location = module.g = module.l; var request = new XMLHttpRequest(); request.onload = function (deps, count) { if (request.status == 200 || module.t) { // Should really use an object and then Object.keys to avoid // duplicate dependencies. But that costs bytes. deps = []; (module.t = module.t || request.response).replace(/(?:^|[^\w\$_.])require\s*\(\s*["']([^"']*)["']\s*\)/g, function (_, id) { deps.push(id); }); count = deps.length; function loaded() { // We call loaded straight away below in case there // are no dependencies. Putting this check first // and the decrement after saves us an `if` for that // special case if (!count--) { callback(undefined, module); } } deps.map(function (dep) { deepLoad( resolveModuleOrGetExports(module.l, dep), loaded, // If it doesn't begin with a ".", then we're searching // node_modules, so pass in the info to make this // possible dep[0] != "." ? location + "/../" : undefined, dep ); }); loaded(); } else { // parentLocation is only given if we're searching in node_modules if (parentLocation) { // Recurse up the tree trying to find the dependency // (generating 404s on the way) deepLoad( module.n = resolveModuleOrGetExports(parentLocation += "../", id), callback, parentLocation, id ); } else { module.e = request; callback(request, module); } } }; // If the module already has text because we're using a factory // function, then there's no need to load the file! if (module.t) { request.onload(); } else { request.open("GET", location, true); request.send(); } }
javascript
function deepLoad(module, callback, parentLocation, id) { // If this module is already loading then don't proceed. // This is a bug. // If a module is requested but not loaded then the module isn't ready, // but we callback as if it is. Oh well, 1k! if (module.g) { return callback(module.e, module); } var location = module.g = module.l; var request = new XMLHttpRequest(); request.onload = function (deps, count) { if (request.status == 200 || module.t) { // Should really use an object and then Object.keys to avoid // duplicate dependencies. But that costs bytes. deps = []; (module.t = module.t || request.response).replace(/(?:^|[^\w\$_.])require\s*\(\s*["']([^"']*)["']\s*\)/g, function (_, id) { deps.push(id); }); count = deps.length; function loaded() { // We call loaded straight away below in case there // are no dependencies. Putting this check first // and the decrement after saves us an `if` for that // special case if (!count--) { callback(undefined, module); } } deps.map(function (dep) { deepLoad( resolveModuleOrGetExports(module.l, dep), loaded, // If it doesn't begin with a ".", then we're searching // node_modules, so pass in the info to make this // possible dep[0] != "." ? location + "/../" : undefined, dep ); }); loaded(); } else { // parentLocation is only given if we're searching in node_modules if (parentLocation) { // Recurse up the tree trying to find the dependency // (generating 404s on the way) deepLoad( module.n = resolveModuleOrGetExports(parentLocation += "../", id), callback, parentLocation, id ); } else { module.e = request; callback(request, module); } } }; // If the module already has text because we're using a factory // function, then there's no need to load the file! if (module.t) { request.onload(); } else { request.open("GET", location, true); request.send(); } }
[ "function", "deepLoad", "(", "module", ",", "callback", ",", "parentLocation", ",", "id", ")", "{", "// If this module is already loading then don't proceed.", "// This is a bug.", "// If a module is requested but not loaded then the module isn't ready,", "// but we callback as if it is. Oh well, 1k!", "if", "(", "module", ".", "g", ")", "{", "return", "callback", "(", "module", ".", "e", ",", "module", ")", ";", "}", "var", "location", "=", "module", ".", "g", "=", "module", ".", "l", ";", "var", "request", "=", "new", "XMLHttpRequest", "(", ")", ";", "request", ".", "onload", "=", "function", "(", "deps", ",", "count", ")", "{", "if", "(", "request", ".", "status", "==", "200", "||", "module", ".", "t", ")", "{", "// Should really use an object and then Object.keys to avoid", "// duplicate dependencies. But that costs bytes.", "deps", "=", "[", "]", ";", "(", "module", ".", "t", "=", "module", ".", "t", "||", "request", ".", "response", ")", ".", "replace", "(", "/", "(?:^|[^\\w\\$_.])require\\s*\\(\\s*[\"']([^\"']*)[\"']\\s*\\)", "/", "g", ",", "function", "(", "_", ",", "id", ")", "{", "deps", ".", "push", "(", "id", ")", ";", "}", ")", ";", "count", "=", "deps", ".", "length", ";", "function", "loaded", "(", ")", "{", "// We call loaded straight away below in case there", "// are no dependencies. Putting this check first", "// and the decrement after saves us an `if` for that", "// special case", "if", "(", "!", "count", "--", ")", "{", "callback", "(", "undefined", ",", "module", ")", ";", "}", "}", "deps", ".", "map", "(", "function", "(", "dep", ")", "{", "deepLoad", "(", "resolveModuleOrGetExports", "(", "module", ".", "l", ",", "dep", ")", ",", "loaded", ",", "// If it doesn't begin with a \".\", then we're searching", "// node_modules, so pass in the info to make this", "// possible", "dep", "[", "0", "]", "!=", "\".\"", "?", "location", "+", "\"/../\"", ":", "undefined", ",", "dep", ")", ";", "}", ")", ";", "loaded", "(", ")", ";", "}", "else", "{", "// parentLocation is only given if we're searching in node_modules", "if", "(", "parentLocation", ")", "{", "// Recurse up the tree trying to find the dependency", "// (generating 404s on the way)", "deepLoad", "(", "module", ".", "n", "=", "resolveModuleOrGetExports", "(", "parentLocation", "+=", "\"../\"", ",", "id", ")", ",", "callback", ",", "parentLocation", ",", "id", ")", ";", "}", "else", "{", "module", ".", "e", "=", "request", ";", "callback", "(", "request", ",", "module", ")", ";", "}", "}", "}", ";", "// If the module already has text because we're using a factory", "// function, then there's no need to load the file!", "if", "(", "module", ".", "t", ")", "{", "request", ".", "onload", "(", ")", ";", "}", "else", "{", "request", ".", "open", "(", "\"GET\"", ",", "location", ",", "true", ")", ";", "request", ".", "send", "(", ")", ";", "}", "}" ]
Loads the given module and all of it dependencies, recursively - module The module object - callback Called when everything has been loaded - parentLocation Location of the parent directory to look in. Only given for non-relative dependencies - id The name of the dependency. Only used for non-relative dependencies
[ "Loads", "the", "given", "module", "and", "all", "of", "it", "dependencies", "recursively", "-", "module", "The", "module", "object", "-", "callback", "Called", "when", "everything", "has", "been", "loaded", "-", "parentLocation", "Location", "of", "the", "parent", "directory", "to", "look", "in", ".", "Only", "given", "for", "non", "-", "relative", "dependencies", "-", "id", "The", "name", "of", "the", "dependency", ".", "Only", "used", "for", "non", "-", "relative", "dependencies" ]
f13b01efefedb3701d10d33138224574dc3189b9
https://github.com/MitocGroup/deep-framework/blob/f13b01efefedb3701d10d33138224574dc3189b9/src/deep-core/lib/Generic/require1k.js#L44-L112
16,530
MitocGroup/deep-framework
src/deep-core/lib/Generic/require1k.js
resolveModuleOrGetExports
function resolveModuleOrGetExports(baseOrModule, relative, resolved) { // This should really be after the relative check, but because we are // `throw`ing, it messes up the optimizations. If we are being called // as resolveModule then the string `base` won't have the `e` property, // so we're fine. if (baseOrModule.e) { throw baseOrModule.e; } // If 2 arguments are given, then we are resolving modules... if (relative) { baseElement.href = baseOrModule; // If the relative url doesn't begin with a "." or a "/", then it's // in node_modules relativeElement.href = (relative[0] != "." && relative[0] != "/") ? "./node_modules/" + relative : relative; resolved = relativeElement.href.substr(-3).toLowerCase() == ".js" ? relativeElement.href : relativeElement.href + ".js"; baseElement.href = ""; return (MODULES[resolved] = MODULES[resolved] || {l: resolved}); } // ...otherwise we are getting the exports // Is this module a redirect to another one? if (baseOrModule.n) { return resolveModuleOrGetExports(baseOrModule.n); } if (!baseOrModule[tmp]) { (baseOrModule.f || globalEval("(function(require,"+tmp+",module){" + baseOrModule.t + "\n})//# sourceURL=" + baseOrModule.l))( function require (id) { return resolveModuleOrGetExports(resolveModuleOrGetExports(baseOrModule.l, id)); }, // require baseOrModule[tmp] = {}, // exports baseOrModule // module ); } return baseOrModule[tmp]; }
javascript
function resolveModuleOrGetExports(baseOrModule, relative, resolved) { // This should really be after the relative check, but because we are // `throw`ing, it messes up the optimizations. If we are being called // as resolveModule then the string `base` won't have the `e` property, // so we're fine. if (baseOrModule.e) { throw baseOrModule.e; } // If 2 arguments are given, then we are resolving modules... if (relative) { baseElement.href = baseOrModule; // If the relative url doesn't begin with a "." or a "/", then it's // in node_modules relativeElement.href = (relative[0] != "." && relative[0] != "/") ? "./node_modules/" + relative : relative; resolved = relativeElement.href.substr(-3).toLowerCase() == ".js" ? relativeElement.href : relativeElement.href + ".js"; baseElement.href = ""; return (MODULES[resolved] = MODULES[resolved] || {l: resolved}); } // ...otherwise we are getting the exports // Is this module a redirect to another one? if (baseOrModule.n) { return resolveModuleOrGetExports(baseOrModule.n); } if (!baseOrModule[tmp]) { (baseOrModule.f || globalEval("(function(require,"+tmp+",module){" + baseOrModule.t + "\n})//# sourceURL=" + baseOrModule.l))( function require (id) { return resolveModuleOrGetExports(resolveModuleOrGetExports(baseOrModule.l, id)); }, // require baseOrModule[tmp] = {}, // exports baseOrModule // module ); } return baseOrModule[tmp]; }
[ "function", "resolveModuleOrGetExports", "(", "baseOrModule", ",", "relative", ",", "resolved", ")", "{", "// This should really be after the relative check, but because we are", "// `throw`ing, it messes up the optimizations. If we are being called", "// as resolveModule then the string `base` won't have the `e` property,", "// so we're fine.", "if", "(", "baseOrModule", ".", "e", ")", "{", "throw", "baseOrModule", ".", "e", ";", "}", "// If 2 arguments are given, then we are resolving modules...", "if", "(", "relative", ")", "{", "baseElement", ".", "href", "=", "baseOrModule", ";", "// If the relative url doesn't begin with a \".\" or a \"/\", then it's", "// in node_modules", "relativeElement", ".", "href", "=", "(", "relative", "[", "0", "]", "!=", "\".\"", "&&", "relative", "[", "0", "]", "!=", "\"/\"", ")", "?", "\"./node_modules/\"", "+", "relative", ":", "relative", ";", "resolved", "=", "relativeElement", ".", "href", ".", "substr", "(", "-", "3", ")", ".", "toLowerCase", "(", ")", "==", "\".js\"", "?", "relativeElement", ".", "href", ":", "relativeElement", ".", "href", "+", "\".js\"", ";", "baseElement", ".", "href", "=", "\"\"", ";", "return", "(", "MODULES", "[", "resolved", "]", "=", "MODULES", "[", "resolved", "]", "||", "{", "l", ":", "resolved", "}", ")", ";", "}", "// ...otherwise we are getting the exports", "// Is this module a redirect to another one?", "if", "(", "baseOrModule", ".", "n", ")", "{", "return", "resolveModuleOrGetExports", "(", "baseOrModule", ".", "n", ")", ";", "}", "if", "(", "!", "baseOrModule", "[", "tmp", "]", ")", "{", "(", "baseOrModule", ".", "f", "||", "globalEval", "(", "\"(function(require,\"", "+", "tmp", "+", "\",module){\"", "+", "baseOrModule", ".", "t", "+", "\"\\n})//# sourceURL=\"", "+", "baseOrModule", ".", "l", ")", ")", "(", "function", "require", "(", "id", ")", "{", "return", "resolveModuleOrGetExports", "(", "resolveModuleOrGetExports", "(", "baseOrModule", ".", "l", ",", "id", ")", ")", ";", "}", ",", "// require", "baseOrModule", "[", "tmp", "]", "=", "{", "}", ",", "// exports", "baseOrModule", "// module", ")", ";", "}", "return", "baseOrModule", "[", "tmp", "]", ";", "}" ]
Save bytes by combining two functions - resolveModule which resolves a given relative path against the given base, and returns an existing or new module object - getExports which returns the existing exports or runs the factory to create the exports for a module
[ "Save", "bytes", "by", "combining", "two", "functions", "-", "resolveModule", "which", "resolves", "a", "given", "relative", "path", "against", "the", "given", "base", "and", "returns", "an", "existing", "or", "new", "module", "object", "-", "getExports", "which", "returns", "the", "existing", "exports", "or", "runs", "the", "factory", "to", "create", "the", "exports", "for", "a", "module" ]
f13b01efefedb3701d10d33138224574dc3189b9
https://github.com/MitocGroup/deep-framework/blob/f13b01efefedb3701d10d33138224574dc3189b9/src/deep-core/lib/Generic/require1k.js#L119-L161
16,531
generate/generate
index.js
Generate
function Generate(options) { if (!(this instanceof Generate)) { return new Generate(options); } Assemble.call(this, options); this.is('generate'); this.initGenerate(this.options); if (!setArgs) { setArgs = true; this.base.option(utils.argv); } }
javascript
function Generate(options) { if (!(this instanceof Generate)) { return new Generate(options); } Assemble.call(this, options); this.is('generate'); this.initGenerate(this.options); if (!setArgs) { setArgs = true; this.base.option(utils.argv); } }
[ "function", "Generate", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Generate", ")", ")", "{", "return", "new", "Generate", "(", "options", ")", ";", "}", "Assemble", ".", "call", "(", "this", ",", "options", ")", ";", "this", ".", "is", "(", "'generate'", ")", ";", "this", ".", "initGenerate", "(", "this", ".", "options", ")", ";", "if", "(", "!", "setArgs", ")", "{", "setArgs", "=", "true", ";", "this", ".", "base", ".", "option", "(", "utils", ".", "argv", ")", ";", "}", "}" ]
Create an instance of `Generate` with the given `options` ```js var Generate = require('generate'); var generate = new Generate(); ``` @param {Object} `options` Settings to initialize with. @api public
[ "Create", "an", "instance", "of", "Generate", "with", "the", "given", "options" ]
63ab3cf87a61d83806d81541c27308da294c15e8
https://github.com/generate/generate/blob/63ab3cf87a61d83806d81541c27308da294c15e8/index.js#L29-L42
16,532
nylas/nylas-nodejs
example/webhooks/index.js
verify_nylas_request
function verify_nylas_request(req) { const digest = crypto .createHmac('sha256', config.nylasClientSecret) .update(req.rawBody) .digest('hex'); return digest === req.get('x-nylas-signature'); }
javascript
function verify_nylas_request(req) { const digest = crypto .createHmac('sha256', config.nylasClientSecret) .update(req.rawBody) .digest('hex'); return digest === req.get('x-nylas-signature'); }
[ "function", "verify_nylas_request", "(", "req", ")", "{", "const", "digest", "=", "crypto", ".", "createHmac", "(", "'sha256'", ",", "config", ".", "nylasClientSecret", ")", ".", "update", "(", "req", ".", "rawBody", ")", ".", "digest", "(", "'hex'", ")", ";", "return", "digest", "===", "req", ".", "get", "(", "'x-nylas-signature'", ")", ";", "}" ]
Each request made by Nylas includes an X-Nylas-Signature header. The header contains the HMAC-SHA256 signature of the request body, using your client secret as the signing key. This allows your app to verify that the notification really came from Nylas.
[ "Each", "request", "made", "by", "Nylas", "includes", "an", "X", "-", "Nylas", "-", "Signature", "header", ".", "The", "header", "contains", "the", "HMAC", "-", "SHA256", "signature", "of", "the", "request", "body", "using", "your", "client", "secret", "as", "the", "signing", "key", ".", "This", "allows", "your", "app", "to", "verify", "that", "the", "notification", "really", "came", "from", "Nylas", "." ]
a562be663d135562b44b1d6faf61d518859d16d0
https://github.com/nylas/nylas-nodejs/blob/a562be663d135562b44b1d6faf61d518859d16d0/example/webhooks/index.js#L64-L70
16,533
AllenWooooo/rc-datetime-picker
build/build.js
buildUmdDev
function buildUmdDev() { return rollup.rollup({ entry: 'src/index.js', plugins: [ babel(babelOptions) ] }).then(function (bundle) { bundle.generate({ format: 'umd', banner: banner, name: 'rc-datetime-picker' }).then(({ code }) => { return write('dist/rc-datetime-picker.js', code); }); }); }
javascript
function buildUmdDev() { return rollup.rollup({ entry: 'src/index.js', plugins: [ babel(babelOptions) ] }).then(function (bundle) { bundle.generate({ format: 'umd', banner: banner, name: 'rc-datetime-picker' }).then(({ code }) => { return write('dist/rc-datetime-picker.js', code); }); }); }
[ "function", "buildUmdDev", "(", ")", "{", "return", "rollup", ".", "rollup", "(", "{", "entry", ":", "'src/index.js'", ",", "plugins", ":", "[", "babel", "(", "babelOptions", ")", "]", "}", ")", ".", "then", "(", "function", "(", "bundle", ")", "{", "bundle", ".", "generate", "(", "{", "format", ":", "'umd'", ",", "banner", ":", "banner", ",", "name", ":", "'rc-datetime-picker'", "}", ")", ".", "then", "(", "(", "{", "code", "}", ")", "=>", "{", "return", "write", "(", "'dist/rc-datetime-picker.js'", ",", "code", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Standalone development build
[ "Standalone", "development", "build" ]
3cb7b3e4a595047ddac5332ecc055a25187a055a
https://github.com/AllenWooooo/rc-datetime-picker/blob/3cb7b3e4a595047ddac5332ecc055a25187a055a/build/build.js#L55-L70
16,534
nieldlr/hanzi
lib/dictionary.js
determineFreqCategories
function determineFreqCategories() { if (mean - sd < 0) { var lowrange = 0 + mean / 3; } else { var lowrange = mean - sd; } var midrange = [mean + sd, lowrange]; var highrange = mean + sd; var i = 0; for (; i < potentialexamples.length; i++) { var word = potentialexamples[i][0]; if ('undefined' != typeof wordfreq[word.simplified]) { pushFrequency(word); } } function pushFrequency(word) { if (wordfreq[word.simplified] < lowrange) { lowfreq.push(word); } if ( wordfreq[word.simplified] >= midrange[1] && wordfreq[word.simplified] < midrange[0] ) { midfreq.push(word); } if (wordfreq[word.simplified] >= highrange) { highfreq.push(word); } } }
javascript
function determineFreqCategories() { if (mean - sd < 0) { var lowrange = 0 + mean / 3; } else { var lowrange = mean - sd; } var midrange = [mean + sd, lowrange]; var highrange = mean + sd; var i = 0; for (; i < potentialexamples.length; i++) { var word = potentialexamples[i][0]; if ('undefined' != typeof wordfreq[word.simplified]) { pushFrequency(word); } } function pushFrequency(word) { if (wordfreq[word.simplified] < lowrange) { lowfreq.push(word); } if ( wordfreq[word.simplified] >= midrange[1] && wordfreq[word.simplified] < midrange[0] ) { midfreq.push(word); } if (wordfreq[word.simplified] >= highrange) { highfreq.push(word); } } }
[ "function", "determineFreqCategories", "(", ")", "{", "if", "(", "mean", "-", "sd", "<", "0", ")", "{", "var", "lowrange", "=", "0", "+", "mean", "/", "3", ";", "}", "else", "{", "var", "lowrange", "=", "mean", "-", "sd", ";", "}", "var", "midrange", "=", "[", "mean", "+", "sd", ",", "lowrange", "]", ";", "var", "highrange", "=", "mean", "+", "sd", ";", "var", "i", "=", "0", ";", "for", "(", ";", "i", "<", "potentialexamples", ".", "length", ";", "i", "++", ")", "{", "var", "word", "=", "potentialexamples", "[", "i", "]", "[", "0", "]", ";", "if", "(", "'undefined'", "!=", "typeof", "wordfreq", "[", "word", ".", "simplified", "]", ")", "{", "pushFrequency", "(", "word", ")", ";", "}", "}", "function", "pushFrequency", "(", "word", ")", "{", "if", "(", "wordfreq", "[", "word", ".", "simplified", "]", "<", "lowrange", ")", "{", "lowfreq", ".", "push", "(", "word", ")", ";", "}", "if", "(", "wordfreq", "[", "word", ".", "simplified", "]", ">=", "midrange", "[", "1", "]", "&&", "wordfreq", "[", "word", ".", "simplified", "]", "<", "midrange", "[", "0", "]", ")", "{", "midfreq", ".", "push", "(", "word", ")", ";", "}", "if", "(", "wordfreq", "[", "word", ".", "simplified", "]", ">=", "highrange", ")", "{", "highfreq", ".", "push", "(", "word", ")", ";", "}", "}", "}" ]
Create frequency categories
[ "Create", "frequency", "categories" ]
8b80e6d85130c9412117dbc41802cf6add3a74a3
https://github.com/nieldlr/hanzi/blob/8b80e6d85130c9412117dbc41802cf6add3a74a3/lib/dictionary.js#L202-L234
16,535
Kitware/paraviewweb
src/IO/Core/DataManager/request.js
makeRequest
function makeRequest(url, handler) { const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = handler.type; xhr.onload = function onLoad(e) { if (this.status === 200 || this.status === 0) { handler.fn(null, xhr); return; } handler.fn(e, xhr); }; xhr.onerror = function onError(e) { handler.fn(e, xhr); }; xhr.send(); }
javascript
function makeRequest(url, handler) { const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.responseType = handler.type; xhr.onload = function onLoad(e) { if (this.status === 200 || this.status === 0) { handler.fn(null, xhr); return; } handler.fn(e, xhr); }; xhr.onerror = function onError(e) { handler.fn(e, xhr); }; xhr.send(); }
[ "function", "makeRequest", "(", "url", ",", "handler", ")", "{", "const", "xhr", "=", "new", "XMLHttpRequest", "(", ")", ";", "xhr", ".", "open", "(", "'GET'", ",", "url", ",", "true", ")", ";", "xhr", ".", "responseType", "=", "handler", ".", "type", ";", "xhr", ".", "onload", "=", "function", "onLoad", "(", "e", ")", "{", "if", "(", "this", ".", "status", "===", "200", "||", "this", ".", "status", "===", "0", ")", "{", "handler", ".", "fn", "(", "null", ",", "xhr", ")", ";", "return", ";", "}", "handler", ".", "fn", "(", "e", ",", "xhr", ")", ";", "}", ";", "xhr", ".", "onerror", "=", "function", "onError", "(", "e", ")", "{", "handler", ".", "fn", "(", "e", ",", "xhr", ")", ";", "}", ";", "xhr", ".", "send", "(", ")", ";", "}" ]
Generic request handler
[ "Generic", "request", "handler" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/IO/Core/DataManager/request.js#L2-L19
16,536
Kitware/paraviewweb
src/IO/Core/DataManager/request.js
arraybufferHandler
function arraybufferHandler(callback) { return { type: 'arraybuffer', fn: (error, xhrObject) => { if (error) { callback(error); return; } callback(null, xhrObject.response); }, }; }
javascript
function arraybufferHandler(callback) { return { type: 'arraybuffer', fn: (error, xhrObject) => { if (error) { callback(error); return; } callback(null, xhrObject.response); }, }; }
[ "function", "arraybufferHandler", "(", "callback", ")", "{", "return", "{", "type", ":", "'arraybuffer'", ",", "fn", ":", "(", "error", ",", "xhrObject", ")", "=>", "{", "if", "(", "error", ")", "{", "callback", "(", "error", ")", ";", "return", ";", "}", "callback", "(", "null", ",", "xhrObject", ".", "response", ")", ";", "}", ",", "}", ";", "}" ]
Array buffer handler
[ "Array", "buffer", "handler" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/IO/Core/DataManager/request.js#L22-L33
16,537
Kitware/paraviewweb
src/Common/Misc/WebGl/index.js
showGlInfo
function showGlInfo(gl) { const vertexUnits = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); const fragmentUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); const combinedUnits = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); console.log('vertex texture image units:', vertexUnits); console.log('fragment texture image units:', fragmentUnits); console.log('combined texture image units:', combinedUnits); }
javascript
function showGlInfo(gl) { const vertexUnits = gl.getParameter(gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS); const fragmentUnits = gl.getParameter(gl.MAX_TEXTURE_IMAGE_UNITS); const combinedUnits = gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); console.log('vertex texture image units:', vertexUnits); console.log('fragment texture image units:', fragmentUnits); console.log('combined texture image units:', combinedUnits); }
[ "function", "showGlInfo", "(", "gl", ")", "{", "const", "vertexUnits", "=", "gl", ".", "getParameter", "(", "gl", ".", "MAX_VERTEX_TEXTURE_IMAGE_UNITS", ")", ";", "const", "fragmentUnits", "=", "gl", ".", "getParameter", "(", "gl", ".", "MAX_TEXTURE_IMAGE_UNITS", ")", ";", "const", "combinedUnits", "=", "gl", ".", "getParameter", "(", "gl", ".", "MAX_COMBINED_TEXTURE_IMAGE_UNITS", ")", ";", "console", ".", "log", "(", "'vertex texture image units:'", ",", "vertexUnits", ")", ";", "console", ".", "log", "(", "'fragment texture image units:'", ",", "fragmentUnits", ")", ";", "console", ".", "log", "(", "'combined texture image units:'", ",", "combinedUnits", ")", ";", "}" ]
Show GL informations
[ "Show", "GL", "informations" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/Common/Misc/WebGl/index.js#L2-L9
16,538
Kitware/paraviewweb
src/Common/Misc/WebGl/index.js
compileShader
function compileShader(gl, src, type) { const shader = gl.createShader(type); gl.shaderSource(shader, src); // Compile and check status gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { // Something went wrong during compilation; get the error const lastError = gl.getShaderInfoLog(shader); console.error(`Error compiling shader '${shader}': ${lastError}`); gl.deleteShader(shader); return null; } return shader; }
javascript
function compileShader(gl, src, type) { const shader = gl.createShader(type); gl.shaderSource(shader, src); // Compile and check status gl.compileShader(shader); if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) { // Something went wrong during compilation; get the error const lastError = gl.getShaderInfoLog(shader); console.error(`Error compiling shader '${shader}': ${lastError}`); gl.deleteShader(shader); return null; } return shader; }
[ "function", "compileShader", "(", "gl", ",", "src", ",", "type", ")", "{", "const", "shader", "=", "gl", ".", "createShader", "(", "type", ")", ";", "gl", ".", "shaderSource", "(", "shader", ",", "src", ")", ";", "// Compile and check status", "gl", ".", "compileShader", "(", "shader", ")", ";", "if", "(", "!", "gl", ".", "getShaderParameter", "(", "shader", ",", "gl", ".", "COMPILE_STATUS", ")", ")", "{", "// Something went wrong during compilation; get the error", "const", "lastError", "=", "gl", ".", "getShaderInfoLog", "(", "shader", ")", ";", "console", ".", "error", "(", "`", "${", "shader", "}", "${", "lastError", "}", "`", ")", ";", "gl", ".", "deleteShader", "(", "shader", ")", ";", "return", "null", ";", "}", "return", "shader", ";", "}" ]
Compile a shader
[ "Compile", "a", "shader" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/Common/Misc/WebGl/index.js#L12-L29
16,539
Kitware/paraviewweb
src/Common/Misc/WebGl/index.js
applyProgramDataMapping
function applyProgramDataMapping( gl, programName, mappingName, glConfig, glResources ) { const program = glResources.programs[programName]; const mapping = glConfig.mappings[mappingName]; mapping.forEach((bufferMapping) => { const glBuffer = glResources.buffers[bufferMapping.id]; gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer); program[bufferMapping.name] = gl.getAttribLocation( program, bufferMapping.attribute ); gl.enableVertexAttribArray(program[bufferMapping.name]); gl.vertexAttribPointer( program[bufferMapping.name], ...bufferMapping.format ); // FIXME: Remove this check when Apple fixes this bug /* global navigator */ // const buggyBrowserVersion = ['AppleWebKit/602.1.50', 'AppleWebKit/602.2.14']; if (navigator.userAgent.indexOf('AppleWebKit/602') === -1) { gl.bindBuffer(gl.ARRAY_BUFFER, null); } }); }
javascript
function applyProgramDataMapping( gl, programName, mappingName, glConfig, glResources ) { const program = glResources.programs[programName]; const mapping = glConfig.mappings[mappingName]; mapping.forEach((bufferMapping) => { const glBuffer = glResources.buffers[bufferMapping.id]; gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer); program[bufferMapping.name] = gl.getAttribLocation( program, bufferMapping.attribute ); gl.enableVertexAttribArray(program[bufferMapping.name]); gl.vertexAttribPointer( program[bufferMapping.name], ...bufferMapping.format ); // FIXME: Remove this check when Apple fixes this bug /* global navigator */ // const buggyBrowserVersion = ['AppleWebKit/602.1.50', 'AppleWebKit/602.2.14']; if (navigator.userAgent.indexOf('AppleWebKit/602') === -1) { gl.bindBuffer(gl.ARRAY_BUFFER, null); } }); }
[ "function", "applyProgramDataMapping", "(", "gl", ",", "programName", ",", "mappingName", ",", "glConfig", ",", "glResources", ")", "{", "const", "program", "=", "glResources", ".", "programs", "[", "programName", "]", ";", "const", "mapping", "=", "glConfig", ".", "mappings", "[", "mappingName", "]", ";", "mapping", ".", "forEach", "(", "(", "bufferMapping", ")", "=>", "{", "const", "glBuffer", "=", "glResources", ".", "buffers", "[", "bufferMapping", ".", "id", "]", ";", "gl", ".", "bindBuffer", "(", "gl", ".", "ARRAY_BUFFER", ",", "glBuffer", ")", ";", "program", "[", "bufferMapping", ".", "name", "]", "=", "gl", ".", "getAttribLocation", "(", "program", ",", "bufferMapping", ".", "attribute", ")", ";", "gl", ".", "enableVertexAttribArray", "(", "program", "[", "bufferMapping", ".", "name", "]", ")", ";", "gl", ".", "vertexAttribPointer", "(", "program", "[", "bufferMapping", ".", "name", "]", ",", "...", "bufferMapping", ".", "format", ")", ";", "// FIXME: Remove this check when Apple fixes this bug", "/* global navigator */", "// const buggyBrowserVersion = ['AppleWebKit/602.1.50', 'AppleWebKit/602.2.14'];", "if", "(", "navigator", ".", "userAgent", ".", "indexOf", "(", "'AppleWebKit/602'", ")", "===", "-", "1", ")", "{", "gl", ".", "bindBuffer", "(", "gl", ".", "ARRAY_BUFFER", ",", "null", ")", ";", "}", "}", ")", ";", "}" ]
Apply new mapping to a program
[ "Apply", "new", "mapping", "to", "a", "program" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/Common/Misc/WebGl/index.js#L59-L89
16,540
Kitware/paraviewweb
src/Common/Misc/WebGl/index.js
bindTextureToFramebuffer
function bindTextureToFramebuffer(gl, fbo, texture) { gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, fbo.width, fbo.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0 ); // Check fbo status const fbs = gl.checkFramebufferStatus(gl.FRAMEBUFFER); if (fbs !== gl.FRAMEBUFFER_COMPLETE) { console.log('ERROR: There is a problem with the framebuffer:', fbs); } // Clear the bindings we created in this function. gl.bindTexture(gl.TEXTURE_2D, null); gl.bindFramebuffer(gl.FRAMEBUFFER, null); }
javascript
function bindTextureToFramebuffer(gl, fbo, texture) { gl.bindFramebuffer(gl.FRAMEBUFFER, fbo); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texImage2D( gl.TEXTURE_2D, 0, gl.RGBA, fbo.width, fbo.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null ); gl.framebufferTexture2D( gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0 ); // Check fbo status const fbs = gl.checkFramebufferStatus(gl.FRAMEBUFFER); if (fbs !== gl.FRAMEBUFFER_COMPLETE) { console.log('ERROR: There is a problem with the framebuffer:', fbs); } // Clear the bindings we created in this function. gl.bindTexture(gl.TEXTURE_2D, null); gl.bindFramebuffer(gl.FRAMEBUFFER, null); }
[ "function", "bindTextureToFramebuffer", "(", "gl", ",", "fbo", ",", "texture", ")", "{", "gl", ".", "bindFramebuffer", "(", "gl", ".", "FRAMEBUFFER", ",", "fbo", ")", ";", "gl", ".", "bindTexture", "(", "gl", ".", "TEXTURE_2D", ",", "texture", ")", ";", "gl", ".", "texImage2D", "(", "gl", ".", "TEXTURE_2D", ",", "0", ",", "gl", ".", "RGBA", ",", "fbo", ".", "width", ",", "fbo", ".", "height", ",", "0", ",", "gl", ".", "RGBA", ",", "gl", ".", "UNSIGNED_BYTE", ",", "null", ")", ";", "gl", ".", "framebufferTexture2D", "(", "gl", ".", "FRAMEBUFFER", ",", "gl", ".", "COLOR_ATTACHMENT0", ",", "gl", ".", "TEXTURE_2D", ",", "texture", ",", "0", ")", ";", "// Check fbo status", "const", "fbs", "=", "gl", ".", "checkFramebufferStatus", "(", "gl", ".", "FRAMEBUFFER", ")", ";", "if", "(", "fbs", "!==", "gl", ".", "FRAMEBUFFER_COMPLETE", ")", "{", "console", ".", "log", "(", "'ERROR: There is a problem with the framebuffer:'", ",", "fbs", ")", ";", "}", "// Clear the bindings we created in this function.", "gl", ".", "bindTexture", "(", "gl", ".", "TEXTURE_2D", ",", "null", ")", ";", "gl", ".", "bindFramebuffer", "(", "gl", ".", "FRAMEBUFFER", ",", "null", ")", ";", "}" ]
Bind texture to Framebuffer
[ "Bind", "texture", "to", "Framebuffer" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/Common/Misc/WebGl/index.js#L122-L155
16,541
Kitware/paraviewweb
src/Common/Misc/WebGl/index.js
freeGLResources
function freeGLResources(glResources) { const gl = glResources.gl; // Delete each program Object.keys(glResources.programs).forEach((programName) => { const program = glResources.programs[programName]; const shaders = program.shaders; let count = shaders.length; // Delete shaders while (count) { count -= 1; gl.deleteShader(shaders[count]); } // Delete program gl.deleteProgram(program); }); // Delete framebuffers Object.keys(glResources.framebuffers).forEach((fbName) => { gl.deleteFramebuffer(glResources.framebuffers[fbName]); }); // Delete textures Object.keys(glResources.textures).forEach((textureName) => { gl.deleteTexture(glResources.textures[textureName]); }); // Delete buffers Object.keys(glResources.buffers).forEach((bufferName) => { gl.deleteBuffer(glResources.buffers[bufferName]); }); }
javascript
function freeGLResources(glResources) { const gl = glResources.gl; // Delete each program Object.keys(glResources.programs).forEach((programName) => { const program = glResources.programs[programName]; const shaders = program.shaders; let count = shaders.length; // Delete shaders while (count) { count -= 1; gl.deleteShader(shaders[count]); } // Delete program gl.deleteProgram(program); }); // Delete framebuffers Object.keys(glResources.framebuffers).forEach((fbName) => { gl.deleteFramebuffer(glResources.framebuffers[fbName]); }); // Delete textures Object.keys(glResources.textures).forEach((textureName) => { gl.deleteTexture(glResources.textures[textureName]); }); // Delete buffers Object.keys(glResources.buffers).forEach((bufferName) => { gl.deleteBuffer(glResources.buffers[bufferName]); }); }
[ "function", "freeGLResources", "(", "glResources", ")", "{", "const", "gl", "=", "glResources", ".", "gl", ";", "// Delete each program", "Object", ".", "keys", "(", "glResources", ".", "programs", ")", ".", "forEach", "(", "(", "programName", ")", "=>", "{", "const", "program", "=", "glResources", ".", "programs", "[", "programName", "]", ";", "const", "shaders", "=", "program", ".", "shaders", ";", "let", "count", "=", "shaders", ".", "length", ";", "// Delete shaders", "while", "(", "count", ")", "{", "count", "-=", "1", ";", "gl", ".", "deleteShader", "(", "shaders", "[", "count", "]", ")", ";", "}", "// Delete program", "gl", ".", "deleteProgram", "(", "program", ")", ";", "}", ")", ";", "// Delete framebuffers", "Object", ".", "keys", "(", "glResources", ".", "framebuffers", ")", ".", "forEach", "(", "(", "fbName", ")", "=>", "{", "gl", ".", "deleteFramebuffer", "(", "glResources", ".", "framebuffers", "[", "fbName", "]", ")", ";", "}", ")", ";", "// Delete textures", "Object", ".", "keys", "(", "glResources", ".", "textures", ")", ".", "forEach", "(", "(", "textureName", ")", "=>", "{", "gl", ".", "deleteTexture", "(", "glResources", ".", "textures", "[", "textureName", "]", ")", ";", "}", ")", ";", "// Delete buffers", "Object", ".", "keys", "(", "glResources", ".", "buffers", ")", ".", "forEach", "(", "(", "bufferName", ")", "=>", "{", "gl", ".", "deleteBuffer", "(", "glResources", ".", "buffers", "[", "bufferName", "]", ")", ";", "}", ")", ";", "}" ]
Free GL resources
[ "Free", "GL", "resources" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/Common/Misc/WebGl/index.js#L158-L192
16,542
Kitware/paraviewweb
src/Common/Misc/WebGl/index.js
createGLResources
function createGLResources(gl, glConfig) { const resources = { gl, buffers: {}, textures: {}, framebuffers: {}, programs: {}, }; const buffers = glConfig.resources.buffers || []; const textures = glConfig.resources.textures || []; const framebuffers = glConfig.resources.framebuffers || []; // Create Buffer buffers.forEach((buffer) => { const glBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer); gl.bufferData(gl.ARRAY_BUFFER, buffer.data, gl.STATIC_DRAW); resources.buffers[buffer.id] = glBuffer; }); // Create Texture textures.forEach((texture) => { const glTexture = gl.createTexture(); const pixelStore = texture.pixelStore || []; const texParameter = texture.texParameter || []; gl.bindTexture(gl.TEXTURE_2D, glTexture); pixelStore.forEach((option) => { gl.pixelStorei(gl[option[0]], option[1]); }); texParameter.forEach((option) => { gl.texParameteri(gl.TEXTURE_2D, gl[option[0]], gl[option[1]]); }); resources.textures[texture.id] = glTexture; }); // Create Framebuffer framebuffers.forEach((framebuffer) => { const glFramebuffer = gl.createFramebuffer(); glFramebuffer.width = framebuffer.width; glFramebuffer.height = framebuffer.height; resources.framebuffers[framebuffer.id] = glFramebuffer; }); // Create programs Object.keys(glConfig.programs).forEach((programName) => { buildShaderProgram(gl, programName, glConfig, resources); }); // Add destroy function resources.destroy = () => { freeGLResources(resources); }; return resources; }
javascript
function createGLResources(gl, glConfig) { const resources = { gl, buffers: {}, textures: {}, framebuffers: {}, programs: {}, }; const buffers = glConfig.resources.buffers || []; const textures = glConfig.resources.textures || []; const framebuffers = glConfig.resources.framebuffers || []; // Create Buffer buffers.forEach((buffer) => { const glBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, glBuffer); gl.bufferData(gl.ARRAY_BUFFER, buffer.data, gl.STATIC_DRAW); resources.buffers[buffer.id] = glBuffer; }); // Create Texture textures.forEach((texture) => { const glTexture = gl.createTexture(); const pixelStore = texture.pixelStore || []; const texParameter = texture.texParameter || []; gl.bindTexture(gl.TEXTURE_2D, glTexture); pixelStore.forEach((option) => { gl.pixelStorei(gl[option[0]], option[1]); }); texParameter.forEach((option) => { gl.texParameteri(gl.TEXTURE_2D, gl[option[0]], gl[option[1]]); }); resources.textures[texture.id] = glTexture; }); // Create Framebuffer framebuffers.forEach((framebuffer) => { const glFramebuffer = gl.createFramebuffer(); glFramebuffer.width = framebuffer.width; glFramebuffer.height = framebuffer.height; resources.framebuffers[framebuffer.id] = glFramebuffer; }); // Create programs Object.keys(glConfig.programs).forEach((programName) => { buildShaderProgram(gl, programName, glConfig, resources); }); // Add destroy function resources.destroy = () => { freeGLResources(resources); }; return resources; }
[ "function", "createGLResources", "(", "gl", ",", "glConfig", ")", "{", "const", "resources", "=", "{", "gl", ",", "buffers", ":", "{", "}", ",", "textures", ":", "{", "}", ",", "framebuffers", ":", "{", "}", ",", "programs", ":", "{", "}", ",", "}", ";", "const", "buffers", "=", "glConfig", ".", "resources", ".", "buffers", "||", "[", "]", ";", "const", "textures", "=", "glConfig", ".", "resources", ".", "textures", "||", "[", "]", ";", "const", "framebuffers", "=", "glConfig", ".", "resources", ".", "framebuffers", "||", "[", "]", ";", "// Create Buffer", "buffers", ".", "forEach", "(", "(", "buffer", ")", "=>", "{", "const", "glBuffer", "=", "gl", ".", "createBuffer", "(", ")", ";", "gl", ".", "bindBuffer", "(", "gl", ".", "ARRAY_BUFFER", ",", "glBuffer", ")", ";", "gl", ".", "bufferData", "(", "gl", ".", "ARRAY_BUFFER", ",", "buffer", ".", "data", ",", "gl", ".", "STATIC_DRAW", ")", ";", "resources", ".", "buffers", "[", "buffer", ".", "id", "]", "=", "glBuffer", ";", "}", ")", ";", "// Create Texture", "textures", ".", "forEach", "(", "(", "texture", ")", "=>", "{", "const", "glTexture", "=", "gl", ".", "createTexture", "(", ")", ";", "const", "pixelStore", "=", "texture", ".", "pixelStore", "||", "[", "]", ";", "const", "texParameter", "=", "texture", ".", "texParameter", "||", "[", "]", ";", "gl", ".", "bindTexture", "(", "gl", ".", "TEXTURE_2D", ",", "glTexture", ")", ";", "pixelStore", ".", "forEach", "(", "(", "option", ")", "=>", "{", "gl", ".", "pixelStorei", "(", "gl", "[", "option", "[", "0", "]", "]", ",", "option", "[", "1", "]", ")", ";", "}", ")", ";", "texParameter", ".", "forEach", "(", "(", "option", ")", "=>", "{", "gl", ".", "texParameteri", "(", "gl", ".", "TEXTURE_2D", ",", "gl", "[", "option", "[", "0", "]", "]", ",", "gl", "[", "option", "[", "1", "]", "]", ")", ";", "}", ")", ";", "resources", ".", "textures", "[", "texture", ".", "id", "]", "=", "glTexture", ";", "}", ")", ";", "// Create Framebuffer", "framebuffers", ".", "forEach", "(", "(", "framebuffer", ")", "=>", "{", "const", "glFramebuffer", "=", "gl", ".", "createFramebuffer", "(", ")", ";", "glFramebuffer", ".", "width", "=", "framebuffer", ".", "width", ";", "glFramebuffer", ".", "height", "=", "framebuffer", ".", "height", ";", "resources", ".", "framebuffers", "[", "framebuffer", ".", "id", "]", "=", "glFramebuffer", ";", "}", ")", ";", "// Create programs", "Object", ".", "keys", "(", "glConfig", ".", "programs", ")", ".", "forEach", "(", "(", "programName", ")", "=>", "{", "buildShaderProgram", "(", "gl", ",", "programName", ",", "glConfig", ",", "resources", ")", ";", "}", ")", ";", "// Add destroy function", "resources", ".", "destroy", "=", "(", ")", "=>", "{", "freeGLResources", "(", "resources", ")", ";", "}", ";", "return", "resources", ";", "}" ]
Create GL resources
[ "Create", "GL", "resources" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/Common/Misc/WebGl/index.js#L195-L254
16,543
Kitware/paraviewweb
src/InfoViz/Native/HistogramSelector/index.js
styleRows
function styleRows(selection, self) { selection .classed(style.row, true) .style('height', `${self.rowHeight}px`) .style( transformCSSProp, (d, i) => `translate3d(0,${d.key * self.rowHeight}px,0)` ); }
javascript
function styleRows(selection, self) { selection .classed(style.row, true) .style('height', `${self.rowHeight}px`) .style( transformCSSProp, (d, i) => `translate3d(0,${d.key * self.rowHeight}px,0)` ); }
[ "function", "styleRows", "(", "selection", ",", "self", ")", "{", "selection", ".", "classed", "(", "style", ".", "row", ",", "true", ")", ".", "style", "(", "'height'", ",", "`", "${", "self", ".", "rowHeight", "}", "`", ")", ".", "style", "(", "transformCSSProp", ",", "(", "d", ",", "i", ")", "=>", "`", "${", "d", ".", "key", "*", "self", ".", "rowHeight", "}", "`", ")", ";", "}" ]
Apply our desired attributes to the grid rows
[ "Apply", "our", "desired", "attributes", "to", "the", "grid", "rows" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/InfoViz/Native/HistogramSelector/index.js#L81-L89
16,544
Kitware/paraviewweb
src/InfoViz/Native/HistogramSelector/index.js
styleBoxes
function styleBoxes(selection, self) { selection .style('width', `${self.boxWidth}px`) .style('height', `${self.boxHeight}px`); // .style('margin', `${self.boxMargin / 2}px`) }
javascript
function styleBoxes(selection, self) { selection .style('width', `${self.boxWidth}px`) .style('height', `${self.boxHeight}px`); // .style('margin', `${self.boxMargin / 2}px`) }
[ "function", "styleBoxes", "(", "selection", ",", "self", ")", "{", "selection", ".", "style", "(", "'width'", ",", "`", "${", "self", ".", "boxWidth", "}", "`", ")", ".", "style", "(", "'height'", ",", "`", "${", "self", ".", "boxHeight", "}", "`", ")", ";", "// .style('margin', `${self.boxMargin / 2}px`)", "}" ]
apply our desired attributes to the boxes of a row
[ "apply", "our", "desired", "attributes", "to", "the", "boxes", "of", "a", "row" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/InfoViz/Native/HistogramSelector/index.js#L92-L97
16,545
Kitware/paraviewweb
src/InfoViz/Native/HistogramSelector/index.js
getFieldRow
function getFieldRow(name) { if (model.nest === null) return 0; const foundRow = model.nest.reduce((prev, item, i) => { const val = item.value.filter((def) => def.name === name); if (val.length > 0) { return item.key; } return prev; }, 0); return foundRow; }
javascript
function getFieldRow(name) { if (model.nest === null) return 0; const foundRow = model.nest.reduce((prev, item, i) => { const val = item.value.filter((def) => def.name === name); if (val.length > 0) { return item.key; } return prev; }, 0); return foundRow; }
[ "function", "getFieldRow", "(", "name", ")", "{", "if", "(", "model", ".", "nest", "===", "null", ")", "return", "0", ";", "const", "foundRow", "=", "model", ".", "nest", ".", "reduce", "(", "(", "prev", ",", "item", ",", "i", ")", "=>", "{", "const", "val", "=", "item", ".", "value", ".", "filter", "(", "(", "def", ")", "=>", "def", ".", "name", "===", "name", ")", ";", "if", "(", "val", ".", "length", ">", "0", ")", "{", "return", "item", ".", "key", ";", "}", "return", "prev", ";", "}", ",", "0", ")", ";", "return", "foundRow", ";", "}" ]
which row of model.nest does this field name reside in?
[ "which", "row", "of", "model", ".", "nest", "does", "this", "field", "name", "reside", "in?" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/InfoViz/Native/HistogramSelector/index.js#L161-L171
16,546
Kitware/paraviewweb
src/InfoViz/Native/MutualInformationDiagram/index.js
updateStatusBarVisibility
function updateStatusBarVisibility() { const cntnr = d3.select(model.container); if (model.statusBarVisible) { cntnr .select('.status-bar-container') .style('width', function updateWidth() { return this.dataset.width; }); cntnr.select('.show-button').classed(style.hidden, true); cntnr.select('.hide-button').classed(style.hidden, false); cntnr.select('.status-bar-text').classed(style.hidden, false); } else { cntnr.select('.status-bar-container').style('width', '20px'); cntnr.select('.show-button').classed(style.hidden, false); cntnr.select('.hide-button').classed(style.hidden, true); cntnr.select('.status-bar-text').classed(style.hidden, true); } }
javascript
function updateStatusBarVisibility() { const cntnr = d3.select(model.container); if (model.statusBarVisible) { cntnr .select('.status-bar-container') .style('width', function updateWidth() { return this.dataset.width; }); cntnr.select('.show-button').classed(style.hidden, true); cntnr.select('.hide-button').classed(style.hidden, false); cntnr.select('.status-bar-text').classed(style.hidden, false); } else { cntnr.select('.status-bar-container').style('width', '20px'); cntnr.select('.show-button').classed(style.hidden, false); cntnr.select('.hide-button').classed(style.hidden, true); cntnr.select('.status-bar-text').classed(style.hidden, true); } }
[ "function", "updateStatusBarVisibility", "(", ")", "{", "const", "cntnr", "=", "d3", ".", "select", "(", "model", ".", "container", ")", ";", "if", "(", "model", ".", "statusBarVisible", ")", "{", "cntnr", ".", "select", "(", "'.status-bar-container'", ")", ".", "style", "(", "'width'", ",", "function", "updateWidth", "(", ")", "{", "return", "this", ".", "dataset", ".", "width", ";", "}", ")", ";", "cntnr", ".", "select", "(", "'.show-button'", ")", ".", "classed", "(", "style", ".", "hidden", ",", "true", ")", ";", "cntnr", ".", "select", "(", "'.hide-button'", ")", ".", "classed", "(", "style", ".", "hidden", ",", "false", ")", ";", "cntnr", ".", "select", "(", "'.status-bar-text'", ")", ".", "classed", "(", "style", ".", "hidden", ",", "false", ")", ";", "}", "else", "{", "cntnr", ".", "select", "(", "'.status-bar-container'", ")", ".", "style", "(", "'width'", ",", "'20px'", ")", ";", "cntnr", ".", "select", "(", "'.show-button'", ")", ".", "classed", "(", "style", ".", "hidden", ",", "false", ")", ";", "cntnr", ".", "select", "(", "'.hide-button'", ")", ".", "classed", "(", "style", ".", "hidden", ",", "true", ")", ";", "cntnr", ".", "select", "(", "'.status-bar-text'", ")", ".", "classed", "(", "style", ".", "hidden", ",", "true", ")", ";", "}", "}" ]
Handle style for status bar
[ "Handle", "style", "for", "status", "bar" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/InfoViz/Native/MutualInformationDiagram/index.js#L58-L75
16,547
Kitware/paraviewweb
src/InfoViz/Native/MutualInformationDiagram/index.js
singleClick
function singleClick(d, i) { // single click handler const overCoords = d3.mouse(model.container); const info = findGroupAndBin(overCoords); if (info.radius > veryOutermostRadius) { showAllChords(); } else if ( info.radius > outerRadius || (info.radius <= innerRadius && pmiChordMode.mode === PMI_CHORD_MODE_ONE_BIN_ALL_VARS && info.group === pmiChordMode.srcParam) ) { if (info.found) { model.renderState.pmiAllBinsTwoVars = null; model.renderState.pmiOneBinAllVars = { group: info.group, bin: info.bin, d, i, }; drawPMIOneBinAllVars()(d, i); publicAPI.selectStatusBarText(); } } // }, }
javascript
function singleClick(d, i) { // single click handler const overCoords = d3.mouse(model.container); const info = findGroupAndBin(overCoords); if (info.radius > veryOutermostRadius) { showAllChords(); } else if ( info.radius > outerRadius || (info.radius <= innerRadius && pmiChordMode.mode === PMI_CHORD_MODE_ONE_BIN_ALL_VARS && info.group === pmiChordMode.srcParam) ) { if (info.found) { model.renderState.pmiAllBinsTwoVars = null; model.renderState.pmiOneBinAllVars = { group: info.group, bin: info.bin, d, i, }; drawPMIOneBinAllVars()(d, i); publicAPI.selectStatusBarText(); } } // }, }
[ "function", "singleClick", "(", "d", ",", "i", ")", "{", "// single click handler", "const", "overCoords", "=", "d3", ".", "mouse", "(", "model", ".", "container", ")", ";", "const", "info", "=", "findGroupAndBin", "(", "overCoords", ")", ";", "if", "(", "info", ".", "radius", ">", "veryOutermostRadius", ")", "{", "showAllChords", "(", ")", ";", "}", "else", "if", "(", "info", ".", "radius", ">", "outerRadius", "||", "(", "info", ".", "radius", "<=", "innerRadius", "&&", "pmiChordMode", ".", "mode", "===", "PMI_CHORD_MODE_ONE_BIN_ALL_VARS", "&&", "info", ".", "group", "===", "pmiChordMode", ".", "srcParam", ")", ")", "{", "if", "(", "info", ".", "found", ")", "{", "model", ".", "renderState", ".", "pmiAllBinsTwoVars", "=", "null", ";", "model", ".", "renderState", ".", "pmiOneBinAllVars", "=", "{", "group", ":", "info", ".", "group", ",", "bin", ":", "info", ".", "bin", ",", "d", ",", "i", ",", "}", ";", "drawPMIOneBinAllVars", "(", ")", "(", "d", ",", "i", ")", ";", "publicAPI", ".", "selectStatusBarText", "(", ")", ";", "}", "}", "// },", "}" ]
multiClicker([
[ "multiClicker", "(", "[" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/InfoViz/Native/MutualInformationDiagram/index.js#L748-L773
16,548
Kitware/paraviewweb
src/Common/Core/CompositeClosureHelper/index.js
flushDataToListener
function flushDataToListener(dataListener, dataChanged) { try { if (dataListener) { const dataToForward = dataHandler.get( model[dataContainerName], dataListener.request, dataChanged ); if ( dataToForward && (JSON.stringify(dataToForward) !== dataListener.request.lastPush || dataListener.request.metadata.forceFlush) ) { dataListener.request.lastPush = JSON.stringify(dataToForward); dataListener.onDataReady(dataToForward); } } } catch (err) { console.log(`flush ${dataName} error caught:`, err); } }
javascript
function flushDataToListener(dataListener, dataChanged) { try { if (dataListener) { const dataToForward = dataHandler.get( model[dataContainerName], dataListener.request, dataChanged ); if ( dataToForward && (JSON.stringify(dataToForward) !== dataListener.request.lastPush || dataListener.request.metadata.forceFlush) ) { dataListener.request.lastPush = JSON.stringify(dataToForward); dataListener.onDataReady(dataToForward); } } } catch (err) { console.log(`flush ${dataName} error caught:`, err); } }
[ "function", "flushDataToListener", "(", "dataListener", ",", "dataChanged", ")", "{", "try", "{", "if", "(", "dataListener", ")", "{", "const", "dataToForward", "=", "dataHandler", ".", "get", "(", "model", "[", "dataContainerName", "]", ",", "dataListener", ".", "request", ",", "dataChanged", ")", ";", "if", "(", "dataToForward", "&&", "(", "JSON", ".", "stringify", "(", "dataToForward", ")", "!==", "dataListener", ".", "request", ".", "lastPush", "||", "dataListener", ".", "request", ".", "metadata", ".", "forceFlush", ")", ")", "{", "dataListener", ".", "request", ".", "lastPush", "=", "JSON", ".", "stringify", "(", "dataToForward", ")", ";", "dataListener", ".", "onDataReady", "(", "dataToForward", ")", ";", "}", "}", "}", "catch", "(", "err", ")", "{", "console", ".", "log", "(", "`", "${", "dataName", "}", "`", ",", "err", ")", ";", "}", "}" ]
Internal function that will notify any subscriber with its data in a synchronous manner
[ "Internal", "function", "that", "will", "notify", "any", "subscriber", "with", "its", "data", "in", "a", "synchronous", "manner" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/Common/Core/CompositeClosureHelper/index.js#L269-L289
16,549
Kitware/paraviewweb
src/React/Containers/OverlayWindow/index.js
getMouseEventInfo
function getMouseEventInfo(event, divElt) { const clientRect = divElt.getBoundingClientRect(); return { relX: event.clientX - clientRect.left, relY: event.clientY - clientRect.top, eltBounds: clientRect, }; }
javascript
function getMouseEventInfo(event, divElt) { const clientRect = divElt.getBoundingClientRect(); return { relX: event.clientX - clientRect.left, relY: event.clientY - clientRect.top, eltBounds: clientRect, }; }
[ "function", "getMouseEventInfo", "(", "event", ",", "divElt", ")", "{", "const", "clientRect", "=", "divElt", ".", "getBoundingClientRect", "(", ")", ";", "return", "{", "relX", ":", "event", ".", "clientX", "-", "clientRect", ".", "left", ",", "relY", ":", "event", ".", "clientY", "-", "clientRect", ".", "top", ",", "eltBounds", ":", "clientRect", ",", "}", ";", "}" ]
Return extra information about the target element bounds
[ "Return", "extra", "information", "about", "the", "target", "element", "bounds" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/React/Containers/OverlayWindow/index.js#L19-L26
16,550
Kitware/paraviewweb
src/React/Widgets/SelectionEditorWidget/rule/index.js
ensureRuleNumbers
function ensureRuleNumbers(rule) { if (!rule || rule.length === 0) { return; } const ruleSelector = rule.type; if (ruleSelector === 'rule') { ensureRuleNumbers(rule.rule); } if (ruleSelector === 'logical') { rule.terms.filter((r, idx) => idx > 0).forEach((r) => ensureRuleNumbers(r)); } if (ruleSelector === '5C') { const terms = rule.terms; terms[0] = Number(terms[0]); terms[4] = Number(terms[4]); } }
javascript
function ensureRuleNumbers(rule) { if (!rule || rule.length === 0) { return; } const ruleSelector = rule.type; if (ruleSelector === 'rule') { ensureRuleNumbers(rule.rule); } if (ruleSelector === 'logical') { rule.terms.filter((r, idx) => idx > 0).forEach((r) => ensureRuleNumbers(r)); } if (ruleSelector === '5C') { const terms = rule.terms; terms[0] = Number(terms[0]); terms[4] = Number(terms[4]); } }
[ "function", "ensureRuleNumbers", "(", "rule", ")", "{", "if", "(", "!", "rule", "||", "rule", ".", "length", "===", "0", ")", "{", "return", ";", "}", "const", "ruleSelector", "=", "rule", ".", "type", ";", "if", "(", "ruleSelector", "===", "'rule'", ")", "{", "ensureRuleNumbers", "(", "rule", ".", "rule", ")", ";", "}", "if", "(", "ruleSelector", "===", "'logical'", ")", "{", "rule", ".", "terms", ".", "filter", "(", "(", "r", ",", "idx", ")", "=>", "idx", ">", "0", ")", ".", "forEach", "(", "(", "r", ")", "=>", "ensureRuleNumbers", "(", "r", ")", ")", ";", "}", "if", "(", "ruleSelector", "===", "'5C'", ")", "{", "const", "terms", "=", "rule", ".", "terms", ";", "terms", "[", "0", "]", "=", "Number", "(", "terms", "[", "0", "]", ")", ";", "terms", "[", "4", "]", "=", "Number", "(", "terms", "[", "4", "]", ")", ";", "}", "}" ]
Edit in place
[ "Edit", "in", "place" ]
ebff9dbeefee70225c349077e25280c56d39920e
https://github.com/Kitware/paraviewweb/blob/ebff9dbeefee70225c349077e25280c56d39920e/src/React/Widgets/SelectionEditorWidget/rule/index.js#L27-L45
16,551
CartoDB/odyssey.js
lib/odyssey/template.js
md2json
function md2json(tree) { var slide = null; var slides = []; var globalProperties = {} var elements = tree.slice(1); for (var i = 0; i < elements.length; ++i) { var el = elements[i]; var add = true; if (el[0] === 'header' && el[1].level === 1) { if (slide) slides.push(Slide(slide.md_tree, slide.actions, slide.properties)); slide = { md_tree: [], html: '', actions: [], properties: {} }; } else if (el[0] === 'para') { // search inline code inside it var actions = []; for(var j = 1; j < el.length; ++j) { var subel = el[j]; if (subel[0] === "inlinecode") { var lines = subel[1].split('\n'); for (var ln = 0; ln < lines.length; ++ln) { var line = lines[ln]; if (trim(line) !== '') { // if matches property, parse it if (prop_re.exec(line)) { var p = parseProperties(subel[1]); var prop = slide ? slide.properties: globalProperties for(var k in p) { prop[k] = { order: ln, value: p[k] } } } else { slide && slide.actions.push({ cmd: line, order: ln }); } } } // remove from list el.splice(j, 1); --j; } } } add && slide && slide.md_tree.push(el); } if (slide) slides.push(Slide(slide.md_tree, slide.actions, slide.properties)); // remove the order for globalProperties slides.global = {}; for(var k in globalProperties) { slides.global[k] = globalProperties[k].value; } return slides; }
javascript
function md2json(tree) { var slide = null; var slides = []; var globalProperties = {} var elements = tree.slice(1); for (var i = 0; i < elements.length; ++i) { var el = elements[i]; var add = true; if (el[0] === 'header' && el[1].level === 1) { if (slide) slides.push(Slide(slide.md_tree, slide.actions, slide.properties)); slide = { md_tree: [], html: '', actions: [], properties: {} }; } else if (el[0] === 'para') { // search inline code inside it var actions = []; for(var j = 1; j < el.length; ++j) { var subel = el[j]; if (subel[0] === "inlinecode") { var lines = subel[1].split('\n'); for (var ln = 0; ln < lines.length; ++ln) { var line = lines[ln]; if (trim(line) !== '') { // if matches property, parse it if (prop_re.exec(line)) { var p = parseProperties(subel[1]); var prop = slide ? slide.properties: globalProperties for(var k in p) { prop[k] = { order: ln, value: p[k] } } } else { slide && slide.actions.push({ cmd: line, order: ln }); } } } // remove from list el.splice(j, 1); --j; } } } add && slide && slide.md_tree.push(el); } if (slide) slides.push(Slide(slide.md_tree, slide.actions, slide.properties)); // remove the order for globalProperties slides.global = {}; for(var k in globalProperties) { slides.global[k] = globalProperties[k].value; } return slides; }
[ "function", "md2json", "(", "tree", ")", "{", "var", "slide", "=", "null", ";", "var", "slides", "=", "[", "]", ";", "var", "globalProperties", "=", "{", "}", "var", "elements", "=", "tree", ".", "slice", "(", "1", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "elements", ".", "length", ";", "++", "i", ")", "{", "var", "el", "=", "elements", "[", "i", "]", ";", "var", "add", "=", "true", ";", "if", "(", "el", "[", "0", "]", "===", "'header'", "&&", "el", "[", "1", "]", ".", "level", "===", "1", ")", "{", "if", "(", "slide", ")", "slides", ".", "push", "(", "Slide", "(", "slide", ".", "md_tree", ",", "slide", ".", "actions", ",", "slide", ".", "properties", ")", ")", ";", "slide", "=", "{", "md_tree", ":", "[", "]", ",", "html", ":", "''", ",", "actions", ":", "[", "]", ",", "properties", ":", "{", "}", "}", ";", "}", "else", "if", "(", "el", "[", "0", "]", "===", "'para'", ")", "{", "// search inline code inside it", "var", "actions", "=", "[", "]", ";", "for", "(", "var", "j", "=", "1", ";", "j", "<", "el", ".", "length", ";", "++", "j", ")", "{", "var", "subel", "=", "el", "[", "j", "]", ";", "if", "(", "subel", "[", "0", "]", "===", "\"inlinecode\"", ")", "{", "var", "lines", "=", "subel", "[", "1", "]", ".", "split", "(", "'\\n'", ")", ";", "for", "(", "var", "ln", "=", "0", ";", "ln", "<", "lines", ".", "length", ";", "++", "ln", ")", "{", "var", "line", "=", "lines", "[", "ln", "]", ";", "if", "(", "trim", "(", "line", ")", "!==", "''", ")", "{", "// if matches property, parse it", "if", "(", "prop_re", ".", "exec", "(", "line", ")", ")", "{", "var", "p", "=", "parseProperties", "(", "subel", "[", "1", "]", ")", ";", "var", "prop", "=", "slide", "?", "slide", ".", "properties", ":", "globalProperties", "for", "(", "var", "k", "in", "p", ")", "{", "prop", "[", "k", "]", "=", "{", "order", ":", "ln", ",", "value", ":", "p", "[", "k", "]", "}", "}", "}", "else", "{", "slide", "&&", "slide", ".", "actions", ".", "push", "(", "{", "cmd", ":", "line", ",", "order", ":", "ln", "}", ")", ";", "}", "}", "}", "// remove from list", "el", ".", "splice", "(", "j", ",", "1", ")", ";", "--", "j", ";", "}", "}", "}", "add", "&&", "slide", "&&", "slide", ".", "md_tree", ".", "push", "(", "el", ")", ";", "}", "if", "(", "slide", ")", "slides", ".", "push", "(", "Slide", "(", "slide", ".", "md_tree", ",", "slide", ".", "actions", ",", "slide", ".", "properties", ")", ")", ";", "// remove the order for globalProperties", "slides", ".", "global", "=", "{", "}", ";", "for", "(", "var", "k", "in", "globalProperties", ")", "{", "slides", ".", "global", "[", "k", "]", "=", "globalProperties", "[", "k", "]", ".", "value", ";", "}", "return", "slides", ";", "}" ]
given a markdown parsed tree return a list of slides with html and actions
[ "given", "a", "markdown", "parsed", "tree", "return", "a", "list", "of", "slides", "with", "html", "and", "actions" ]
59e194e8cf18154d095f004e01f955b6af9348f9
https://github.com/CartoDB/odyssey.js/blob/59e194e8cf18154d095f004e01f955b6af9348f9/lib/odyssey/template.js#L239-L302
16,552
CartoDB/odyssey.js
sandbox/dialog.js
addAction
function addAction(codemirror, slideNumer, action) { // parse properties from the new actions to next compare with // the current ones in the slide var currentActions = O.Template.parseProperties(action); var currentLine; var c = 0; var blockStart; // search for a actions block for (var i = slideNumer + 1; i < codemirror.lineCount(); ++i) { var line = codemirror.getLineHandle(i).text; if (ACTIONS_BLOCK_REGEXP.exec(line)) { if (++c === 2) { // parse current slide properties var slideActions = O.Template.parseProperties(getLines(codemirror, blockStart, i)); var updatedActions = {}; // search for the same in the slides for (var k in currentActions) { if (k in slideActions) { updatedActions[k] = currentActions[k]; } } // remove the ones that need update for (var k in updatedActions) { for (var linePos = blockStart + 1; linePos < i; ++linePos) { if (k in O.Template.parseProperties(codemirror.getLine(linePos))) { codemirror.removeLine(linePos); i -= 1; } } } // insert in the previous line currentLine = codemirror.getLineHandle(i); codemirror.setLine(i, action + "\n" + currentLine.text); return; } else { blockStart = i; } } else if(SLIDE_REGEXP.exec(line)) { // not found, insert a block currentLine = codemirror.getLineHandle(slideNumer); codemirror.setLine(slideNumer, currentLine.text + "\n```\n" + action +"\n```\n"); return; } } // insert at the end currentLine = codemirror.getLineHandle(slideNumer); codemirror.setLine(slideNumer, currentLine.text + "\n```\n"+ action + "\n```\n"); }
javascript
function addAction(codemirror, slideNumer, action) { // parse properties from the new actions to next compare with // the current ones in the slide var currentActions = O.Template.parseProperties(action); var currentLine; var c = 0; var blockStart; // search for a actions block for (var i = slideNumer + 1; i < codemirror.lineCount(); ++i) { var line = codemirror.getLineHandle(i).text; if (ACTIONS_BLOCK_REGEXP.exec(line)) { if (++c === 2) { // parse current slide properties var slideActions = O.Template.parseProperties(getLines(codemirror, blockStart, i)); var updatedActions = {}; // search for the same in the slides for (var k in currentActions) { if (k in slideActions) { updatedActions[k] = currentActions[k]; } } // remove the ones that need update for (var k in updatedActions) { for (var linePos = blockStart + 1; linePos < i; ++linePos) { if (k in O.Template.parseProperties(codemirror.getLine(linePos))) { codemirror.removeLine(linePos); i -= 1; } } } // insert in the previous line currentLine = codemirror.getLineHandle(i); codemirror.setLine(i, action + "\n" + currentLine.text); return; } else { blockStart = i; } } else if(SLIDE_REGEXP.exec(line)) { // not found, insert a block currentLine = codemirror.getLineHandle(slideNumer); codemirror.setLine(slideNumer, currentLine.text + "\n```\n" + action +"\n```\n"); return; } } // insert at the end currentLine = codemirror.getLineHandle(slideNumer); codemirror.setLine(slideNumer, currentLine.text + "\n```\n"+ action + "\n```\n"); }
[ "function", "addAction", "(", "codemirror", ",", "slideNumer", ",", "action", ")", "{", "// parse properties from the new actions to next compare with", "// the current ones in the slide", "var", "currentActions", "=", "O", ".", "Template", ".", "parseProperties", "(", "action", ")", ";", "var", "currentLine", ";", "var", "c", "=", "0", ";", "var", "blockStart", ";", "// search for a actions block", "for", "(", "var", "i", "=", "slideNumer", "+", "1", ";", "i", "<", "codemirror", ".", "lineCount", "(", ")", ";", "++", "i", ")", "{", "var", "line", "=", "codemirror", ".", "getLineHandle", "(", "i", ")", ".", "text", ";", "if", "(", "ACTIONS_BLOCK_REGEXP", ".", "exec", "(", "line", ")", ")", "{", "if", "(", "++", "c", "===", "2", ")", "{", "// parse current slide properties", "var", "slideActions", "=", "O", ".", "Template", ".", "parseProperties", "(", "getLines", "(", "codemirror", ",", "blockStart", ",", "i", ")", ")", ";", "var", "updatedActions", "=", "{", "}", ";", "// search for the same in the slides", "for", "(", "var", "k", "in", "currentActions", ")", "{", "if", "(", "k", "in", "slideActions", ")", "{", "updatedActions", "[", "k", "]", "=", "currentActions", "[", "k", "]", ";", "}", "}", "// remove the ones that need update", "for", "(", "var", "k", "in", "updatedActions", ")", "{", "for", "(", "var", "linePos", "=", "blockStart", "+", "1", ";", "linePos", "<", "i", ";", "++", "linePos", ")", "{", "if", "(", "k", "in", "O", ".", "Template", ".", "parseProperties", "(", "codemirror", ".", "getLine", "(", "linePos", ")", ")", ")", "{", "codemirror", ".", "removeLine", "(", "linePos", ")", ";", "i", "-=", "1", ";", "}", "}", "}", "// insert in the previous line", "currentLine", "=", "codemirror", ".", "getLineHandle", "(", "i", ")", ";", "codemirror", ".", "setLine", "(", "i", ",", "action", "+", "\"\\n\"", "+", "currentLine", ".", "text", ")", ";", "return", ";", "}", "else", "{", "blockStart", "=", "i", ";", "}", "}", "else", "if", "(", "SLIDE_REGEXP", ".", "exec", "(", "line", ")", ")", "{", "// not found, insert a block", "currentLine", "=", "codemirror", ".", "getLineHandle", "(", "slideNumer", ")", ";", "codemirror", ".", "setLine", "(", "slideNumer", ",", "currentLine", ".", "text", "+", "\"\\n```\\n\"", "+", "action", "+", "\"\\n```\\n\"", ")", ";", "return", ";", "}", "}", "// insert at the end", "currentLine", "=", "codemirror", ".", "getLineHandle", "(", "slideNumer", ")", ";", "codemirror", ".", "setLine", "(", "slideNumer", ",", "currentLine", ".", "text", "+", "\"\\n```\\n\"", "+", "action", "+", "\"\\n```\\n\"", ")", ";", "}" ]
adds action to slideNumber. creates it if the slide does not have any action
[ "adds", "action", "to", "slideNumber", ".", "creates", "it", "if", "the", "slide", "does", "not", "have", "any", "action" ]
59e194e8cf18154d095f004e01f955b6af9348f9
https://github.com/CartoDB/odyssey.js/blob/59e194e8cf18154d095f004e01f955b6af9348f9/sandbox/dialog.js#L330-L381
16,553
CartoDB/odyssey.js
sandbox/dialog.js
placeActionButtons
function placeActionButtons(el, codemirror) { // search for h1's var positions = []; var lineNumber = 0; codemirror.eachLine(function(a) { if (SLIDE_REGEXP.exec(a.text)) { positions.push({ pos: codemirror.heightAtLine(lineNumber)-66, // header height line: lineNumber }); } ++lineNumber; }); //remove previously added buttons el.selectAll('.actionButton').remove() var buttons = el.selectAll('.actionButton') .data(positions); // enter buttons.enter() .append('div') .attr('class', 'actionButton') .style({ position: 'absolute' }) .html('add') .on('click', function(d, i) { d3.event.stopPropagation(); var self = this; open(this, context.actions()).on('click', function(e) { context.getAction(e, function(action) { addAction(codemirror, d.line, action); context.changeSlide(i); }); close(self); }); }); el.on('click.actionbutton', function() { //close popup close(); }) // update var LINE_HEIGHT = 38; buttons.style({ top: function(d) { return (d.pos - LINE_HEIGHT) + "px"; }, left: 16 + "px" }); }
javascript
function placeActionButtons(el, codemirror) { // search for h1's var positions = []; var lineNumber = 0; codemirror.eachLine(function(a) { if (SLIDE_REGEXP.exec(a.text)) { positions.push({ pos: codemirror.heightAtLine(lineNumber)-66, // header height line: lineNumber }); } ++lineNumber; }); //remove previously added buttons el.selectAll('.actionButton').remove() var buttons = el.selectAll('.actionButton') .data(positions); // enter buttons.enter() .append('div') .attr('class', 'actionButton') .style({ position: 'absolute' }) .html('add') .on('click', function(d, i) { d3.event.stopPropagation(); var self = this; open(this, context.actions()).on('click', function(e) { context.getAction(e, function(action) { addAction(codemirror, d.line, action); context.changeSlide(i); }); close(self); }); }); el.on('click.actionbutton', function() { //close popup close(); }) // update var LINE_HEIGHT = 38; buttons.style({ top: function(d) { return (d.pos - LINE_HEIGHT) + "px"; }, left: 16 + "px" }); }
[ "function", "placeActionButtons", "(", "el", ",", "codemirror", ")", "{", "// search for h1's", "var", "positions", "=", "[", "]", ";", "var", "lineNumber", "=", "0", ";", "codemirror", ".", "eachLine", "(", "function", "(", "a", ")", "{", "if", "(", "SLIDE_REGEXP", ".", "exec", "(", "a", ".", "text", ")", ")", "{", "positions", ".", "push", "(", "{", "pos", ":", "codemirror", ".", "heightAtLine", "(", "lineNumber", ")", "-", "66", ",", "// header height", "line", ":", "lineNumber", "}", ")", ";", "}", "++", "lineNumber", ";", "}", ")", ";", "//remove previously added buttons", "el", ".", "selectAll", "(", "'.actionButton'", ")", ".", "remove", "(", ")", "var", "buttons", "=", "el", ".", "selectAll", "(", "'.actionButton'", ")", ".", "data", "(", "positions", ")", ";", "// enter", "buttons", ".", "enter", "(", ")", ".", "append", "(", "'div'", ")", ".", "attr", "(", "'class'", ",", "'actionButton'", ")", ".", "style", "(", "{", "position", ":", "'absolute'", "}", ")", ".", "html", "(", "'add'", ")", ".", "on", "(", "'click'", ",", "function", "(", "d", ",", "i", ")", "{", "d3", ".", "event", ".", "stopPropagation", "(", ")", ";", "var", "self", "=", "this", ";", "open", "(", "this", ",", "context", ".", "actions", "(", ")", ")", ".", "on", "(", "'click'", ",", "function", "(", "e", ")", "{", "context", ".", "getAction", "(", "e", ",", "function", "(", "action", ")", "{", "addAction", "(", "codemirror", ",", "d", ".", "line", ",", "action", ")", ";", "context", ".", "changeSlide", "(", "i", ")", ";", "}", ")", ";", "close", "(", "self", ")", ";", "}", ")", ";", "}", ")", ";", "el", ".", "on", "(", "'click.actionbutton'", ",", "function", "(", ")", "{", "//close popup", "close", "(", ")", ";", "}", ")", "// update", "var", "LINE_HEIGHT", "=", "38", ";", "buttons", ".", "style", "(", "{", "top", ":", "function", "(", "d", ")", "{", "return", "(", "d", ".", "pos", "-", "LINE_HEIGHT", ")", "+", "\"px\"", ";", "}", ",", "left", ":", "16", "+", "\"px\"", "}", ")", ";", "}" ]
place actions buttons on the left of the beggining of each slide
[ "place", "actions", "buttons", "on", "the", "left", "of", "the", "beggining", "of", "each", "slide" ]
59e194e8cf18154d095f004e01f955b6af9348f9
https://github.com/CartoDB/odyssey.js/blob/59e194e8cf18154d095f004e01f955b6af9348f9/sandbox/dialog.js#L385-L436
16,554
CartoDB/odyssey.js
lib/odyssey/actions/debug.js
Debug
function Debug() { function _debug() {}; _debug.log = function(_) { return Action({ enter: function() { console.log("STATE =>", _, arguments); }, update: function() { console.log("STATE (.)", _, arguments); }, exit: function() { console.log("STATE <=", _, arguments); } }); }; return _debug; }
javascript
function Debug() { function _debug() {}; _debug.log = function(_) { return Action({ enter: function() { console.log("STATE =>", _, arguments); }, update: function() { console.log("STATE (.)", _, arguments); }, exit: function() { console.log("STATE <=", _, arguments); } }); }; return _debug; }
[ "function", "Debug", "(", ")", "{", "function", "_debug", "(", ")", "{", "}", ";", "_debug", ".", "log", "=", "function", "(", "_", ")", "{", "return", "Action", "(", "{", "enter", ":", "function", "(", ")", "{", "console", ".", "log", "(", "\"STATE =>\"", ",", "_", ",", "arguments", ")", ";", "}", ",", "update", ":", "function", "(", ")", "{", "console", ".", "log", "(", "\"STATE (.)\"", ",", "_", ",", "arguments", ")", ";", "}", ",", "exit", ":", "function", "(", ")", "{", "console", ".", "log", "(", "\"STATE <=\"", ",", "_", ",", "arguments", ")", ";", "}", "}", ")", ";", "}", ";", "return", "_debug", ";", "}" ]
debug action prints information about current state
[ "debug", "action", "prints", "information", "about", "current", "state" ]
59e194e8cf18154d095f004e01f955b6af9348f9
https://github.com/CartoDB/odyssey.js/blob/59e194e8cf18154d095f004e01f955b6af9348f9/lib/odyssey/actions/debug.js#L7-L31
16,555
CartoDB/odyssey.js
lib/odyssey/actions/leaflet/map.js
leaflet_method
function leaflet_method(name) { _map[name] = function() { var args = arguments; return Action(function() { map[name].apply(map, args); }); }; }
javascript
function leaflet_method(name) { _map[name] = function() { var args = arguments; return Action(function() { map[name].apply(map, args); }); }; }
[ "function", "leaflet_method", "(", "name", ")", "{", "_map", "[", "name", "]", "=", "function", "(", ")", "{", "var", "args", "=", "arguments", ";", "return", "Action", "(", "function", "(", ")", "{", "map", "[", "name", "]", ".", "apply", "(", "map", ",", "args", ")", ";", "}", ")", ";", "}", ";", "}" ]
helper method to translate leaflet methods to actions
[ "helper", "method", "to", "translate", "leaflet", "methods", "to", "actions" ]
59e194e8cf18154d095f004e01f955b6af9348f9
https://github.com/CartoDB/odyssey.js/blob/59e194e8cf18154d095f004e01f955b6af9348f9/lib/odyssey/actions/leaflet/map.js#L9-L16
16,556
CartoDB/odyssey.js
vendor/jquery.spriteanim.js
function(elem) { // is this already initialized? if ($(elem).data('spriteanim')) return $(elem).data('spriteanim'); var spriteanim = new SpriteAnim(elem); $(elem).data('spriteanim', spriteanim); return spriteanim; }
javascript
function(elem) { // is this already initialized? if ($(elem).data('spriteanim')) return $(elem).data('spriteanim'); var spriteanim = new SpriteAnim(elem); $(elem).data('spriteanim', spriteanim); return spriteanim; }
[ "function", "(", "elem", ")", "{", "// is this already initialized?", "if", "(", "$", "(", "elem", ")", ".", "data", "(", "'spriteanim'", ")", ")", "return", "$", "(", "elem", ")", ".", "data", "(", "'spriteanim'", ")", ";", "var", "spriteanim", "=", "new", "SpriteAnim", "(", "elem", ")", ";", "$", "(", "elem", ")", ".", "data", "(", "'spriteanim'", ",", "spriteanim", ")", ";", "return", "spriteanim", ";", "}" ]
Initialize the animation for the element.
[ "Initialize", "the", "animation", "for", "the", "element", "." ]
59e194e8cf18154d095f004e01f955b6af9348f9
https://github.com/CartoDB/odyssey.js/blob/59e194e8cf18154d095f004e01f955b6af9348f9/vendor/jquery.spriteanim.js#L426-L433
16,557
CartoDB/odyssey.js
lib/odyssey/story.js
Edge
function Edge(a, b) { var s = 0; function t() {} a._story(null, function() { if(s !== 0) { t.trigger(); } s = 0; }); b._story(null, function() { if(s !== 1) { t.trigger(); } s = 1; }); return Trigger(t); }
javascript
function Edge(a, b) { var s = 0; function t() {} a._story(null, function() { if(s !== 0) { t.trigger(); } s = 0; }); b._story(null, function() { if(s !== 1) { t.trigger(); } s = 1; }); return Trigger(t); }
[ "function", "Edge", "(", "a", ",", "b", ")", "{", "var", "s", "=", "0", ";", "function", "t", "(", ")", "{", "}", "a", ".", "_story", "(", "null", ",", "function", "(", ")", "{", "if", "(", "s", "!==", "0", ")", "{", "t", ".", "trigger", "(", ")", ";", "}", "s", "=", "0", ";", "}", ")", ";", "b", ".", "_story", "(", "null", ",", "function", "(", ")", "{", "if", "(", "s", "!==", "1", ")", "{", "t", ".", "trigger", "(", ")", ";", "}", "s", "=", "1", ";", "}", ")", ";", "return", "Trigger", "(", "t", ")", ";", "}" ]
check change between two states and triggers
[ "check", "change", "between", "two", "states", "and", "triggers" ]
59e194e8cf18154d095f004e01f955b6af9348f9
https://github.com/CartoDB/odyssey.js/blob/59e194e8cf18154d095f004e01f955b6af9348f9/lib/odyssey/story.js#L305-L321
16,558
platanus/angular-restmod
src/module/support/default-packer.js
processFeature
function processFeature(_raw, _name, _feature, _other, _do) { if(_feature === '.' || _feature === true) { var skip = [_name]; if(_other) skip.push.apply(skip, angular.isArray(_other) ? _other : [_other]); exclude(_raw, skip, _do); } else if(typeof _feature === 'string') { exclude(_raw[_feature], [], _do); } else { // links is an array include(_raw, _feature, _do); } }
javascript
function processFeature(_raw, _name, _feature, _other, _do) { if(_feature === '.' || _feature === true) { var skip = [_name]; if(_other) skip.push.apply(skip, angular.isArray(_other) ? _other : [_other]); exclude(_raw, skip, _do); } else if(typeof _feature === 'string') { exclude(_raw[_feature], [], _do); } else { // links is an array include(_raw, _feature, _do); } }
[ "function", "processFeature", "(", "_raw", ",", "_name", ",", "_feature", ",", "_other", ",", "_do", ")", "{", "if", "(", "_feature", "===", "'.'", "||", "_feature", "===", "true", ")", "{", "var", "skip", "=", "[", "_name", "]", ";", "if", "(", "_other", ")", "skip", ".", "push", ".", "apply", "(", "skip", ",", "angular", ".", "isArray", "(", "_other", ")", "?", "_other", ":", "[", "_other", "]", ")", ";", "exclude", "(", "_raw", ",", "skip", ",", "_do", ")", ";", "}", "else", "if", "(", "typeof", "_feature", "===", "'string'", ")", "{", "exclude", "(", "_raw", "[", "_feature", "]", ",", "[", "]", ",", "_do", ")", ";", "}", "else", "{", "// links is an array", "include", "(", "_raw", ",", "_feature", ",", "_do", ")", ";", "}", "}" ]
process links and stores them in the packer cache
[ "process", "links", "and", "stores", "them", "in", "the", "packer", "cache" ]
ed18b4da48fca7582edb8bcbcca91ef3177adf0b
https://github.com/platanus/angular-restmod/blob/ed18b4da48fca7582edb8bcbcca91ef3177adf0b/src/module/support/default-packer.js#L20-L30
16,559
platanus/angular-restmod
src/module/extended/builder-relations.js
applyHooks
function applyHooks(_target, _hooks, _owner) { for(var key in _hooks) { if(_hooks.hasOwnProperty(key)) { _target.$on(key, wrapHook(_hooks[key], _owner)); } } }
javascript
function applyHooks(_target, _hooks, _owner) { for(var key in _hooks) { if(_hooks.hasOwnProperty(key)) { _target.$on(key, wrapHook(_hooks[key], _owner)); } } }
[ "function", "applyHooks", "(", "_target", ",", "_hooks", ",", "_owner", ")", "{", "for", "(", "var", "key", "in", "_hooks", ")", "{", "if", "(", "_hooks", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "_target", ".", "$on", "(", "key", ",", "wrapHook", "(", "_hooks", "[", "key", "]", ",", "_owner", ")", ")", ";", "}", "}", "}" ]
wraps a bunch of hooks
[ "wraps", "a", "bunch", "of", "hooks" ]
ed18b4da48fca7582edb8bcbcca91ef3177adf0b
https://github.com/platanus/angular-restmod/blob/ed18b4da48fca7582edb8bcbcca91ef3177adf0b/src/module/extended/builder-relations.js#L19-L25
16,560
platanus/angular-restmod
dist/plugins/preload.js
processGroup
function processGroup(_records, _target, _params) { // extract targets var targets = [], record; for(var i = 0, l = _records.length; i < l; i++) { record = _records[i][_target]; if(angular.isArray(record)) { targets.push.apply(targets, record); } else if(record) { targets.push(record); } } // populate targets if(targets.length > 0) { var promise = typeof targets[0].$type.$populate === 'function' ? targets[0].$type.$populate(targets, _params).$asPromise() : populate(targets, _params); if(promise) { return promise.then(function() { return targets; }); } } return $q.when(targets); }
javascript
function processGroup(_records, _target, _params) { // extract targets var targets = [], record; for(var i = 0, l = _records.length; i < l; i++) { record = _records[i][_target]; if(angular.isArray(record)) { targets.push.apply(targets, record); } else if(record) { targets.push(record); } } // populate targets if(targets.length > 0) { var promise = typeof targets[0].$type.$populate === 'function' ? targets[0].$type.$populate(targets, _params).$asPromise() : populate(targets, _params); if(promise) { return promise.then(function() { return targets; }); } } return $q.when(targets); }
[ "function", "processGroup", "(", "_records", ",", "_target", ",", "_params", ")", "{", "// extract targets", "var", "targets", "=", "[", "]", ",", "record", ";", "for", "(", "var", "i", "=", "0", ",", "l", "=", "_records", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "record", "=", "_records", "[", "i", "]", "[", "_target", "]", ";", "if", "(", "angular", ".", "isArray", "(", "record", ")", ")", "{", "targets", ".", "push", ".", "apply", "(", "targets", ",", "record", ")", ";", "}", "else", "if", "(", "record", ")", "{", "targets", ".", "push", "(", "record", ")", ";", "}", "}", "// populate targets", "if", "(", "targets", ".", "length", ">", "0", ")", "{", "var", "promise", "=", "typeof", "targets", "[", "0", "]", ".", "$type", ".", "$populate", "===", "'function'", "?", "targets", "[", "0", "]", ".", "$type", ".", "$populate", "(", "targets", ",", "_params", ")", ".", "$asPromise", "(", ")", ":", "populate", "(", "targets", ",", "_params", ")", ";", "if", "(", "promise", ")", "{", "return", "promise", ".", "then", "(", "function", "(", ")", "{", "return", "targets", ";", "}", ")", ";", "}", "}", "return", "$q", ".", "when", "(", "targets", ")", ";", "}" ]
processes a group records of the same type
[ "processes", "a", "group", "records", "of", "the", "same", "type" ]
ed18b4da48fca7582edb8bcbcca91ef3177adf0b
https://github.com/platanus/angular-restmod/blob/ed18b4da48fca7582edb8bcbcca91ef3177adf0b/dist/plugins/preload.js#L29-L56
16,561
platanus/angular-restmod
src/module/serializer.js
function() { return { /** * @memberof BuilderApi# * * @description Sets an attribute mapping. * * Allows a explicit server to model property mapping to be defined. * * For example, to map the response property `stats.created_at` to model's `created` property. * * ```javascript * builder.attrMap('created', 'stats.created_at'); * ``` * * It's also posible to use a wildcard '*' as server name to use the default name decoder as * server name. This is used to force a property to be processed on decode/encode even if its * not present on request/record (respectively), by doing this its posible, for example, to define * a dynamic property that is generated automatically before the object is send to the server. * * @param {string} _attr Attribute name * @param {string} _serverName Server (request/response) property name * @return {BuilderApi} self */ attrMap: function(_attr, _serverPath, _forced) { // extract parent node from client name: var index = _attr.lastIndexOf('.'), node = index !== -1 ? _attr.substr(0, index) : '', leaf = index !== -1 ? _attr.substr(index + 1) : _attr; mapped[_attr] = true; var nodes = (mappings[node] || (mappings[node] = [])); nodes.push({ path: leaf, map: _serverPath === '*' ? null : _serverPath.split('.'), mapPath: _serverPath, forced: _forced }); return this; }, /** * @memberof BuilderApi# * * @description Sets an attribute mask. * * An attribute mask prevents the attribute to be loaded from or sent to the server on certain operations. * * The attribute mask is a string composed by: * * C: To prevent attribute from being sent on create * * R: To prevent attribute from being loaded from server * * U: To prevent attribute from being sent on update * * For example, the following will prevent an attribute to be send on create or update: * * ```javascript * builder.attrMask('readOnly', 'CU'); * ``` * * If a true boolean value is passed as mask, then 'CRU' will be used * If a false boolean valus is passed as mask, then mask will be removed * * @param {string} _attr Attribute name * @param {boolean|string} _mask Attribute mask * @return {BuilderApi} self */ attrMask: function(_attr, _mask) { if(!_mask) { delete masks[_attr]; } else { masks[_attr] = _mask; } return this; }, /** * @memberof BuilderApi# * * @description Assigns a decoding function/filter to a given attribute. * * @param {string} _name Attribute name * @param {string|function} _filter filter or function to register * @param {mixed} _filterParam Misc filter parameter * @param {boolean} _chain If true, filter is chained to the current attribute filter. * @return {BuilderApi} self */ attrDecoder: function(_attr, _filter, _filterParam, _chain) { if(typeof _filter === 'string') { var filter = $filter(_filter); _filter = function(_value) { return filter(_value, _filterParam); }; } decoders[_attr] = _chain ? Utils.chain(decoders[_attr], _filter) : _filter; return this; }, /** * @memberof BuilderApi# * * @description Assigns a encoding function/filter to a given attribute. * * @param {string} _name Attribute name * @param {string|function} _filter filter or function to register * @param {mixed} _filterParam Misc filter parameter * @param {boolean} _chain If true, filter is chained to the current attribute filter. * @return {BuilderApi} self */ attrEncoder: function(_attr, _filter, _filterParam, _chain) { if(typeof _filter === 'string') { var filter = $filter(_filter); _filter = function(_value) { return filter(_value, _filterParam); }; } encoders[_attr] = _chain ? Utils.chain(encoders[_attr], _filter) : _filter; return this; }, /** * @memberof BuilderApi# * * @description Makes an attribute volatile, a volatile attribute is deleted from source after encoding. * * @param {string} _name Attribute name * @param {boolean} _isVolatile defaults to true, if set to false then the attribute is no longer volatile. * @return {BuilderApi} self */ attrVolatile: function(_attr, _isVolatile) { vol[_attr] = _isVolatile === undefined ? true : _isVolatile; return this; } }; }
javascript
function() { return { /** * @memberof BuilderApi# * * @description Sets an attribute mapping. * * Allows a explicit server to model property mapping to be defined. * * For example, to map the response property `stats.created_at` to model's `created` property. * * ```javascript * builder.attrMap('created', 'stats.created_at'); * ``` * * It's also posible to use a wildcard '*' as server name to use the default name decoder as * server name. This is used to force a property to be processed on decode/encode even if its * not present on request/record (respectively), by doing this its posible, for example, to define * a dynamic property that is generated automatically before the object is send to the server. * * @param {string} _attr Attribute name * @param {string} _serverName Server (request/response) property name * @return {BuilderApi} self */ attrMap: function(_attr, _serverPath, _forced) { // extract parent node from client name: var index = _attr.lastIndexOf('.'), node = index !== -1 ? _attr.substr(0, index) : '', leaf = index !== -1 ? _attr.substr(index + 1) : _attr; mapped[_attr] = true; var nodes = (mappings[node] || (mappings[node] = [])); nodes.push({ path: leaf, map: _serverPath === '*' ? null : _serverPath.split('.'), mapPath: _serverPath, forced: _forced }); return this; }, /** * @memberof BuilderApi# * * @description Sets an attribute mask. * * An attribute mask prevents the attribute to be loaded from or sent to the server on certain operations. * * The attribute mask is a string composed by: * * C: To prevent attribute from being sent on create * * R: To prevent attribute from being loaded from server * * U: To prevent attribute from being sent on update * * For example, the following will prevent an attribute to be send on create or update: * * ```javascript * builder.attrMask('readOnly', 'CU'); * ``` * * If a true boolean value is passed as mask, then 'CRU' will be used * If a false boolean valus is passed as mask, then mask will be removed * * @param {string} _attr Attribute name * @param {boolean|string} _mask Attribute mask * @return {BuilderApi} self */ attrMask: function(_attr, _mask) { if(!_mask) { delete masks[_attr]; } else { masks[_attr] = _mask; } return this; }, /** * @memberof BuilderApi# * * @description Assigns a decoding function/filter to a given attribute. * * @param {string} _name Attribute name * @param {string|function} _filter filter or function to register * @param {mixed} _filterParam Misc filter parameter * @param {boolean} _chain If true, filter is chained to the current attribute filter. * @return {BuilderApi} self */ attrDecoder: function(_attr, _filter, _filterParam, _chain) { if(typeof _filter === 'string') { var filter = $filter(_filter); _filter = function(_value) { return filter(_value, _filterParam); }; } decoders[_attr] = _chain ? Utils.chain(decoders[_attr], _filter) : _filter; return this; }, /** * @memberof BuilderApi# * * @description Assigns a encoding function/filter to a given attribute. * * @param {string} _name Attribute name * @param {string|function} _filter filter or function to register * @param {mixed} _filterParam Misc filter parameter * @param {boolean} _chain If true, filter is chained to the current attribute filter. * @return {BuilderApi} self */ attrEncoder: function(_attr, _filter, _filterParam, _chain) { if(typeof _filter === 'string') { var filter = $filter(_filter); _filter = function(_value) { return filter(_value, _filterParam); }; } encoders[_attr] = _chain ? Utils.chain(encoders[_attr], _filter) : _filter; return this; }, /** * @memberof BuilderApi# * * @description Makes an attribute volatile, a volatile attribute is deleted from source after encoding. * * @param {string} _name Attribute name * @param {boolean} _isVolatile defaults to true, if set to false then the attribute is no longer volatile. * @return {BuilderApi} self */ attrVolatile: function(_attr, _isVolatile) { vol[_attr] = _isVolatile === undefined ? true : _isVolatile; return this; } }; }
[ "function", "(", ")", "{", "return", "{", "/**\n * @memberof BuilderApi#\n *\n * @description Sets an attribute mapping.\n *\n * Allows a explicit server to model property mapping to be defined.\n *\n * For example, to map the response property `stats.created_at` to model's `created` property.\n *\n * ```javascript\n * builder.attrMap('created', 'stats.created_at');\n * ```\n *\n * It's also posible to use a wildcard '*' as server name to use the default name decoder as\n * server name. This is used to force a property to be processed on decode/encode even if its\n * not present on request/record (respectively), by doing this its posible, for example, to define\n * a dynamic property that is generated automatically before the object is send to the server.\n *\n * @param {string} _attr Attribute name\n * @param {string} _serverName Server (request/response) property name\n * @return {BuilderApi} self\n */", "attrMap", ":", "function", "(", "_attr", ",", "_serverPath", ",", "_forced", ")", "{", "// extract parent node from client name:", "var", "index", "=", "_attr", ".", "lastIndexOf", "(", "'.'", ")", ",", "node", "=", "index", "!==", "-", "1", "?", "_attr", ".", "substr", "(", "0", ",", "index", ")", ":", "''", ",", "leaf", "=", "index", "!==", "-", "1", "?", "_attr", ".", "substr", "(", "index", "+", "1", ")", ":", "_attr", ";", "mapped", "[", "_attr", "]", "=", "true", ";", "var", "nodes", "=", "(", "mappings", "[", "node", "]", "||", "(", "mappings", "[", "node", "]", "=", "[", "]", ")", ")", ";", "nodes", ".", "push", "(", "{", "path", ":", "leaf", ",", "map", ":", "_serverPath", "===", "'*'", "?", "null", ":", "_serverPath", ".", "split", "(", "'.'", ")", ",", "mapPath", ":", "_serverPath", ",", "forced", ":", "_forced", "}", ")", ";", "return", "this", ";", "}", ",", "/**\n * @memberof BuilderApi#\n *\n * @description Sets an attribute mask.\n *\n * An attribute mask prevents the attribute to be loaded from or sent to the server on certain operations.\n *\n * The attribute mask is a string composed by:\n * * C: To prevent attribute from being sent on create\n * * R: To prevent attribute from being loaded from server\n * * U: To prevent attribute from being sent on update\n *\n * For example, the following will prevent an attribute to be send on create or update:\n *\n * ```javascript\n * builder.attrMask('readOnly', 'CU');\n * ```\n *\n * If a true boolean value is passed as mask, then 'CRU' will be used\n * If a false boolean valus is passed as mask, then mask will be removed\n *\n * @param {string} _attr Attribute name\n * @param {boolean|string} _mask Attribute mask\n * @return {BuilderApi} self\n */", "attrMask", ":", "function", "(", "_attr", ",", "_mask", ")", "{", "if", "(", "!", "_mask", ")", "{", "delete", "masks", "[", "_attr", "]", ";", "}", "else", "{", "masks", "[", "_attr", "]", "=", "_mask", ";", "}", "return", "this", ";", "}", ",", "/**\n * @memberof BuilderApi#\n *\n * @description Assigns a decoding function/filter to a given attribute.\n *\n * @param {string} _name Attribute name\n * @param {string|function} _filter filter or function to register\n * @param {mixed} _filterParam Misc filter parameter\n * @param {boolean} _chain If true, filter is chained to the current attribute filter.\n * @return {BuilderApi} self\n */", "attrDecoder", ":", "function", "(", "_attr", ",", "_filter", ",", "_filterParam", ",", "_chain", ")", "{", "if", "(", "typeof", "_filter", "===", "'string'", ")", "{", "var", "filter", "=", "$filter", "(", "_filter", ")", ";", "_filter", "=", "function", "(", "_value", ")", "{", "return", "filter", "(", "_value", ",", "_filterParam", ")", ";", "}", ";", "}", "decoders", "[", "_attr", "]", "=", "_chain", "?", "Utils", ".", "chain", "(", "decoders", "[", "_attr", "]", ",", "_filter", ")", ":", "_filter", ";", "return", "this", ";", "}", ",", "/**\n * @memberof BuilderApi#\n *\n * @description Assigns a encoding function/filter to a given attribute.\n *\n * @param {string} _name Attribute name\n * @param {string|function} _filter filter or function to register\n * @param {mixed} _filterParam Misc filter parameter\n * @param {boolean} _chain If true, filter is chained to the current attribute filter.\n * @return {BuilderApi} self\n */", "attrEncoder", ":", "function", "(", "_attr", ",", "_filter", ",", "_filterParam", ",", "_chain", ")", "{", "if", "(", "typeof", "_filter", "===", "'string'", ")", "{", "var", "filter", "=", "$filter", "(", "_filter", ")", ";", "_filter", "=", "function", "(", "_value", ")", "{", "return", "filter", "(", "_value", ",", "_filterParam", ")", ";", "}", ";", "}", "encoders", "[", "_attr", "]", "=", "_chain", "?", "Utils", ".", "chain", "(", "encoders", "[", "_attr", "]", ",", "_filter", ")", ":", "_filter", ";", "return", "this", ";", "}", ",", "/**\n * @memberof BuilderApi#\n *\n * @description Makes an attribute volatile, a volatile attribute is deleted from source after encoding.\n *\n * @param {string} _name Attribute name\n * @param {boolean} _isVolatile defaults to true, if set to false then the attribute is no longer volatile.\n * @return {BuilderApi} self\n */", "attrVolatile", ":", "function", "(", "_attr", ",", "_isVolatile", ")", "{", "vol", "[", "_attr", "]", "=", "_isVolatile", "===", "undefined", "?", "true", ":", "_isVolatile", ";", "return", "this", ";", "}", "}", ";", "}" ]
builds a serializerd DSL, is a standalone object that can be extended.
[ "builds", "a", "serializerd", "DSL", "is", "a", "standalone", "object", "that", "can", "be", "extended", "." ]
ed18b4da48fca7582edb8bcbcca91ef3177adf0b
https://github.com/platanus/angular-restmod/blob/ed18b4da48fca7582edb8bcbcca91ef3177adf0b/src/module/serializer.js#L195-L326
16,562
platanus/angular-restmod
src/module/builder.js
function(_chain) { for(var i = 0, l = _chain.length; i < l; i++) { this.mixin(_chain[i]); } }
javascript
function(_chain) { for(var i = 0, l = _chain.length; i < l; i++) { this.mixin(_chain[i]); } }
[ "function", "(", "_chain", ")", "{", "for", "(", "var", "i", "=", "0", ",", "l", "=", "_chain", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "this", ".", "mixin", "(", "_chain", "[", "i", "]", ")", ";", "}", "}" ]
use the builder to process a mixin chain
[ "use", "the", "builder", "to", "process", "a", "mixin", "chain" ]
ed18b4da48fca7582edb8bcbcca91ef3177adf0b
https://github.com/platanus/angular-restmod/blob/ed18b4da48fca7582edb8bcbcca91ef3177adf0b/src/module/builder.js#L313-L317
16,563
platanus/angular-restmod
src/module/builder.js
function(_mix) { if(_mix.$$chain) { this.chain(_mix.$$chain); } else if(typeof _mix === 'string') { this.mixin($injector.get(_mix)); } else if(isArray(_mix)) { this.chain(_mix); } else if(isFunction(_mix)) { _mix.call(this.dsl, $injector); } else { this.dsl.describe(_mix); } }
javascript
function(_mix) { if(_mix.$$chain) { this.chain(_mix.$$chain); } else if(typeof _mix === 'string') { this.mixin($injector.get(_mix)); } else if(isArray(_mix)) { this.chain(_mix); } else if(isFunction(_mix)) { _mix.call(this.dsl, $injector); } else { this.dsl.describe(_mix); } }
[ "function", "(", "_mix", ")", "{", "if", "(", "_mix", ".", "$$chain", ")", "{", "this", ".", "chain", "(", "_mix", ".", "$$chain", ")", ";", "}", "else", "if", "(", "typeof", "_mix", "===", "'string'", ")", "{", "this", ".", "mixin", "(", "$injector", ".", "get", "(", "_mix", ")", ")", ";", "}", "else", "if", "(", "isArray", "(", "_mix", ")", ")", "{", "this", ".", "chain", "(", "_mix", ")", ";", "}", "else", "if", "(", "isFunction", "(", "_mix", ")", ")", "{", "_mix", ".", "call", "(", "this", ".", "dsl", ",", "$injector", ")", ";", "}", "else", "{", "this", ".", "dsl", ".", "describe", "(", "_mix", ")", ";", "}", "}" ]
use the builder to process a single mixin
[ "use", "the", "builder", "to", "process", "a", "single", "mixin" ]
ed18b4da48fca7582edb8bcbcca91ef3177adf0b
https://github.com/platanus/angular-restmod/blob/ed18b4da48fca7582edb8bcbcca91ef3177adf0b/src/module/builder.js#L320-L332
16,564
platanus/angular-restmod
src/plugins/debounced.js
buildAsyncSaveFun
function buildAsyncSaveFun(_this, _oldSave, _promise, _oldPromise) { return function() { // swap promises so save behaves like it has been called during the original call. var currentPromise = _this.$promise; _this.$promise = _oldPromise; // when save resolves, the timeout promise is resolved and the last resource promise returned // so it behaves _oldSave.call(_this).$promise.then( function(_data) { _promise.resolve(_data); _this.$promise = currentPromise; }, function(_reason) { _promise.reject(_reason); _this.$promise = currentPromise; } ); _this.$dmStatus = null; }; }
javascript
function buildAsyncSaveFun(_this, _oldSave, _promise, _oldPromise) { return function() { // swap promises so save behaves like it has been called during the original call. var currentPromise = _this.$promise; _this.$promise = _oldPromise; // when save resolves, the timeout promise is resolved and the last resource promise returned // so it behaves _oldSave.call(_this).$promise.then( function(_data) { _promise.resolve(_data); _this.$promise = currentPromise; }, function(_reason) { _promise.reject(_reason); _this.$promise = currentPromise; } ); _this.$dmStatus = null; }; }
[ "function", "buildAsyncSaveFun", "(", "_this", ",", "_oldSave", ",", "_promise", ",", "_oldPromise", ")", "{", "return", "function", "(", ")", "{", "// swap promises so save behaves like it has been called during the original call.", "var", "currentPromise", "=", "_this", ".", "$promise", ";", "_this", ".", "$promise", "=", "_oldPromise", ";", "// when save resolves, the timeout promise is resolved and the last resource promise returned", "// so it behaves", "_oldSave", ".", "call", "(", "_this", ")", ".", "$promise", ".", "then", "(", "function", "(", "_data", ")", "{", "_promise", ".", "resolve", "(", "_data", ")", ";", "_this", ".", "$promise", "=", "currentPromise", ";", "}", ",", "function", "(", "_reason", ")", "{", "_promise", ".", "reject", "(", "_reason", ")", ";", "_this", ".", "$promise", "=", "currentPromise", ";", "}", ")", ";", "_this", ".", "$dmStatus", "=", "null", ";", "}", ";", "}" ]
builds a new async save function bound to a given context and promise.
[ "builds", "a", "new", "async", "save", "function", "bound", "to", "a", "given", "context", "and", "promise", "." ]
ed18b4da48fca7582edb8bcbcca91ef3177adf0b
https://github.com/platanus/angular-restmod/blob/ed18b4da48fca7582edb8bcbcca91ef3177adf0b/src/plugins/debounced.js#L46-L67
16,565
platanus/angular-restmod
dist/angular-restmod-bundle.js
applyRules
function applyRules(_string, _ruleSet, _skip) { if(_skip.indexOf(_string.toLowerCase()) === -1) { var i = 0, rule; while(rule = _ruleSet[i++]) { if(_string.match(rule[0])) { return _string.replace(rule[0], rule[1]); } } } return _string; }
javascript
function applyRules(_string, _ruleSet, _skip) { if(_skip.indexOf(_string.toLowerCase()) === -1) { var i = 0, rule; while(rule = _ruleSet[i++]) { if(_string.match(rule[0])) { return _string.replace(rule[0], rule[1]); } } } return _string; }
[ "function", "applyRules", "(", "_string", ",", "_ruleSet", ",", "_skip", ")", "{", "if", "(", "_skip", ".", "indexOf", "(", "_string", ".", "toLowerCase", "(", ")", ")", "===", "-", "1", ")", "{", "var", "i", "=", "0", ",", "rule", ";", "while", "(", "rule", "=", "_ruleSet", "[", "i", "++", "]", ")", "{", "if", "(", "_string", ".", "match", "(", "rule", "[", "0", "]", ")", ")", "{", "return", "_string", ".", "replace", "(", "rule", "[", "0", "]", ",", "rule", "[", "1", "]", ")", ";", "}", "}", "}", "return", "_string", ";", "}" ]
helper function used by singularize and pluralize
[ "helper", "function", "used", "by", "singularize", "and", "pluralize" ]
ed18b4da48fca7582edb8bcbcca91ef3177adf0b
https://github.com/platanus/angular-restmod/blob/ed18b4da48fca7582edb8bcbcca91ef3177adf0b/dist/angular-restmod-bundle.js#L99-L111
16,566
platanus/angular-restmod
dist/angular-restmod-bundle.js
function(_hook, _args, _ctx) { var cbs = hooks[_hook], i, cb; if(cbs) { for(i = 0; !!(cb = cbs[i]); i++) { cb.apply(_ctx || this, _args || []); } } return this; }
javascript
function(_hook, _args, _ctx) { var cbs = hooks[_hook], i, cb; if(cbs) { for(i = 0; !!(cb = cbs[i]); i++) { cb.apply(_ctx || this, _args || []); } } return this; }
[ "function", "(", "_hook", ",", "_args", ",", "_ctx", ")", "{", "var", "cbs", "=", "hooks", "[", "_hook", "]", ",", "i", ",", "cb", ";", "if", "(", "cbs", ")", "{", "for", "(", "i", "=", "0", ";", "!", "!", "(", "cb", "=", "cbs", "[", "i", "]", ")", ";", "i", "++", ")", "{", "cb", ".", "apply", "(", "_ctx", "||", "this", ",", "_args", "||", "[", "]", ")", ";", "}", "}", "return", "this", ";", "}" ]
bubbles events comming from related resources
[ "bubbles", "events", "comming", "from", "related", "resources" ]
ed18b4da48fca7582edb8bcbcca91ef3177adf0b
https://github.com/platanus/angular-restmod/blob/ed18b4da48fca7582edb8bcbcca91ef3177adf0b/dist/angular-restmod-bundle.js#L2819-L2827
16,567
platanus/angular-restmod
dist/angular-restmod-bundle.js
function(_items) { var list = new List(); if(_items) list.push.apply(list, _items); return list; }
javascript
function(_items) { var list = new List(); if(_items) list.push.apply(list, _items); return list; }
[ "function", "(", "_items", ")", "{", "var", "list", "=", "new", "List", "(", ")", ";", "if", "(", "_items", ")", "list", ".", "push", ".", "apply", "(", "list", ",", "_items", ")", ";", "return", "list", ";", "}" ]
Creates a new record list. A list is a ordered set of records not bound to a particular scope. Contained records can belong to any scope. @return {List} the new list
[ "Creates", "a", "new", "record", "list", "." ]
ed18b4da48fca7582edb8bcbcca91ef3177adf0b
https://github.com/platanus/angular-restmod/blob/ed18b4da48fca7582edb8bcbcca91ef3177adf0b/dist/angular-restmod-bundle.js#L2928-L2932
16,568
platanus/angular-restmod
dist/angular-restmod-bundle.js
function(_params, _scope) { _params = this.$params ? angular.extend({}, this.$params, _params) : _params; return newCollection(_params, _scope || this.$scope); }
javascript
function(_params, _scope) { _params = this.$params ? angular.extend({}, this.$params, _params) : _params; return newCollection(_params, _scope || this.$scope); }
[ "function", "(", "_params", ",", "_scope", ")", "{", "_params", "=", "this", ".", "$params", "?", "angular", ".", "extend", "(", "{", "}", ",", "this", ".", "$params", ",", "_params", ")", ":", "_params", ";", "return", "newCollection", "(", "_params", ",", "_scope", "||", "this", ".", "$scope", ")", ";", "}" ]
provide collection constructor
[ "provide", "collection", "constructor" ]
ed18b4da48fca7582edb8bcbcca91ef3177adf0b
https://github.com/platanus/angular-restmod/blob/ed18b4da48fca7582edb8bcbcca91ef3177adf0b/dist/angular-restmod-bundle.js#L3116-L3119
16,569
platanus/angular-restmod
dist/angular-restmod-bundle.js
helpDefine
function helpDefine(_api, _name, _fun) { var api = APIS[_api]; Utils.assert(!!api, 'Invalid api name $1', _api); if(_name) { api[_name] = Utils.override(api[_name], _fun); } else { Utils.extendOverriden(api, _fun); } }
javascript
function helpDefine(_api, _name, _fun) { var api = APIS[_api]; Utils.assert(!!api, 'Invalid api name $1', _api); if(_name) { api[_name] = Utils.override(api[_name], _fun); } else { Utils.extendOverriden(api, _fun); } }
[ "function", "helpDefine", "(", "_api", ",", "_name", ",", "_fun", ")", "{", "var", "api", "=", "APIS", "[", "_api", "]", ";", "Utils", ".", "assert", "(", "!", "!", "api", ",", "'Invalid api name $1'", ",", "_api", ")", ";", "if", "(", "_name", ")", "{", "api", "[", "_name", "]", "=", "Utils", ".", "override", "(", "api", "[", "_name", "]", ",", "_fun", ")", ";", "}", "else", "{", "Utils", ".", "extendOverriden", "(", "api", ",", "_fun", ")", ";", "}", "}" ]
helper used to extend api's
[ "helper", "used", "to", "extend", "api", "s" ]
ed18b4da48fca7582edb8bcbcca91ef3177adf0b
https://github.com/platanus/angular-restmod/blob/ed18b4da48fca7582edb8bcbcca91ef3177adf0b/dist/angular-restmod-bundle.js#L3154-L3164
16,570
adonisjs/adonis-bodyparser
src/Bindings/Validations.js
validateFile
async function validateFile (file, options) { if (file instanceof File === false) { return null } await file.setOptions(Object.assign(file.validationOptions, options)).runValidations() return _.size(file.error()) ? file.error().message : null }
javascript
async function validateFile (file, options) { if (file instanceof File === false) { return null } await file.setOptions(Object.assign(file.validationOptions, options)).runValidations() return _.size(file.error()) ? file.error().message : null }
[ "async", "function", "validateFile", "(", "file", ",", "options", ")", "{", "if", "(", "file", "instanceof", "File", "===", "false", ")", "{", "return", "null", "}", "await", "file", ".", "setOptions", "(", "Object", ".", "assign", "(", "file", ".", "validationOptions", ",", "options", ")", ")", ".", "runValidations", "(", ")", "return", "_", ".", "size", "(", "file", ".", "error", "(", ")", ")", "?", "file", ".", "error", "(", ")", ".", "message", ":", "null", "}" ]
Validates a single file instance. If validation has error, then error message will be returned as string, else null is returned. @method validateFile @param {File} file @param {Object} options @return {String|Null}
[ "Validates", "a", "single", "file", "instance", ".", "If", "validation", "has", "error", "then", "error", "message", "will", "be", "returned", "as", "string", "else", "null", "is", "returned", "." ]
11efb935e382c68da531da28d32d9b3d821338da
https://github.com/adonisjs/adonis-bodyparser/blob/11efb935e382c68da531da28d32d9b3d821338da/src/Bindings/Validations.js#L24-L31
16,571
adonisjs/adonis-bodyparser
src/Multipart/File.js
function (type, data) { if (type === 'size') { return `File size should be less than ${bytes(data.size)}` } if (type === 'type') { const verb = data.types.length === 1 ? 'is' : 'are' return `Invalid file type ${data.subtype} or ${data.type}. Only ${data.types.join(', ')} ${verb} allowed` } if (type === 'extname') { const verb = data.extnames.length === 1 ? 'is' : 'are' return `Invalid file extension ${data.extname}. Only ${data.extnames.join(', ')} ${verb} allowed` } }
javascript
function (type, data) { if (type === 'size') { return `File size should be less than ${bytes(data.size)}` } if (type === 'type') { const verb = data.types.length === 1 ? 'is' : 'are' return `Invalid file type ${data.subtype} or ${data.type}. Only ${data.types.join(', ')} ${verb} allowed` } if (type === 'extname') { const verb = data.extnames.length === 1 ? 'is' : 'are' return `Invalid file extension ${data.extname}. Only ${data.extnames.join(', ')} ${verb} allowed` } }
[ "function", "(", "type", ",", "data", ")", "{", "if", "(", "type", "===", "'size'", ")", "{", "return", "`", "${", "bytes", "(", "data", ".", "size", ")", "}", "`", "}", "if", "(", "type", "===", "'type'", ")", "{", "const", "verb", "=", "data", ".", "types", ".", "length", "===", "1", "?", "'is'", ":", "'are'", "return", "`", "${", "data", ".", "subtype", "}", "${", "data", ".", "type", "}", "${", "data", ".", "types", ".", "join", "(", "', '", ")", "}", "${", "verb", "}", "`", "}", "if", "(", "type", "===", "'extname'", ")", "{", "const", "verb", "=", "data", ".", "extnames", ".", "length", "===", "1", "?", "'is'", ":", "'are'", "return", "`", "${", "data", ".", "extname", "}", "${", "data", ".", "extnames", ".", "join", "(", "', '", ")", "}", "${", "verb", "}", "`", "}", "}" ]
Returns the error string for given error type @method getError @param {String} type @param {Object} data @return {String}
[ "Returns", "the", "error", "string", "for", "given", "error", "type" ]
11efb935e382c68da531da28d32d9b3d821338da
https://github.com/adonisjs/adonis-bodyparser/blob/11efb935e382c68da531da28d32d9b3d821338da/src/Multipart/File.js#L40-L54
16,572
tikonen/blog
mine/js/game.js
_empty
function _empty( x, y, force ) { if ( x < 0 || x >= that.width || y < 0 || y >= that.height ) return; var pos = that.pos(x, y); var d = that.grid[pos]; if (d && (d & SLAB_MASK) && (force || !(d & APPLE_MASK))) { that.grid[pos] &= ~SLAB_MASK; // clear out slab // Clear next neighbor if this is empty tile if (that.grid[pos] == 0) { _empty(x, y - 1) // north _empty(x, y + 1) // south _empty(x - 1, y) // west _empty(x - 1, y - 1) // north west _empty(x - 1, y + 1) // south east _empty(x + 1, y) // east _empty(x + 1, y - 1) // north east _empty(x + 1, y + 1) // south east } } }
javascript
function _empty( x, y, force ) { if ( x < 0 || x >= that.width || y < 0 || y >= that.height ) return; var pos = that.pos(x, y); var d = that.grid[pos]; if (d && (d & SLAB_MASK) && (force || !(d & APPLE_MASK))) { that.grid[pos] &= ~SLAB_MASK; // clear out slab // Clear next neighbor if this is empty tile if (that.grid[pos] == 0) { _empty(x, y - 1) // north _empty(x, y + 1) // south _empty(x - 1, y) // west _empty(x - 1, y - 1) // north west _empty(x - 1, y + 1) // south east _empty(x + 1, y) // east _empty(x + 1, y - 1) // north east _empty(x + 1, y + 1) // south east } } }
[ "function", "_empty", "(", "x", ",", "y", ",", "force", ")", "{", "if", "(", "x", "<", "0", "||", "x", ">=", "that", ".", "width", "||", "y", "<", "0", "||", "y", ">=", "that", ".", "height", ")", "return", ";", "var", "pos", "=", "that", ".", "pos", "(", "x", ",", "y", ")", ";", "var", "d", "=", "that", ".", "grid", "[", "pos", "]", ";", "if", "(", "d", "&&", "(", "d", "&", "SLAB_MASK", ")", "&&", "(", "force", "||", "!", "(", "d", "&", "APPLE_MASK", ")", ")", ")", "{", "that", ".", "grid", "[", "pos", "]", "&=", "~", "SLAB_MASK", ";", "// clear out slab", "// Clear next neighbor if this is empty tile", "if", "(", "that", ".", "grid", "[", "pos", "]", "==", "0", ")", "{", "_empty", "(", "x", ",", "y", "-", "1", ")", "// north", "_empty", "(", "x", ",", "y", "+", "1", ")", "// south", "_empty", "(", "x", "-", "1", ",", "y", ")", "// west", "_empty", "(", "x", "-", "1", ",", "y", "-", "1", ")", "// north west", "_empty", "(", "x", "-", "1", ",", "y", "+", "1", ")", "// south east", "_empty", "(", "x", "+", "1", ",", "y", ")", "// east", "_empty", "(", "x", "+", "1", ",", "y", "-", "1", ")", "// north east", "_empty", "(", "x", "+", "1", ",", "y", "+", "1", ")", "// south east", "}", "}", "}" ]
Check where click hit Recursive function to clear empty areas
[ "Check", "where", "click", "hit", "Recursive", "function", "to", "clear", "empty", "areas" ]
4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae
https://github.com/tikonen/blog/blob/4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae/mine/js/game.js#L182-L204
16,573
tikonen/blog
simplehttpserver/simplehttpserver.js
directoryHTML
function directoryHTML( res, urldir, pathname, list ) { var ulist = []; function sendHTML( list ) { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.send('<!DOCTYPE html>' + '<html>\n' + '<title>Directory listing for '+htmlsafe(urldir)+'</title>\n' + '<body>\n' + '<h2>Directory listing for '+htmlsafe(urldir)+'</h2>\n' + '<hr><ul>\n' + list.join('\n') + '</ul><hr>\n' + '</body>\n' + '</html>'); } if ( !list.length ) { // Nothing to resolve return sendHTML( ulist ); } // Check for each file if it's a directory or a file var q = async.queue(function(item, cb) { fs.stat(path.join(pathname, item), function(err, stat) { if ( !stat ) cb(); var link = escape(item); item = htmlsafe(item); if ( stat.isDirectory() ) { ulist.push('<li><a href="'+link+'/">'+item+'/</a></li>') } else { ulist.push('<li><a href="'+link+'">'+item+'</a></li>') } cb(); }); }, 4); list.forEach(function(item) { q.push(item); }); q.drain = function() { // Finished checking files, send the response sendHTML(ulist); }; }
javascript
function directoryHTML( res, urldir, pathname, list ) { var ulist = []; function sendHTML( list ) { res.setHeader('Content-Type', 'text/html; charset=utf-8'); res.send('<!DOCTYPE html>' + '<html>\n' + '<title>Directory listing for '+htmlsafe(urldir)+'</title>\n' + '<body>\n' + '<h2>Directory listing for '+htmlsafe(urldir)+'</h2>\n' + '<hr><ul>\n' + list.join('\n') + '</ul><hr>\n' + '</body>\n' + '</html>'); } if ( !list.length ) { // Nothing to resolve return sendHTML( ulist ); } // Check for each file if it's a directory or a file var q = async.queue(function(item, cb) { fs.stat(path.join(pathname, item), function(err, stat) { if ( !stat ) cb(); var link = escape(item); item = htmlsafe(item); if ( stat.isDirectory() ) { ulist.push('<li><a href="'+link+'/">'+item+'/</a></li>') } else { ulist.push('<li><a href="'+link+'">'+item+'</a></li>') } cb(); }); }, 4); list.forEach(function(item) { q.push(item); }); q.drain = function() { // Finished checking files, send the response sendHTML(ulist); }; }
[ "function", "directoryHTML", "(", "res", ",", "urldir", ",", "pathname", ",", "list", ")", "{", "var", "ulist", "=", "[", "]", ";", "function", "sendHTML", "(", "list", ")", "{", "res", ".", "setHeader", "(", "'Content-Type'", ",", "'text/html; charset=utf-8'", ")", ";", "res", ".", "send", "(", "'<!DOCTYPE html>'", "+", "'<html>\\n'", "+", "'<title>Directory listing for '", "+", "htmlsafe", "(", "urldir", ")", "+", "'</title>\\n'", "+", "'<body>\\n'", "+", "'<h2>Directory listing for '", "+", "htmlsafe", "(", "urldir", ")", "+", "'</h2>\\n'", "+", "'<hr><ul>\\n'", "+", "list", ".", "join", "(", "'\\n'", ")", "+", "'</ul><hr>\\n'", "+", "'</body>\\n'", "+", "'</html>'", ")", ";", "}", "if", "(", "!", "list", ".", "length", ")", "{", "// Nothing to resolve", "return", "sendHTML", "(", "ulist", ")", ";", "}", "// Check for each file if it's a directory or a file", "var", "q", "=", "async", ".", "queue", "(", "function", "(", "item", ",", "cb", ")", "{", "fs", ".", "stat", "(", "path", ".", "join", "(", "pathname", ",", "item", ")", ",", "function", "(", "err", ",", "stat", ")", "{", "if", "(", "!", "stat", ")", "cb", "(", ")", ";", "var", "link", "=", "escape", "(", "item", ")", ";", "item", "=", "htmlsafe", "(", "item", ")", ";", "if", "(", "stat", ".", "isDirectory", "(", ")", ")", "{", "ulist", ".", "push", "(", "'<li><a href=\"'", "+", "link", "+", "'/\">'", "+", "item", "+", "'/</a></li>'", ")", "}", "else", "{", "ulist", ".", "push", "(", "'<li><a href=\"'", "+", "link", "+", "'\">'", "+", "item", "+", "'</a></li>'", ")", "}", "cb", "(", ")", ";", "}", ")", ";", "}", ",", "4", ")", ";", "list", ".", "forEach", "(", "function", "(", "item", ")", "{", "q", ".", "push", "(", "item", ")", ";", "}", ")", ";", "q", ".", "drain", "=", "function", "(", ")", "{", "// Finished checking files, send the response", "sendHTML", "(", "ulist", ")", ";", "}", ";", "}" ]
Reads directory content and builds HTML response
[ "Reads", "directory", "content", "and", "builds", "HTML", "response" ]
4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae
https://github.com/tikonen/blog/blob/4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae/simplehttpserver/simplehttpserver.js#L142-L184
16,574
tikonen/blog
slot5/js/slot.js
_check
function _check(err, id) { updateProgress(1); if (err) { alert('Failed to load ' + id + ': ' + err); } loadc++; if (itemc == loadc) callback(); }
javascript
function _check(err, id) { updateProgress(1); if (err) { alert('Failed to load ' + id + ': ' + err); } loadc++; if (itemc == loadc) callback(); }
[ "function", "_check", "(", "err", ",", "id", ")", "{", "updateProgress", "(", "1", ")", ";", "if", "(", "err", ")", "{", "alert", "(", "'Failed to load '", "+", "id", "+", "': '", "+", "err", ")", ";", "}", "loadc", "++", ";", "if", "(", "itemc", "==", "loadc", ")", "callback", "(", ")", ";", "}" ]
called by preloadFunction to notify result
[ "called", "by", "preloadFunction", "to", "notify", "result" ]
4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae
https://github.com/tikonen/blog/blob/4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae/slot5/js/slot.js#L31-L38
16,575
tikonen/blog
slot5/js/slot.js
_fill_canvas
function _fill_canvas(canvas, items) { var ctx = canvas.getContext('2d'); ctx.fillStyle = '#ddd'; for (var i = 0; i < ITEM_COUNT; i++) { var asset = items[i]; ctx.save(); ctx.shadowColor = "rgba(0,0,0,0.5)"; ctx.shadowOffsetX = 5; ctx.shadowOffsetY = 5; ctx.shadowBlur = 5; ctx.drawImage(asset.img, 3, i * SLOT_HEIGHT + IMAGE_TOP_MARGIN); ctx.drawImage(asset.img, 3, (i + ITEM_COUNT) * SLOT_HEIGHT + IMAGE_TOP_MARGIN); ctx.restore(); ctx.fillRect(0, i * SLOT_HEIGHT, 70, SLOT_SEPARATOR_HEIGHT); ctx.fillRect(0, (i + ITEM_COUNT) * SLOT_HEIGHT, 70, SLOT_SEPARATOR_HEIGHT); } }
javascript
function _fill_canvas(canvas, items) { var ctx = canvas.getContext('2d'); ctx.fillStyle = '#ddd'; for (var i = 0; i < ITEM_COUNT; i++) { var asset = items[i]; ctx.save(); ctx.shadowColor = "rgba(0,0,0,0.5)"; ctx.shadowOffsetX = 5; ctx.shadowOffsetY = 5; ctx.shadowBlur = 5; ctx.drawImage(asset.img, 3, i * SLOT_HEIGHT + IMAGE_TOP_MARGIN); ctx.drawImage(asset.img, 3, (i + ITEM_COUNT) * SLOT_HEIGHT + IMAGE_TOP_MARGIN); ctx.restore(); ctx.fillRect(0, i * SLOT_HEIGHT, 70, SLOT_SEPARATOR_HEIGHT); ctx.fillRect(0, (i + ITEM_COUNT) * SLOT_HEIGHT, 70, SLOT_SEPARATOR_HEIGHT); } }
[ "function", "_fill_canvas", "(", "canvas", ",", "items", ")", "{", "var", "ctx", "=", "canvas", ".", "getContext", "(", "'2d'", ")", ";", "ctx", ".", "fillStyle", "=", "'#ddd'", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "ITEM_COUNT", ";", "i", "++", ")", "{", "var", "asset", "=", "items", "[", "i", "]", ";", "ctx", ".", "save", "(", ")", ";", "ctx", ".", "shadowColor", "=", "\"rgba(0,0,0,0.5)\"", ";", "ctx", ".", "shadowOffsetX", "=", "5", ";", "ctx", ".", "shadowOffsetY", "=", "5", ";", "ctx", ".", "shadowBlur", "=", "5", ";", "ctx", ".", "drawImage", "(", "asset", ".", "img", ",", "3", ",", "i", "*", "SLOT_HEIGHT", "+", "IMAGE_TOP_MARGIN", ")", ";", "ctx", ".", "drawImage", "(", "asset", ".", "img", ",", "3", ",", "(", "i", "+", "ITEM_COUNT", ")", "*", "SLOT_HEIGHT", "+", "IMAGE_TOP_MARGIN", ")", ";", "ctx", ".", "restore", "(", ")", ";", "ctx", ".", "fillRect", "(", "0", ",", "i", "*", "SLOT_HEIGHT", ",", "70", ",", "SLOT_SEPARATOR_HEIGHT", ")", ";", "ctx", ".", "fillRect", "(", "0", ",", "(", "i", "+", "ITEM_COUNT", ")", "*", "SLOT_HEIGHT", ",", "70", ",", "SLOT_SEPARATOR_HEIGHT", ")", ";", "}", "}" ]
all loaded draws canvas strip
[ "all", "loaded", "draws", "canvas", "strip" ]
4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae
https://github.com/tikonen/blog/blob/4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae/slot5/js/slot.js#L289-L306
16,576
tikonen/blog
slot5/js/slot.js
_find
function _find( items, id ) { for ( var i=0; i < items.length; i++ ) { if (items[i].id == id) return i; } }
javascript
function _find( items, id ) { for ( var i=0; i < items.length; i++ ) { if (items[i].id == id) return i; } }
[ "function", "_find", "(", "items", ",", "id", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "++", ")", "{", "if", "(", "items", "[", "i", "]", ".", "id", "==", "id", ")", "return", "i", ";", "}", "}" ]
function locates id from items
[ "function", "locates", "id", "from", "items" ]
4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae
https://github.com/tikonen/blog/blob/4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae/slot5/js/slot.js#L400-L404
16,577
tikonen/blog
slot5/js/slot.js
_check_slot
function _check_slot(offset, result) { if (now - that.lastUpdate > SPINTIME) { var c = parseInt(Math.abs(offset / SLOT_HEIGHT)) % ITEM_COUNT; if (c == result) { if (result == 0) { if (Math.abs(offset + (ITEM_COUNT * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) { return true; // done } } else if (Math.abs(offset + (result * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) { return true; // done } } } return false; }
javascript
function _check_slot(offset, result) { if (now - that.lastUpdate > SPINTIME) { var c = parseInt(Math.abs(offset / SLOT_HEIGHT)) % ITEM_COUNT; if (c == result) { if (result == 0) { if (Math.abs(offset + (ITEM_COUNT * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) { return true; // done } } else if (Math.abs(offset + (result * SLOT_HEIGHT)) < (SLOT_SPEED * 1.5)) { return true; // done } } } return false; }
[ "function", "_check_slot", "(", "offset", ",", "result", ")", "{", "if", "(", "now", "-", "that", ".", "lastUpdate", ">", "SPINTIME", ")", "{", "var", "c", "=", "parseInt", "(", "Math", ".", "abs", "(", "offset", "/", "SLOT_HEIGHT", ")", ")", "%", "ITEM_COUNT", ";", "if", "(", "c", "==", "result", ")", "{", "if", "(", "result", "==", "0", ")", "{", "if", "(", "Math", ".", "abs", "(", "offset", "+", "(", "ITEM_COUNT", "*", "SLOT_HEIGHT", ")", ")", "<", "(", "SLOT_SPEED", "*", "1.5", ")", ")", "{", "return", "true", ";", "// done", "}", "}", "else", "if", "(", "Math", ".", "abs", "(", "offset", "+", "(", "result", "*", "SLOT_HEIGHT", ")", ")", "<", "(", "SLOT_SPEED", "*", "1.5", ")", ")", "{", "return", "true", ";", "// done", "}", "}", "}", "return", "false", ";", "}" ]
Check slot status and if spun long enough stop it on result
[ "Check", "slot", "status", "and", "if", "spun", "long", "enough", "stop", "it", "on", "result" ]
4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae
https://github.com/tikonen/blog/blob/4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae/slot5/js/slot.js#L478-L492
16,578
tikonen/blog
slot2/js/slot.js
initAudio
function initAudio( audios, callback ) { var format = 'mp3'; var elem = document.createElement('audio'); if ( elem ) { // Check if we can play mp3, if not then fall back to ogg if( !elem.canPlayType( 'audio/mpeg;' ) && elem.canPlayType('audio/ogg;')) format = 'ogg'; } var AudioContext = window.webkitAudioContext || window.mozAudioContext || window.MSAudioContext || window.AudioContext; if ( AudioContext ) { $('#audio_debug').text('WebAudio Supported'); // Browser supports webaudio // https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html return _initWebAudio( AudioContext, format, audios, callback ); } else if ( elem ) { $('#audio_debug').text('HTML5 Audio Supported'); // HTML5 Audio // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#the-audio-element return _initHTML5Audio(format, audios, callback); } else { $('#audio_debug').text('Audio NOT Supported'); // audio not supported audios.forEach(function(item) { item.play = function() {}; // dummy play }); callback(); } }
javascript
function initAudio( audios, callback ) { var format = 'mp3'; var elem = document.createElement('audio'); if ( elem ) { // Check if we can play mp3, if not then fall back to ogg if( !elem.canPlayType( 'audio/mpeg;' ) && elem.canPlayType('audio/ogg;')) format = 'ogg'; } var AudioContext = window.webkitAudioContext || window.mozAudioContext || window.MSAudioContext || window.AudioContext; if ( AudioContext ) { $('#audio_debug').text('WebAudio Supported'); // Browser supports webaudio // https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html return _initWebAudio( AudioContext, format, audios, callback ); } else if ( elem ) { $('#audio_debug').text('HTML5 Audio Supported'); // HTML5 Audio // http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#the-audio-element return _initHTML5Audio(format, audios, callback); } else { $('#audio_debug').text('Audio NOT Supported'); // audio not supported audios.forEach(function(item) { item.play = function() {}; // dummy play }); callback(); } }
[ "function", "initAudio", "(", "audios", ",", "callback", ")", "{", "var", "format", "=", "'mp3'", ";", "var", "elem", "=", "document", ".", "createElement", "(", "'audio'", ")", ";", "if", "(", "elem", ")", "{", "// Check if we can play mp3, if not then fall back to ogg", "if", "(", "!", "elem", ".", "canPlayType", "(", "'audio/mpeg;'", ")", "&&", "elem", ".", "canPlayType", "(", "'audio/ogg;'", ")", ")", "format", "=", "'ogg'", ";", "}", "var", "AudioContext", "=", "window", ".", "webkitAudioContext", "||", "window", ".", "mozAudioContext", "||", "window", ".", "MSAudioContext", "||", "window", ".", "AudioContext", ";", "if", "(", "AudioContext", ")", "{", "$", "(", "'#audio_debug'", ")", ".", "text", "(", "'WebAudio Supported'", ")", ";", "// Browser supports webaudio", "// https://dvcs.w3.org/hg/audio/raw-file/tip/webaudio/specification.html", "return", "_initWebAudio", "(", "AudioContext", ",", "format", ",", "audios", ",", "callback", ")", ";", "}", "else", "if", "(", "elem", ")", "{", "$", "(", "'#audio_debug'", ")", ".", "text", "(", "'HTML5 Audio Supported'", ")", ";", "// HTML5 Audio", "// http://www.whatwg.org/specs/web-apps/current-work/multipage/the-video-element.html#the-audio-element", "return", "_initHTML5Audio", "(", "format", ",", "audios", ",", "callback", ")", ";", "}", "else", "{", "$", "(", "'#audio_debug'", ")", ".", "text", "(", "'Audio NOT Supported'", ")", ";", "// audio not supported", "audios", ".", "forEach", "(", "function", "(", "item", ")", "{", "item", ".", "play", "=", "function", "(", ")", "{", "}", ";", "// dummy play", "}", ")", ";", "callback", "(", ")", ";", "}", "}" ]
Initializes audio and loads audio files
[ "Initializes", "audio", "and", "loads", "audio", "files" ]
4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae
https://github.com/tikonen/blog/blob/4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae/slot2/js/slot.js#L156-L185
16,579
tikonen/blog
drive/js/drive.js
_build_object
function _build_object( game, x, y, speed ) { var car_asset = game.carAssets[parseInt(Math.random()*game.carAssets.length)] var framex = car_asset.w * parseInt(Math.random() * car_asset.count); return { collided: 0, width: car_asset.w, height: car_asset.h, img: car_asset.img, framex: framex, pos: { x: x, y: y }, speed: speed, cleanup: function() { if (this.bubble) { this.bubble.remove(); } }, update: function( t ) { if (this.collided > 2 && !this.bubble) { this.collided = 0; this.bubble = $('<div class="bubble">'+BLURB_TBL[parseInt(Math.random()*BLURB_TBL.length)]+'</div>').appendTo('#area'); this.bubble.css({ left: this.pos.x - 30, top: this.pos.y - 20 }) this.bubbleEnd = t + 1000; } else if (this.bubbleEnd < t) { this.bubble.remove(); } else if (this.bubble) { this.bubble.css({ left: this.pos.x - 30, top: this.pos.y - 20 }) } }, clear: function( ctx ) { ctx.clearRect( this.pos.x - 1, this.pos.y - 1, this.width + 1 , this.height + 1 ); }, draw: function( ctx ) { ctx.drawImage( this.img, this.framex, 0, this.width, this.height, this.pos.x, this.pos.y, this.width, this.height ); } } }
javascript
function _build_object( game, x, y, speed ) { var car_asset = game.carAssets[parseInt(Math.random()*game.carAssets.length)] var framex = car_asset.w * parseInt(Math.random() * car_asset.count); return { collided: 0, width: car_asset.w, height: car_asset.h, img: car_asset.img, framex: framex, pos: { x: x, y: y }, speed: speed, cleanup: function() { if (this.bubble) { this.bubble.remove(); } }, update: function( t ) { if (this.collided > 2 && !this.bubble) { this.collided = 0; this.bubble = $('<div class="bubble">'+BLURB_TBL[parseInt(Math.random()*BLURB_TBL.length)]+'</div>').appendTo('#area'); this.bubble.css({ left: this.pos.x - 30, top: this.pos.y - 20 }) this.bubbleEnd = t + 1000; } else if (this.bubbleEnd < t) { this.bubble.remove(); } else if (this.bubble) { this.bubble.css({ left: this.pos.x - 30, top: this.pos.y - 20 }) } }, clear: function( ctx ) { ctx.clearRect( this.pos.x - 1, this.pos.y - 1, this.width + 1 , this.height + 1 ); }, draw: function( ctx ) { ctx.drawImage( this.img, this.framex, 0, this.width, this.height, this.pos.x, this.pos.y, this.width, this.height ); } } }
[ "function", "_build_object", "(", "game", ",", "x", ",", "y", ",", "speed", ")", "{", "var", "car_asset", "=", "game", ".", "carAssets", "[", "parseInt", "(", "Math", ".", "random", "(", ")", "*", "game", ".", "carAssets", ".", "length", ")", "]", "var", "framex", "=", "car_asset", ".", "w", "*", "parseInt", "(", "Math", ".", "random", "(", ")", "*", "car_asset", ".", "count", ")", ";", "return", "{", "collided", ":", "0", ",", "width", ":", "car_asset", ".", "w", ",", "height", ":", "car_asset", ".", "h", ",", "img", ":", "car_asset", ".", "img", ",", "framex", ":", "framex", ",", "pos", ":", "{", "x", ":", "x", ",", "y", ":", "y", "}", ",", "speed", ":", "speed", ",", "cleanup", ":", "function", "(", ")", "{", "if", "(", "this", ".", "bubble", ")", "{", "this", ".", "bubble", ".", "remove", "(", ")", ";", "}", "}", ",", "update", ":", "function", "(", "t", ")", "{", "if", "(", "this", ".", "collided", ">", "2", "&&", "!", "this", ".", "bubble", ")", "{", "this", ".", "collided", "=", "0", ";", "this", ".", "bubble", "=", "$", "(", "'<div class=\"bubble\">'", "+", "BLURB_TBL", "[", "parseInt", "(", "Math", ".", "random", "(", ")", "*", "BLURB_TBL", ".", "length", ")", "]", "+", "'</div>'", ")", ".", "appendTo", "(", "'#area'", ")", ";", "this", ".", "bubble", ".", "css", "(", "{", "left", ":", "this", ".", "pos", ".", "x", "-", "30", ",", "top", ":", "this", ".", "pos", ".", "y", "-", "20", "}", ")", "this", ".", "bubbleEnd", "=", "t", "+", "1000", ";", "}", "else", "if", "(", "this", ".", "bubbleEnd", "<", "t", ")", "{", "this", ".", "bubble", ".", "remove", "(", ")", ";", "}", "else", "if", "(", "this", ".", "bubble", ")", "{", "this", ".", "bubble", ".", "css", "(", "{", "left", ":", "this", ".", "pos", ".", "x", "-", "30", ",", "top", ":", "this", ".", "pos", ".", "y", "-", "20", "}", ")", "}", "}", ",", "clear", ":", "function", "(", "ctx", ")", "{", "ctx", ".", "clearRect", "(", "this", ".", "pos", ".", "x", "-", "1", ",", "this", ".", "pos", ".", "y", "-", "1", ",", "this", ".", "width", "+", "1", ",", "this", ".", "height", "+", "1", ")", ";", "}", ",", "draw", ":", "function", "(", "ctx", ")", "{", "ctx", ".", "drawImage", "(", "this", ".", "img", ",", "this", ".", "framex", ",", "0", ",", "this", ".", "width", ",", "this", ".", "height", ",", "this", ".", "pos", ".", "x", ",", "this", ".", "pos", ".", "y", ",", "this", ".", "width", ",", "this", ".", "height", ")", ";", "}", "}", "}" ]
Add car in game
[ "Add", "car", "in", "game" ]
4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae
https://github.com/tikonen/blog/blob/4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae/drive/js/drive.js#L161-L208
16,580
tikonen/blog
biased/biased.js
select
function select(elems) { var r = Math.random(); var ref = 0; for(var i=0; i < elems.length; i++) { var elem= elems[i]; ref += elem[1]; if (r < ref) return elem[0]; } // This happens only if probabilities don't add up to 1 return null; }
javascript
function select(elems) { var r = Math.random(); var ref = 0; for(var i=0; i < elems.length; i++) { var elem= elems[i]; ref += elem[1]; if (r < ref) return elem[0]; } // This happens only if probabilities don't add up to 1 return null; }
[ "function", "select", "(", "elems", ")", "{", "var", "r", "=", "Math", ".", "random", "(", ")", ";", "var", "ref", "=", "0", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "elems", ".", "length", ";", "i", "++", ")", "{", "var", "elem", "=", "elems", "[", "i", "]", ";", "ref", "+=", "elem", "[", "1", "]", ";", "if", "(", "r", "<", "ref", ")", "return", "elem", "[", "0", "]", ";", "}", "// This happens only if probabilities don't add up to 1", "return", "null", ";", "}" ]
Biased random entry selection
[ "Biased", "random", "entry", "selection" ]
4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae
https://github.com/tikonen/blog/blob/4de49cd56886e107ee0b20c1bf6c3e5e4bbb5eae/biased/biased.js#L4-L16
16,581
bustle/shep
src/util/aws/lambda.js
configStripper
function configStripper (c) { return { DeadLetterConfig: c.DeadLetterConfig, Description: c.Description, Environment: c.Environment, Handler: c.Handler, MemorySize: c.MemorySize, Role: c.Role, Runtime: c.Runtime, Timeout: c.Timeout, TracingConfig: c.TracingConfig } }
javascript
function configStripper (c) { return { DeadLetterConfig: c.DeadLetterConfig, Description: c.Description, Environment: c.Environment, Handler: c.Handler, MemorySize: c.MemorySize, Role: c.Role, Runtime: c.Runtime, Timeout: c.Timeout, TracingConfig: c.TracingConfig } }
[ "function", "configStripper", "(", "c", ")", "{", "return", "{", "DeadLetterConfig", ":", "c", ".", "DeadLetterConfig", ",", "Description", ":", "c", ".", "Description", ",", "Environment", ":", "c", ".", "Environment", ",", "Handler", ":", "c", ".", "Handler", ",", "MemorySize", ":", "c", ".", "MemorySize", ",", "Role", ":", "c", ".", "Role", ",", "Runtime", ":", "c", ".", "Runtime", ",", "Timeout", ":", "c", ".", "Timeout", ",", "TracingConfig", ":", "c", ".", "TracingConfig", "}", "}" ]
should beef this up for VpcConfig can only pass SecurityGroupIds and SubnetIds
[ "should", "beef", "this", "up", "for", "VpcConfig", "can", "only", "pass", "SecurityGroupIds", "and", "SubnetIds" ]
a5bbdd27209f5079c12eb98a456d2a2f91a4af8a
https://github.com/bustle/shep/blob/a5bbdd27209f5079c12eb98a456d2a2f91a4af8a/src/util/aws/lambda.js#L160-L172
16,582
TencentWSRD/connect-cas2
lib/validate.js
validateTicket
function validateTicket(req, options, callback) { var query = { service: utils.getPath('service', options), ticket: req.query.ticket }; var logger = utils.getLogger(req, options); if (options.paths.proxyCallback) query.pgtUrl = utils.getPath('pgtUrl', options); var casServerValidPath = utils.getPath('serviceValidate', options) + '?' + queryString.stringify(query); logger.info('Sending request to: "' + casServerValidPath + '" to validate ticket.'); var startTime = Date.now(); utils.getRequest(casServerValidPath, function(err, response) { /* istanbul ignore if */ logger.access('|GET|' + casServerValidPath + '|' + (err ? 500 : response.status) + "|" + (Date.now() - startTime)); if (err) { logger.error('Error when sending request to CAS server, error: ', err.toString()); logger.error(err); return callback(err); } callback(null, response); }); }
javascript
function validateTicket(req, options, callback) { var query = { service: utils.getPath('service', options), ticket: req.query.ticket }; var logger = utils.getLogger(req, options); if (options.paths.proxyCallback) query.pgtUrl = utils.getPath('pgtUrl', options); var casServerValidPath = utils.getPath('serviceValidate', options) + '?' + queryString.stringify(query); logger.info('Sending request to: "' + casServerValidPath + '" to validate ticket.'); var startTime = Date.now(); utils.getRequest(casServerValidPath, function(err, response) { /* istanbul ignore if */ logger.access('|GET|' + casServerValidPath + '|' + (err ? 500 : response.status) + "|" + (Date.now() - startTime)); if (err) { logger.error('Error when sending request to CAS server, error: ', err.toString()); logger.error(err); return callback(err); } callback(null, response); }); }
[ "function", "validateTicket", "(", "req", ",", "options", ",", "callback", ")", "{", "var", "query", "=", "{", "service", ":", "utils", ".", "getPath", "(", "'service'", ",", "options", ")", ",", "ticket", ":", "req", ".", "query", ".", "ticket", "}", ";", "var", "logger", "=", "utils", ".", "getLogger", "(", "req", ",", "options", ")", ";", "if", "(", "options", ".", "paths", ".", "proxyCallback", ")", "query", ".", "pgtUrl", "=", "utils", ".", "getPath", "(", "'pgtUrl'", ",", "options", ")", ";", "var", "casServerValidPath", "=", "utils", ".", "getPath", "(", "'serviceValidate'", ",", "options", ")", "+", "'?'", "+", "queryString", ".", "stringify", "(", "query", ")", ";", "logger", ".", "info", "(", "'Sending request to: \"'", "+", "casServerValidPath", "+", "'\" to validate ticket.'", ")", ";", "var", "startTime", "=", "Date", ".", "now", "(", ")", ";", "utils", ".", "getRequest", "(", "casServerValidPath", ",", "function", "(", "err", ",", "response", ")", "{", "/* istanbul ignore if */", "logger", ".", "access", "(", "'|GET|'", "+", "casServerValidPath", "+", "'|'", "+", "(", "err", "?", "500", ":", "response", ".", "status", ")", "+", "\"|\"", "+", "(", "Date", ".", "now", "(", ")", "-", "startTime", ")", ")", ";", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "'Error when sending request to CAS server, error: '", ",", "err", ".", "toString", "(", ")", ")", ";", "logger", ".", "error", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "callback", "(", "null", ",", "response", ")", ";", "}", ")", ";", "}" ]
Validate ticket from CAS server @param req @param options @param callback
[ "Validate", "ticket", "from", "CAS", "server" ]
b01415629abc08bb4a462873c0d53577481bd52d
https://github.com/TencentWSRD/connect-cas2/blob/b01415629abc08bb4a462873c0d53577481bd52d/lib/validate.js#L151-L175
16,583
TencentWSRD/connect-cas2
lib/validate.js
retrievePGTFromPGTIOU
function retrievePGTFromPGTIOU(req, res, callback, pgtIou, options) { var logger = utils.getLogger(req, options); logger.info('Trying to retrieve pgtId from pgtIou...'); req.sessionStore.get(pgtIou, function(err, session) { /* istanbul ignore if */ if (err) { logger.error('Get pgtId from sessionStore failed!'); logger.error(err); req.sessionStore.destroy(pgtIou); return callback(function(req, res, next) { res.status(500).send({ message: 'Get pgtId from sessionStore failed!', error: err }); }); } if (session && session.pgtId) { var lastUrl = utils.getLastUrl(req, options, logger); if (!req.session || req.session && !req.session.cas) { logger.error('Here session.cas should not be empty!', req.session); req.session.cas = {}; } req.session.cas.pgt = session.pgtId; req.session.save(function(err) { /* istanbul ignore if */ if (err) { logger.error('Trying to save session failed!'); logger.error(err); return callback(function(req, res, next) { res.status(500).send({ message: 'Trying to save session failed!', error: err }); }); } // 释放 req.sessionStore.destroy(pgtIou); /* istanbul ignore if */ // 测一次就够了 lastUrl = getLastUrl(req, res, options, logger, lastUrl); logger.info('CAS proxy mode login and validation succeed, pgtId finded. Redirecting to lastUrl: ' + lastUrl); return callback(function(req, res, next) { res.redirect(302, lastUrl); }); }); } else { logger.error('CAS proxy mode login and validation succeed, but can\' find pgtId from pgtIou: `' + pgtIou + '`, maybe something wrong with sessionStroe!'); callback(function(req, res, next) { res.status(401).send({ message: 'CAS proxy mode login and validation succeed, but can\' find pgtId from pgtIou: `' + pgtIou + '`, maybe something wrong with sessionStroe!' }); }); } }); }
javascript
function retrievePGTFromPGTIOU(req, res, callback, pgtIou, options) { var logger = utils.getLogger(req, options); logger.info('Trying to retrieve pgtId from pgtIou...'); req.sessionStore.get(pgtIou, function(err, session) { /* istanbul ignore if */ if (err) { logger.error('Get pgtId from sessionStore failed!'); logger.error(err); req.sessionStore.destroy(pgtIou); return callback(function(req, res, next) { res.status(500).send({ message: 'Get pgtId from sessionStore failed!', error: err }); }); } if (session && session.pgtId) { var lastUrl = utils.getLastUrl(req, options, logger); if (!req.session || req.session && !req.session.cas) { logger.error('Here session.cas should not be empty!', req.session); req.session.cas = {}; } req.session.cas.pgt = session.pgtId; req.session.save(function(err) { /* istanbul ignore if */ if (err) { logger.error('Trying to save session failed!'); logger.error(err); return callback(function(req, res, next) { res.status(500).send({ message: 'Trying to save session failed!', error: err }); }); } // 释放 req.sessionStore.destroy(pgtIou); /* istanbul ignore if */ // 测一次就够了 lastUrl = getLastUrl(req, res, options, logger, lastUrl); logger.info('CAS proxy mode login and validation succeed, pgtId finded. Redirecting to lastUrl: ' + lastUrl); return callback(function(req, res, next) { res.redirect(302, lastUrl); }); }); } else { logger.error('CAS proxy mode login and validation succeed, but can\' find pgtId from pgtIou: `' + pgtIou + '`, maybe something wrong with sessionStroe!'); callback(function(req, res, next) { res.status(401).send({ message: 'CAS proxy mode login and validation succeed, but can\' find pgtId from pgtIou: `' + pgtIou + '`, maybe something wrong with sessionStroe!' }); }); } }); }
[ "function", "retrievePGTFromPGTIOU", "(", "req", ",", "res", ",", "callback", ",", "pgtIou", ",", "options", ")", "{", "var", "logger", "=", "utils", ".", "getLogger", "(", "req", ",", "options", ")", ";", "logger", ".", "info", "(", "'Trying to retrieve pgtId from pgtIou...'", ")", ";", "req", ".", "sessionStore", ".", "get", "(", "pgtIou", ",", "function", "(", "err", ",", "session", ")", "{", "/* istanbul ignore if */", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "'Get pgtId from sessionStore failed!'", ")", ";", "logger", ".", "error", "(", "err", ")", ";", "req", ".", "sessionStore", ".", "destroy", "(", "pgtIou", ")", ";", "return", "callback", "(", "function", "(", "req", ",", "res", ",", "next", ")", "{", "res", ".", "status", "(", "500", ")", ".", "send", "(", "{", "message", ":", "'Get pgtId from sessionStore failed!'", ",", "error", ":", "err", "}", ")", ";", "}", ")", ";", "}", "if", "(", "session", "&&", "session", ".", "pgtId", ")", "{", "var", "lastUrl", "=", "utils", ".", "getLastUrl", "(", "req", ",", "options", ",", "logger", ")", ";", "if", "(", "!", "req", ".", "session", "||", "req", ".", "session", "&&", "!", "req", ".", "session", ".", "cas", ")", "{", "logger", ".", "error", "(", "'Here session.cas should not be empty!'", ",", "req", ".", "session", ")", ";", "req", ".", "session", ".", "cas", "=", "{", "}", ";", "}", "req", ".", "session", ".", "cas", ".", "pgt", "=", "session", ".", "pgtId", ";", "req", ".", "session", ".", "save", "(", "function", "(", "err", ")", "{", "/* istanbul ignore if */", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "'Trying to save session failed!'", ")", ";", "logger", ".", "error", "(", "err", ")", ";", "return", "callback", "(", "function", "(", "req", ",", "res", ",", "next", ")", "{", "res", ".", "status", "(", "500", ")", ".", "send", "(", "{", "message", ":", "'Trying to save session failed!'", ",", "error", ":", "err", "}", ")", ";", "}", ")", ";", "}", "// 释放", "req", ".", "sessionStore", ".", "destroy", "(", "pgtIou", ")", ";", "/* istanbul ignore if */", "// 测一次就够了", "lastUrl", "=", "getLastUrl", "(", "req", ",", "res", ",", "options", ",", "logger", ",", "lastUrl", ")", ";", "logger", ".", "info", "(", "'CAS proxy mode login and validation succeed, pgtId finded. Redirecting to lastUrl: '", "+", "lastUrl", ")", ";", "return", "callback", "(", "function", "(", "req", ",", "res", ",", "next", ")", "{", "res", ".", "redirect", "(", "302", ",", "lastUrl", ")", ";", "}", ")", ";", "}", ")", ";", "}", "else", "{", "logger", ".", "error", "(", "'CAS proxy mode login and validation succeed, but can\\' find pgtId from pgtIou: `'", "+", "pgtIou", "+", "'`, maybe something wrong with sessionStroe!'", ")", ";", "callback", "(", "function", "(", "req", ",", "res", ",", "next", ")", "{", "res", ".", "status", "(", "401", ")", ".", "send", "(", "{", "message", ":", "'CAS proxy mode login and validation succeed, but can\\' find pgtId from pgtIou: `'", "+", "pgtIou", "+", "'`, maybe something wrong with sessionStroe!'", "}", ")", ";", "}", ")", ";", "}", "}", ")", ";", "}" ]
Find PGT by PGTIOU @param req @param res @param callback @param pgtIou @param options
[ "Find", "PGT", "by", "PGTIOU" ]
b01415629abc08bb4a462873c0d53577481bd52d
https://github.com/TencentWSRD/connect-cas2/blob/b01415629abc08bb4a462873c0d53577481bd52d/lib/validate.js#L231-L292
16,584
TencentWSRD/connect-cas2
lib/getProxyTicket.js
requestPT
function requestPT(path, callback, retryHandler) { logger.info('Trying to request proxy ticket from ', proxyPath); var startTime = Date.now(); utils.getRequest(path, function(err, response) { /* istanbul ignore if */ logger.access('|GET|' + path + '|' + (err ? 500 : response.status) + "|" + (Date.now() - startTime)); if (err) { logger.error('Error happened when sending request to: ' + path); logger.error(err); return callback(err); } if (response.status !== 200) { logger.error('Request fail when trying to get proxy ticket', response); if (typeof retryHandler === 'function') return retryHandler(err); return callback(new Error('Request fail when trying to get proxy ticket, response status: ' + response.status + ', response body: ' + response.body)); } var pt = parseCasResponse(response.body); if (pt) { logger.info('Request proxy ticket succeed, receive pt: ', pt); callback(null, pt); } else { logger.error('Can\' get pt from get proxy ticket response.'); logger.error('Request for PT succeed, but response is invalid, response: ', response.body); if (typeof retryHandler === 'function') return retryHandler(new Error('Request for PT succeed, but response is invalid, response: ' + response.body)); return callback(new Error('Request for PT succeed, but the response is invalid, response: ' + response.body)); } }); }
javascript
function requestPT(path, callback, retryHandler) { logger.info('Trying to request proxy ticket from ', proxyPath); var startTime = Date.now(); utils.getRequest(path, function(err, response) { /* istanbul ignore if */ logger.access('|GET|' + path + '|' + (err ? 500 : response.status) + "|" + (Date.now() - startTime)); if (err) { logger.error('Error happened when sending request to: ' + path); logger.error(err); return callback(err); } if (response.status !== 200) { logger.error('Request fail when trying to get proxy ticket', response); if (typeof retryHandler === 'function') return retryHandler(err); return callback(new Error('Request fail when trying to get proxy ticket, response status: ' + response.status + ', response body: ' + response.body)); } var pt = parseCasResponse(response.body); if (pt) { logger.info('Request proxy ticket succeed, receive pt: ', pt); callback(null, pt); } else { logger.error('Can\' get pt from get proxy ticket response.'); logger.error('Request for PT succeed, but response is invalid, response: ', response.body); if (typeof retryHandler === 'function') return retryHandler(new Error('Request for PT succeed, but response is invalid, response: ' + response.body)); return callback(new Error('Request for PT succeed, but the response is invalid, response: ' + response.body)); } }); }
[ "function", "requestPT", "(", "path", ",", "callback", ",", "retryHandler", ")", "{", "logger", ".", "info", "(", "'Trying to request proxy ticket from '", ",", "proxyPath", ")", ";", "var", "startTime", "=", "Date", ".", "now", "(", ")", ";", "utils", ".", "getRequest", "(", "path", ",", "function", "(", "err", ",", "response", ")", "{", "/* istanbul ignore if */", "logger", ".", "access", "(", "'|GET|'", "+", "path", "+", "'|'", "+", "(", "err", "?", "500", ":", "response", ".", "status", ")", "+", "\"|\"", "+", "(", "Date", ".", "now", "(", ")", "-", "startTime", ")", ")", ";", "if", "(", "err", ")", "{", "logger", ".", "error", "(", "'Error happened when sending request to: '", "+", "path", ")", ";", "logger", ".", "error", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "if", "(", "response", ".", "status", "!==", "200", ")", "{", "logger", ".", "error", "(", "'Request fail when trying to get proxy ticket'", ",", "response", ")", ";", "if", "(", "typeof", "retryHandler", "===", "'function'", ")", "return", "retryHandler", "(", "err", ")", ";", "return", "callback", "(", "new", "Error", "(", "'Request fail when trying to get proxy ticket, response status: '", "+", "response", ".", "status", "+", "', response body: '", "+", "response", ".", "body", ")", ")", ";", "}", "var", "pt", "=", "parseCasResponse", "(", "response", ".", "body", ")", ";", "if", "(", "pt", ")", "{", "logger", ".", "info", "(", "'Request proxy ticket succeed, receive pt: '", ",", "pt", ")", ";", "callback", "(", "null", ",", "pt", ")", ";", "}", "else", "{", "logger", ".", "error", "(", "'Can\\' get pt from get proxy ticket response.'", ")", ";", "logger", ".", "error", "(", "'Request for PT succeed, but response is invalid, response: '", ",", "response", ".", "body", ")", ";", "if", "(", "typeof", "retryHandler", "===", "'function'", ")", "return", "retryHandler", "(", "new", "Error", "(", "'Request for PT succeed, but response is invalid, response: '", "+", "response", ".", "body", ")", ")", ";", "return", "callback", "(", "new", "Error", "(", "'Request for PT succeed, but the response is invalid, response: '", "+", "response", ".", "body", ")", ")", ";", "}", "}", ")", ";", "}" ]
Request a proxy ticket @param req @param path @param callback @param {Function} retryHandler If this callback is set, it will be called only if request failed due to authentication issue.
[ "Request", "a", "proxy", "ticket" ]
b01415629abc08bb4a462873c0d53577481bd52d
https://github.com/TencentWSRD/connect-cas2/blob/b01415629abc08bb4a462873c0d53577481bd52d/lib/getProxyTicket.js#L159-L191
16,585
TencentWSRD/connect-cas2
lib/utils.js
isMatchRule
function isMatchRule(req, pathname, rule) { if (typeof rule === 'string') { return pathname.indexOf(rule) > -1; } else if (rule instanceof RegExp) { return rule.test(pathname); } else if (typeof rule === 'function') { return rule(pathname, req); } }
javascript
function isMatchRule(req, pathname, rule) { if (typeof rule === 'string') { return pathname.indexOf(rule) > -1; } else if (rule instanceof RegExp) { return rule.test(pathname); } else if (typeof rule === 'function') { return rule(pathname, req); } }
[ "function", "isMatchRule", "(", "req", ",", "pathname", ",", "rule", ")", "{", "if", "(", "typeof", "rule", "===", "'string'", ")", "{", "return", "pathname", ".", "indexOf", "(", "rule", ")", ">", "-", "1", ";", "}", "else", "if", "(", "rule", "instanceof", "RegExp", ")", "{", "return", "rule", ".", "test", "(", "pathname", ")", ";", "}", "else", "if", "(", "typeof", "rule", "===", "'function'", ")", "{", "return", "rule", "(", "pathname", ",", "req", ")", ";", "}", "}" ]
Return `true` when pathname match the rule. @param req @param pathname @param rule @returns {*}
[ "Return", "true", "when", "pathname", "match", "the", "rule", "." ]
b01415629abc08bb4a462873c0d53577481bd52d
https://github.com/TencentWSRD/connect-cas2/blob/b01415629abc08bb4a462873c0d53577481bd52d/lib/utils.js#L16-L24
16,586
TencentWSRD/connect-cas2
lib/utils.js
shouldIgnore
function shouldIgnore(req, options) { var logger = getLogger(req, options); if (options.match && options.match.splice && options.match.length) { var matchedRule; var hasMatch = options.match.some(function (rule) { matchedRule = rule; return isMatchRule(req, req.path, rule); }); if (hasMatch) { logger.info('Matched match rule.', matchedRule, ' Go into CAS authentication.'); return false; } return true; } if (options.ignore && options.ignore.splice && options.ignore.length) { var matchedIgnoreRule; var hasMatchIgnore = options.ignore.some(function (rule) { matchedIgnoreRule = rule; return isMatchRule(req, req.path, rule); }); if (hasMatchIgnore) { logger.info('Matched ignore rule.', matchedIgnoreRule, ' Go through CAS.'); return true; } return false; } return false; }
javascript
function shouldIgnore(req, options) { var logger = getLogger(req, options); if (options.match && options.match.splice && options.match.length) { var matchedRule; var hasMatch = options.match.some(function (rule) { matchedRule = rule; return isMatchRule(req, req.path, rule); }); if (hasMatch) { logger.info('Matched match rule.', matchedRule, ' Go into CAS authentication.'); return false; } return true; } if (options.ignore && options.ignore.splice && options.ignore.length) { var matchedIgnoreRule; var hasMatchIgnore = options.ignore.some(function (rule) { matchedIgnoreRule = rule; return isMatchRule(req, req.path, rule); }); if (hasMatchIgnore) { logger.info('Matched ignore rule.', matchedIgnoreRule, ' Go through CAS.'); return true; } return false; } return false; }
[ "function", "shouldIgnore", "(", "req", ",", "options", ")", "{", "var", "logger", "=", "getLogger", "(", "req", ",", "options", ")", ";", "if", "(", "options", ".", "match", "&&", "options", ".", "match", ".", "splice", "&&", "options", ".", "match", ".", "length", ")", "{", "var", "matchedRule", ";", "var", "hasMatch", "=", "options", ".", "match", ".", "some", "(", "function", "(", "rule", ")", "{", "matchedRule", "=", "rule", ";", "return", "isMatchRule", "(", "req", ",", "req", ".", "path", ",", "rule", ")", ";", "}", ")", ";", "if", "(", "hasMatch", ")", "{", "logger", ".", "info", "(", "'Matched match rule.'", ",", "matchedRule", ",", "' Go into CAS authentication.'", ")", ";", "return", "false", ";", "}", "return", "true", ";", "}", "if", "(", "options", ".", "ignore", "&&", "options", ".", "ignore", ".", "splice", "&&", "options", ".", "ignore", ".", "length", ")", "{", "var", "matchedIgnoreRule", ";", "var", "hasMatchIgnore", "=", "options", ".", "ignore", ".", "some", "(", "function", "(", "rule", ")", "{", "matchedIgnoreRule", "=", "rule", ";", "return", "isMatchRule", "(", "req", ",", "req", ".", "path", ",", "rule", ")", ";", "}", ")", ";", "if", "(", "hasMatchIgnore", ")", "{", "logger", ".", "info", "(", "'Matched ignore rule.'", ",", "matchedIgnoreRule", ",", "' Go through CAS.'", ")", ";", "return", "true", ";", "}", "return", "false", ";", "}", "return", "false", ";", "}" ]
Check options.match first, if match, return `false`, then check the options.ignore, if match, return `true`. If returned `true`, then this request will bypass CAS directly. @param req @param options @param logger
[ "Check", "options", ".", "match", "first", "if", "match", "return", "false", "then", "check", "the", "options", ".", "ignore", "if", "match", "return", "true", "." ]
b01415629abc08bb4a462873c0d53577481bd52d
https://github.com/TencentWSRD/connect-cas2/blob/b01415629abc08bb4a462873c0d53577481bd52d/lib/utils.js#L53-L86
16,587
TencentWSRD/connect-cas2
lib/utils.js
getRequest
function getRequest(path, options, callback) { if (typeof options === 'function') { callback = options; options = { method: 'get' }; } else { options.method = 'get'; } if (options.params) { var uri = url.parse(path, true); uri.query = _.merge({}, uri.query, options.params); path = url.format(uri); delete options.params; } sendRequest(path, options, callback); }
javascript
function getRequest(path, options, callback) { if (typeof options === 'function') { callback = options; options = { method: 'get' }; } else { options.method = 'get'; } if (options.params) { var uri = url.parse(path, true); uri.query = _.merge({}, uri.query, options.params); path = url.format(uri); delete options.params; } sendRequest(path, options, callback); }
[ "function", "getRequest", "(", "path", ",", "options", ",", "callback", ")", "{", "if", "(", "typeof", "options", "===", "'function'", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "method", ":", "'get'", "}", ";", "}", "else", "{", "options", ".", "method", "=", "'get'", ";", "}", "if", "(", "options", ".", "params", ")", "{", "var", "uri", "=", "url", ".", "parse", "(", "path", ",", "true", ")", ";", "uri", ".", "query", "=", "_", ".", "merge", "(", "{", "}", ",", "uri", ".", "query", ",", "options", ".", "params", ")", ";", "path", "=", "url", ".", "format", "(", "uri", ")", ";", "delete", "options", ".", "params", ";", "}", "sendRequest", "(", "path", ",", "options", ",", "callback", ")", ";", "}" ]
Send a GET request @param path @param {Object} options (Optional) @param callback
[ "Send", "a", "GET", "request" ]
b01415629abc08bb4a462873c0d53577481bd52d
https://github.com/TencentWSRD/connect-cas2/blob/b01415629abc08bb4a462873c0d53577481bd52d/lib/utils.js#L108-L126
16,588
DScheglov/mongoose-schema-jsonschema
lib/schema.js
schema_jsonSchema
function schema_jsonSchema(name) { let result; name = name || this.options.name; if (this.__buildingSchema) { this.__jsonSchemaId = this.__jsonSchemaId || '#schema-' + (++schema_jsonSchema.__jsonSchemaIdCounter); return {'$ref': this.__jsonSchemaId} } if (!this.__jsonSchema) { this.__buildingSchema = true; this.__jsonSchema = __build(name, this); this.__buildingSchema = false; if (this.__jsonSchemaId) { this.__jsonSchema = Object.assign( {id: this.__jsonSchemaId}, this.__jsonSchema ) } } result = JSON.parse(JSON.stringify(this.__jsonSchema)); if (name) { result.title = name; } else { delete result.title; } return result; }
javascript
function schema_jsonSchema(name) { let result; name = name || this.options.name; if (this.__buildingSchema) { this.__jsonSchemaId = this.__jsonSchemaId || '#schema-' + (++schema_jsonSchema.__jsonSchemaIdCounter); return {'$ref': this.__jsonSchemaId} } if (!this.__jsonSchema) { this.__buildingSchema = true; this.__jsonSchema = __build(name, this); this.__buildingSchema = false; if (this.__jsonSchemaId) { this.__jsonSchema = Object.assign( {id: this.__jsonSchemaId}, this.__jsonSchema ) } } result = JSON.parse(JSON.stringify(this.__jsonSchema)); if (name) { result.title = name; } else { delete result.title; } return result; }
[ "function", "schema_jsonSchema", "(", "name", ")", "{", "let", "result", ";", "name", "=", "name", "||", "this", ".", "options", ".", "name", ";", "if", "(", "this", ".", "__buildingSchema", ")", "{", "this", ".", "__jsonSchemaId", "=", "this", ".", "__jsonSchemaId", "||", "'#schema-'", "+", "(", "++", "schema_jsonSchema", ".", "__jsonSchemaIdCounter", ")", ";", "return", "{", "'$ref'", ":", "this", ".", "__jsonSchemaId", "}", "}", "if", "(", "!", "this", ".", "__jsonSchema", ")", "{", "this", ".", "__buildingSchema", "=", "true", ";", "this", ".", "__jsonSchema", "=", "__build", "(", "name", ",", "this", ")", ";", "this", ".", "__buildingSchema", "=", "false", ";", "if", "(", "this", ".", "__jsonSchemaId", ")", "{", "this", ".", "__jsonSchema", "=", "Object", ".", "assign", "(", "{", "id", ":", "this", ".", "__jsonSchemaId", "}", ",", "this", ".", "__jsonSchema", ")", "}", "}", "result", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "this", ".", "__jsonSchema", ")", ")", ";", "if", "(", "name", ")", "{", "result", ".", "title", "=", "name", ";", "}", "else", "{", "delete", "result", ".", "title", ";", "}", "return", "result", ";", "}" ]
schema_jsonSchema - builds the json schema based on the Mongooose schema. if schema has been already built the method returns new deep copy Method considers the `schema.options.toJSON.virtuals` to included the virtual paths (without detailed description) @memberof mongoose.Schema @param {String} name Name of the object @return {Object} json schema
[ "schema_jsonSchema", "-", "builds", "the", "json", "schema", "based", "on", "the", "Mongooose", "schema", ".", "if", "schema", "has", "been", "already", "built", "the", "method", "returns", "new", "deep", "copy" ]
b1a844644553420d2dad341bd55cfce966922ca0
https://github.com/DScheglov/mongoose-schema-jsonschema/blob/b1a844644553420d2dad341bd55cfce966922ca0/lib/schema.js#L19-L51
16,589
DScheglov/mongoose-schema-jsonschema
lib/types.js
simpleType_jsonSchema
function simpleType_jsonSchema(name) { var result = {}; result.type = this.instance.toLowerCase(); __processOptions(result, this.options) return result; }
javascript
function simpleType_jsonSchema(name) { var result = {}; result.type = this.instance.toLowerCase(); __processOptions(result, this.options) return result; }
[ "function", "simpleType_jsonSchema", "(", "name", ")", "{", "var", "result", "=", "{", "}", ";", "result", ".", "type", "=", "this", ".", "instance", ".", "toLowerCase", "(", ")", ";", "__processOptions", "(", "result", ",", "this", ".", "options", ")", "return", "result", ";", "}" ]
simpleType_jsonSchema - returns jsonSchema for simple-type parameter @memberof mongoose.Schema.Types.String @param {String} name the name of parameter @return {object} the jsonSchema for parameter
[ "simpleType_jsonSchema", "-", "returns", "jsonSchema", "for", "simple", "-", "type", "parameter" ]
b1a844644553420d2dad341bd55cfce966922ca0
https://github.com/DScheglov/mongoose-schema-jsonschema/blob/b1a844644553420d2dad341bd55cfce966922ca0/lib/types.js#L18-L25
16,590
DScheglov/mongoose-schema-jsonschema
lib/types.js
objectId_jsonSchema
function objectId_jsonSchema(name) { var result = simpleType_jsonSchema.call(this, name); result.type = 'string'; result.pattern = '^[0-9a-fA-F]{24}$'; return result; }
javascript
function objectId_jsonSchema(name) { var result = simpleType_jsonSchema.call(this, name); result.type = 'string'; result.pattern = '^[0-9a-fA-F]{24}$'; return result; }
[ "function", "objectId_jsonSchema", "(", "name", ")", "{", "var", "result", "=", "simpleType_jsonSchema", ".", "call", "(", "this", ",", "name", ")", ";", "result", ".", "type", "=", "'string'", ";", "result", ".", "pattern", "=", "'^[0-9a-fA-F]{24}$'", ";", "return", "result", ";", "}" ]
objectId_jsonSchema - returns the jsonSchema for ObjectId parameters @memberof mongoose.Schema.Types.ObjectId @param {String} name the name of parameter @return {object} the jsonSchema for parameter
[ "objectId_jsonSchema", "-", "returns", "the", "jsonSchema", "for", "ObjectId", "parameters" ]
b1a844644553420d2dad341bd55cfce966922ca0
https://github.com/DScheglov/mongoose-schema-jsonschema/blob/b1a844644553420d2dad341bd55cfce966922ca0/lib/types.js#L36-L44
16,591
DScheglov/mongoose-schema-jsonschema
lib/types.js
date_jsonSchema
function date_jsonSchema(name) { var result = simpleType_jsonSchema.call(this, name); result.type = 'string'; result.format = 'date-time'; return result; }
javascript
function date_jsonSchema(name) { var result = simpleType_jsonSchema.call(this, name); result.type = 'string'; result.format = 'date-time'; return result; }
[ "function", "date_jsonSchema", "(", "name", ")", "{", "var", "result", "=", "simpleType_jsonSchema", ".", "call", "(", "this", ",", "name", ")", ";", "result", ".", "type", "=", "'string'", ";", "result", ".", "format", "=", "'date-time'", ";", "return", "result", ";", "}" ]
date_jsonSchema - description @param {type} name description @return {type} description
[ "date_jsonSchema", "-", "description" ]
b1a844644553420d2dad341bd55cfce966922ca0
https://github.com/DScheglov/mongoose-schema-jsonschema/blob/b1a844644553420d2dad341bd55cfce966922ca0/lib/types.js#L53-L61
16,592
DScheglov/mongoose-schema-jsonschema
lib/types.js
array_jsonSchema
function array_jsonSchema(name) { var result = {}; var itemName; itemName = 'itemOf_' + name; result.type = 'array'; if (this.options.required) result.__required = true; if (this.schema) { result.items = this.schema.jsonSchema(itemName); } else { result.items = this.caster.jsonSchema(itemName); } if (result.items.__required) { result.minItems = 1; } __processOptions(result, this.options); delete result.items.__required; return result; }
javascript
function array_jsonSchema(name) { var result = {}; var itemName; itemName = 'itemOf_' + name; result.type = 'array'; if (this.options.required) result.__required = true; if (this.schema) { result.items = this.schema.jsonSchema(itemName); } else { result.items = this.caster.jsonSchema(itemName); } if (result.items.__required) { result.minItems = 1; } __processOptions(result, this.options); delete result.items.__required; return result; }
[ "function", "array_jsonSchema", "(", "name", ")", "{", "var", "result", "=", "{", "}", ";", "var", "itemName", ";", "itemName", "=", "'itemOf_'", "+", "name", ";", "result", ".", "type", "=", "'array'", ";", "if", "(", "this", ".", "options", ".", "required", ")", "result", ".", "__required", "=", "true", ";", "if", "(", "this", ".", "schema", ")", "{", "result", ".", "items", "=", "this", ".", "schema", ".", "jsonSchema", "(", "itemName", ")", ";", "}", "else", "{", "result", ".", "items", "=", "this", ".", "caster", ".", "jsonSchema", "(", "itemName", ")", ";", "}", "if", "(", "result", ".", "items", ".", "__required", ")", "{", "result", ".", "minItems", "=", "1", ";", "}", "__processOptions", "(", "result", ",", "this", ".", "options", ")", ";", "delete", "result", ".", "items", ".", "__required", ";", "return", "result", ";", "}" ]
array_jsonSchema - returns jsonSchema for array parameters @memberof mongoose.Schema.Types.SchemaArray @memberof mongoose.Schema.Types.DocumentArray @param {String} name parameter name @return {object} json schema
[ "array_jsonSchema", "-", "returns", "jsonSchema", "for", "array", "parameters" ]
b1a844644553420d2dad341bd55cfce966922ca0
https://github.com/DScheglov/mongoose-schema-jsonschema/blob/b1a844644553420d2dad341bd55cfce966922ca0/lib/types.js#L73-L96
16,593
DScheglov/mongoose-schema-jsonschema
lib/types.js
mixed_jsonSchema
function mixed_jsonSchema(name) { var result = __describe(name, this.options.type); __processOptions(result, this.options); return result; }
javascript
function mixed_jsonSchema(name) { var result = __describe(name, this.options.type); __processOptions(result, this.options); return result; }
[ "function", "mixed_jsonSchema", "(", "name", ")", "{", "var", "result", "=", "__describe", "(", "name", ",", "this", ".", "options", ".", "type", ")", ";", "__processOptions", "(", "result", ",", "this", ".", "options", ")", ";", "return", "result", ";", "}" ]
mixed_jsonSchema - returns jsonSchema for Mixed parameter @memberof mongoose.Schema.Types.Mixed @param {String} name parameter name @return {object} json schema
[ "mixed_jsonSchema", "-", "returns", "jsonSchema", "for", "Mixed", "parameter" ]
b1a844644553420d2dad341bd55cfce966922ca0
https://github.com/DScheglov/mongoose-schema-jsonschema/blob/b1a844644553420d2dad341bd55cfce966922ca0/lib/types.js#L107-L111
16,594
DScheglov/mongoose-schema-jsonschema
lib/model.js
model_jsonSchema
function model_jsonSchema(fields, populate, readonly) { var jsonSchema = this.schema.jsonSchema(this.modelName); if (populate != null) { jsonSchema = __populate.call(this, jsonSchema, populate); }; __excludedPaths(this.schema, fields).forEach( __delPath.bind(null, jsonSchema) ); if (readonly) { __excludedReadonlyPaths(jsonSchema, readonly); } if (fields) __removeRequired(jsonSchema); return jsonSchema; }
javascript
function model_jsonSchema(fields, populate, readonly) { var jsonSchema = this.schema.jsonSchema(this.modelName); if (populate != null) { jsonSchema = __populate.call(this, jsonSchema, populate); }; __excludedPaths(this.schema, fields).forEach( __delPath.bind(null, jsonSchema) ); if (readonly) { __excludedReadonlyPaths(jsonSchema, readonly); } if (fields) __removeRequired(jsonSchema); return jsonSchema; }
[ "function", "model_jsonSchema", "(", "fields", ",", "populate", ",", "readonly", ")", "{", "var", "jsonSchema", "=", "this", ".", "schema", ".", "jsonSchema", "(", "this", ".", "modelName", ")", ";", "if", "(", "populate", "!=", "null", ")", "{", "jsonSchema", "=", "__populate", ".", "call", "(", "this", ",", "jsonSchema", ",", "populate", ")", ";", "}", ";", "__excludedPaths", "(", "this", ".", "schema", ",", "fields", ")", ".", "forEach", "(", "__delPath", ".", "bind", "(", "null", ",", "jsonSchema", ")", ")", ";", "if", "(", "readonly", ")", "{", "__excludedReadonlyPaths", "(", "jsonSchema", ",", "readonly", ")", ";", "}", "if", "(", "fields", ")", "__removeRequired", "(", "jsonSchema", ")", ";", "return", "jsonSchema", ";", "}" ]
model_jsonSchema - builds json schema for model considering the selection and population if `fields` specified the method removes `required` contraints @memberof mongoose.Model @param {String|Array|Object} fields mongoose selection object @param {String|Object} populate mongoose population options @return {object} json schema
[ "model_jsonSchema", "-", "builds", "json", "schema", "for", "model", "considering", "the", "selection", "and", "population" ]
b1a844644553420d2dad341bd55cfce966922ca0
https://github.com/DScheglov/mongoose-schema-jsonschema/blob/b1a844644553420d2dad341bd55cfce966922ca0/lib/model.js#L20-L38
16,595
DScheglov/mongoose-schema-jsonschema
lib/query.js
query_jsonSchema
function query_jsonSchema() { let populate = this._mongooseOptions.populate; if (populate) { populate = Object.keys(populate).map(k => populate[k]); } let jsonSchema = this.model.jsonSchema( this._fields, populate ); delete jsonSchema.required; if (this.op.indexOf('findOne') === 0) return jsonSchema; delete jsonSchema.title; jsonSchema = { title: 'List of ' + plural(this.model.modelName), type: 'array', items: jsonSchema }; if (this.options.limit) { jsonSchema.maxItems = this.options.limit } return jsonSchema; }
javascript
function query_jsonSchema() { let populate = this._mongooseOptions.populate; if (populate) { populate = Object.keys(populate).map(k => populate[k]); } let jsonSchema = this.model.jsonSchema( this._fields, populate ); delete jsonSchema.required; if (this.op.indexOf('findOne') === 0) return jsonSchema; delete jsonSchema.title; jsonSchema = { title: 'List of ' + plural(this.model.modelName), type: 'array', items: jsonSchema }; if (this.options.limit) { jsonSchema.maxItems = this.options.limit } return jsonSchema; }
[ "function", "query_jsonSchema", "(", ")", "{", "let", "populate", "=", "this", ".", "_mongooseOptions", ".", "populate", ";", "if", "(", "populate", ")", "{", "populate", "=", "Object", ".", "keys", "(", "populate", ")", ".", "map", "(", "k", "=>", "populate", "[", "k", "]", ")", ";", "}", "let", "jsonSchema", "=", "this", ".", "model", ".", "jsonSchema", "(", "this", ".", "_fields", ",", "populate", ")", ";", "delete", "jsonSchema", ".", "required", ";", "if", "(", "this", ".", "op", ".", "indexOf", "(", "'findOne'", ")", "===", "0", ")", "return", "jsonSchema", ";", "delete", "jsonSchema", ".", "title", ";", "jsonSchema", "=", "{", "title", ":", "'List of '", "+", "plural", "(", "this", ".", "model", ".", "modelName", ")", ",", "type", ":", "'array'", ",", "items", ":", "jsonSchema", "}", ";", "if", "(", "this", ".", "options", ".", "limit", ")", "{", "jsonSchema", ".", "maxItems", "=", "this", ".", "options", ".", "limit", "}", "return", "jsonSchema", ";", "}" ]
query_jsonSchema - returns json schema considering the query type and options @return {Object} json schema
[ "query_jsonSchema", "-", "returns", "json", "schema", "considering", "the", "query", "type", "and", "options" ]
b1a844644553420d2dad341bd55cfce966922ca0
https://github.com/DScheglov/mongoose-schema-jsonschema/blob/b1a844644553420d2dad341bd55cfce966922ca0/lib/query.js#L14-L40
16,596
browserify/node-util
util.js
callbackified
function callbackified() { var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } var maybeCb = args.pop(); if (typeof maybeCb !== 'function') { throw new TypeError('The last argument must be of type Function'); } var self = this; var cb = function() { return maybeCb.apply(self, arguments); }; // In true node style we process the callback on `nextTick` with all the // implications (stack, `uncaughtException`, `async_hooks`) original.apply(this, args) .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); }
javascript
function callbackified() { var args = []; for (var i = 0; i < arguments.length; i++) { args.push(arguments[i]); } var maybeCb = args.pop(); if (typeof maybeCb !== 'function') { throw new TypeError('The last argument must be of type Function'); } var self = this; var cb = function() { return maybeCb.apply(self, arguments); }; // In true node style we process the callback on `nextTick` with all the // implications (stack, `uncaughtException`, `async_hooks`) original.apply(this, args) .then(function(ret) { process.nextTick(cb.bind(null, null, ret)) }, function(rej) { process.nextTick(callbackifyOnRejected.bind(null, rej, cb)) }); }
[ "function", "callbackified", "(", ")", "{", "var", "args", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "args", ".", "push", "(", "arguments", "[", "i", "]", ")", ";", "}", "var", "maybeCb", "=", "args", ".", "pop", "(", ")", ";", "if", "(", "typeof", "maybeCb", "!==", "'function'", ")", "{", "throw", "new", "TypeError", "(", "'The last argument must be of type Function'", ")", ";", "}", "var", "self", "=", "this", ";", "var", "cb", "=", "function", "(", ")", "{", "return", "maybeCb", ".", "apply", "(", "self", ",", "arguments", ")", ";", "}", ";", "// In true node style we process the callback on `nextTick` with all the", "// implications (stack, `uncaughtException`, `async_hooks`)", "original", ".", "apply", "(", "this", ",", "args", ")", ".", "then", "(", "function", "(", "ret", ")", "{", "process", ".", "nextTick", "(", "cb", ".", "bind", "(", "null", ",", "null", ",", "ret", ")", ")", "}", ",", "function", "(", "rej", ")", "{", "process", ".", "nextTick", "(", "callbackifyOnRejected", ".", "bind", "(", "null", ",", "rej", ",", "cb", ")", ")", "}", ")", ";", "}" ]
We DO NOT return the promise as it gives the user a false sense that the promise is actually somehow related to the callback's execution and that the callback throwing will reject the promise.
[ "We", "DO", "NOT", "return", "the", "promise", "as", "it", "gives", "the", "user", "a", "false", "sense", "that", "the", "promise", "is", "actually", "somehow", "related", "to", "the", "callback", "s", "execution", "and", "that", "the", "callback", "throwing", "will", "reject", "the", "promise", "." ]
53026a2923edeaa0a113f479298f555b761f8042
https://github.com/browserify/node-util/blob/53026a2923edeaa0a113f479298f555b761f8042/util.js#L682-L701
16,597
waldophotos/kafka-avro
lib/schema-registry.js
typeFromSchemaResponse
function typeFromSchemaResponse(schema, parseOptions) { var schemaType = avro.parse(schema); //check if the schema has been previouisly parsed and added to the registry if(typeof parseOptions.registry === 'object' && typeof parseOptions.registry[schemaType.name] !== 'undefined'){ return parseOptions.registry[schemaType.name]; } return avro.parse(schema, parseOptions); }
javascript
function typeFromSchemaResponse(schema, parseOptions) { var schemaType = avro.parse(schema); //check if the schema has been previouisly parsed and added to the registry if(typeof parseOptions.registry === 'object' && typeof parseOptions.registry[schemaType.name] !== 'undefined'){ return parseOptions.registry[schemaType.name]; } return avro.parse(schema, parseOptions); }
[ "function", "typeFromSchemaResponse", "(", "schema", ",", "parseOptions", ")", "{", "var", "schemaType", "=", "avro", ".", "parse", "(", "schema", ")", ";", "//check if the schema has been previouisly parsed and added to the registry", "if", "(", "typeof", "parseOptions", ".", "registry", "===", "'object'", "&&", "typeof", "parseOptions", ".", "registry", "[", "schemaType", ".", "name", "]", "!==", "'undefined'", ")", "{", "return", "parseOptions", ".", "registry", "[", "schemaType", ".", "name", "]", ";", "}", "return", "avro", ".", "parse", "(", "schema", ",", "parseOptions", ")", ";", "}" ]
Get the avro RecordType from a schema response. @return {RecordType} An avro RecordType representing the parsed avro schema.
[ "Get", "the", "avro", "RecordType", "from", "a", "schema", "response", "." ]
116b516561348bdc95c13c378da86cb4e335dcd6
https://github.com/waldophotos/kafka-avro/blob/116b516561348bdc95c13c378da86cb4e335dcd6/lib/schema-registry.js#L100-L109
16,598
markusslima/bootstrap-filestyle
src/bootstrap-filestyle.js
function() { var content = '', files = []; if (this.$element[0].files === undefined) { files[0] = { 'name' : this.$element[0] && this.$element[0].value }; } else { files = this.$element[0].files; } for (var i = 0; i < files.length; i++) { content += files[i].name.split("\\").pop() + ', '; } if (content !== '') { this.$elementFilestyle.find(':text').val(content.replace(/\, $/g, '')); } else { this.$elementFilestyle.find(':text').val(''); } return files; }
javascript
function() { var content = '', files = []; if (this.$element[0].files === undefined) { files[0] = { 'name' : this.$element[0] && this.$element[0].value }; } else { files = this.$element[0].files; } for (var i = 0; i < files.length; i++) { content += files[i].name.split("\\").pop() + ', '; } if (content !== '') { this.$elementFilestyle.find(':text').val(content.replace(/\, $/g, '')); } else { this.$elementFilestyle.find(':text').val(''); } return files; }
[ "function", "(", ")", "{", "var", "content", "=", "''", ",", "files", "=", "[", "]", ";", "if", "(", "this", ".", "$element", "[", "0", "]", ".", "files", "===", "undefined", ")", "{", "files", "[", "0", "]", "=", "{", "'name'", ":", "this", ".", "$element", "[", "0", "]", "&&", "this", ".", "$element", "[", "0", "]", ".", "value", "}", ";", "}", "else", "{", "files", "=", "this", ".", "$element", "[", "0", "]", ".", "files", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "content", "+=", "files", "[", "i", "]", ".", "name", ".", "split", "(", "\"\\\\\"", ")", ".", "pop", "(", ")", "+", "', '", ";", "}", "if", "(", "content", "!==", "''", ")", "{", "this", ".", "$elementFilestyle", ".", "find", "(", "':text'", ")", ".", "val", "(", "content", ".", "replace", "(", "/", "\\, $", "/", "g", ",", "''", ")", ")", ";", "}", "else", "{", "this", ".", "$elementFilestyle", ".", "find", "(", "':text'", ")", ".", "val", "(", "''", ")", ";", "}", "return", "files", ";", "}" ]
puts the name of the input files return files
[ "puts", "the", "name", "of", "the", "input", "files", "return", "files" ]
071ae6f3ff9a49a04346848b05d165e86c50f3b7
https://github.com/markusslima/bootstrap-filestyle/blob/071ae6f3ff9a49a04346848b05d165e86c50f3b7/src/bootstrap-filestyle.js#L192-L213
16,599
w8r/polygon-offset
src/edge.js
Edge
function Edge(current, next) { /** * @type {Object} */ this.current = current; /** * @type {Object} */ this.next = next; /** * @type {Object} */ this._inNormal = this.inwardsNormal(); /** * @type {Object} */ this._outNormal = this.outwardsNormal(); }
javascript
function Edge(current, next) { /** * @type {Object} */ this.current = current; /** * @type {Object} */ this.next = next; /** * @type {Object} */ this._inNormal = this.inwardsNormal(); /** * @type {Object} */ this._outNormal = this.outwardsNormal(); }
[ "function", "Edge", "(", "current", ",", "next", ")", "{", "/**\n * @type {Object}\n */", "this", ".", "current", "=", "current", ";", "/**\n * @type {Object}\n */", "this", ".", "next", "=", "next", ";", "/**\n * @type {Object}\n */", "this", ".", "_inNormal", "=", "this", ".", "inwardsNormal", "(", ")", ";", "/**\n * @type {Object}\n */", "this", ".", "_outNormal", "=", "this", ".", "outwardsNormal", "(", ")", ";", "}" ]
Offset edge of the polygon @param {Object} current @param {Object} next @constructor
[ "Offset", "edge", "of", "the", "polygon" ]
9be25b9f18ad83ca4d3243104ebacadbc392d32e
https://github.com/w8r/polygon-offset/blob/9be25b9f18ad83ca4d3243104ebacadbc392d32e/src/edge.js#L8-L29