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
partition
stringclasses
1 value
flint-bot/flint
storage/redis_old.js
initRedis
function initRedis() { return when.promise((resolve, reject) => { redis.get(name, (err, res) => { if(err) { memStore = {}; } else if(res) { memStore = JSON.parse(res); } else { memStore = {}; } resolve(true); }); }); }
javascript
function initRedis() { return when.promise((resolve, reject) => { redis.get(name, (err, res) => { if(err) { memStore = {}; } else if(res) { memStore = JSON.parse(res); } else { memStore = {}; } resolve(true); }); }); }
[ "function", "initRedis", "(", ")", "{", "return", "when", ".", "promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "redis", ".", "get", "(", "name", ",", "(", "err", ",", "res", ")", "=>", "{", "if", "(", "err", ")", "{", "memStore", "=", "{", "}", ";", "}", "else", "if", "(", "res", ")", "{", "memStore", "=", "JSON", ".", "parse", "(", "res", ")", ";", "}", "else", "{", "memStore", "=", "{", "}", ";", "}", "resolve", "(", "true", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
load memStore state from redis
[ "load", "memStore", "state", "from", "redis" ]
718923a17e794e28328aed1a2b24d75748b81fbc
https://github.com/flint-bot/flint/blob/718923a17e794e28328aed1a2b24d75748b81fbc/storage/redis_old.js#L17-L30
train
flint-bot/flint
storage/redis_old.js
syncRedis
function syncRedis() { // if memStore has changed... if(JSON.stringify(memCache) !== JSON.stringify(memStore)) { return when.promise((resolve, reject) => { var serializedStore = JSON.stringify(memStore); redis.set(name, serializedStore, err => { if(err) { reject(err); } else { resolve(true); } }); }) .delay(syncInterval) .catch(err => { console.log(err.stack); return when(true); }) .finally(() => { memCache = _.cloneDeep(memStore); if(active) syncRedis(memStore); return when(true); }); } // else memStore has not changed... else { return when(true) .delay(syncInterval) .then(() => { if(active) syncRedis(memStore); return when(true); }); } }
javascript
function syncRedis() { // if memStore has changed... if(JSON.stringify(memCache) !== JSON.stringify(memStore)) { return when.promise((resolve, reject) => { var serializedStore = JSON.stringify(memStore); redis.set(name, serializedStore, err => { if(err) { reject(err); } else { resolve(true); } }); }) .delay(syncInterval) .catch(err => { console.log(err.stack); return when(true); }) .finally(() => { memCache = _.cloneDeep(memStore); if(active) syncRedis(memStore); return when(true); }); } // else memStore has not changed... else { return when(true) .delay(syncInterval) .then(() => { if(active) syncRedis(memStore); return when(true); }); } }
[ "function", "syncRedis", "(", ")", "{", "if", "(", "JSON", ".", "stringify", "(", "memCache", ")", "!==", "JSON", ".", "stringify", "(", "memStore", ")", ")", "{", "return", "when", ".", "promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "var", "serializedStore", "=", "JSON", ".", "stringify", "(", "memStore", ")", ";", "redis", ".", "set", "(", "name", ",", "serializedStore", ",", "err", "=>", "{", "if", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "else", "{", "resolve", "(", "true", ")", ";", "}", "}", ")", ";", "}", ")", ".", "delay", "(", "syncInterval", ")", ".", "catch", "(", "err", "=>", "{", "console", ".", "log", "(", "err", ".", "stack", ")", ";", "return", "when", "(", "true", ")", ";", "}", ")", ".", "finally", "(", "(", ")", "=>", "{", "memCache", "=", "_", ".", "cloneDeep", "(", "memStore", ")", ";", "if", "(", "active", ")", "syncRedis", "(", "memStore", ")", ";", "return", "when", "(", "true", ")", ";", "}", ")", ";", "}", "else", "{", "return", "when", "(", "true", ")", ".", "delay", "(", "syncInterval", ")", ".", "then", "(", "(", ")", "=>", "{", "if", "(", "active", ")", "syncRedis", "(", "memStore", ")", ";", "return", "when", "(", "true", ")", ";", "}", ")", ";", "}", "}" ]
start periodicly sync of memStore state to redis
[ "start", "periodicly", "sync", "of", "memStore", "state", "to", "redis" ]
718923a17e794e28328aed1a2b24d75748b81fbc
https://github.com/flint-bot/flint/blob/718923a17e794e28328aed1a2b24d75748b81fbc/storage/redis_old.js#L33-L67
train
dominhhai/koa-log4js
koa-logger.js
getKoaLogger
function getKoaLogger (logger4js, options) { if (typeof options === 'object') { options = options || {} } else if (options) { options = { format: options } } else { options = {} } let thislogger = logger4js let level = levels.getLevel(options.level, levels.INFO) let fmt = options.format || DEFAULT_FORMAT let nolog = options.nolog ? createNoLogCondition(options.nolog) : null return async (ctx, next) => { // mount safety if (ctx.request._logging) { await next() return } // nologs if (nolog && nolog.test(ctx.originalUrl)) { await next() return } if (thislogger.isLevelEnabled(level) || options.level === 'auto') { let start = new Date() let writeHead = ctx.response.writeHead // flag as logging ctx.request._logging = true // proxy for statusCode. ctx.response.writeHead = function (code, headers) { ctx.response.writeHead = writeHead ctx.response.writeHead(code, headers) ctx.response.__statusCode = code ctx.response.__headers = headers || {} // status code response level handling if (options.level === 'auto') { level = levels.INFO if (code >= 300) level = levels.WARN if (code >= 400) level = levels.ERROR } else { level = levels.getLevel(options.level, levels.INFO) } } await next() // hook on end request to emit the log entry of the HTTP request. ctx.response.responseTime = new Date() - start // status code response level handling if (ctx.res.statusCode && options.level === 'auto') { level = levels.INFO if (ctx.res.statusCode >= 300) level = levels.WARN if (ctx.res.statusCode >= 400) level = levels.ERROR } if (thislogger.isLevelEnabled(level)) { let combinedTokens = assembleTokens(ctx, options.tokens || []) if (typeof fmt === 'function') { let line = fmt(ctx, function (str) { return format(str, combinedTokens) }) if (line) thislogger.log(level, line) } else { thislogger.log(level, format(fmt, combinedTokens)) } } } else { // ensure next gets always called await next() } } }
javascript
function getKoaLogger (logger4js, options) { if (typeof options === 'object') { options = options || {} } else if (options) { options = { format: options } } else { options = {} } let thislogger = logger4js let level = levels.getLevel(options.level, levels.INFO) let fmt = options.format || DEFAULT_FORMAT let nolog = options.nolog ? createNoLogCondition(options.nolog) : null return async (ctx, next) => { // mount safety if (ctx.request._logging) { await next() return } // nologs if (nolog && nolog.test(ctx.originalUrl)) { await next() return } if (thislogger.isLevelEnabled(level) || options.level === 'auto') { let start = new Date() let writeHead = ctx.response.writeHead // flag as logging ctx.request._logging = true // proxy for statusCode. ctx.response.writeHead = function (code, headers) { ctx.response.writeHead = writeHead ctx.response.writeHead(code, headers) ctx.response.__statusCode = code ctx.response.__headers = headers || {} // status code response level handling if (options.level === 'auto') { level = levels.INFO if (code >= 300) level = levels.WARN if (code >= 400) level = levels.ERROR } else { level = levels.getLevel(options.level, levels.INFO) } } await next() // hook on end request to emit the log entry of the HTTP request. ctx.response.responseTime = new Date() - start // status code response level handling if (ctx.res.statusCode && options.level === 'auto') { level = levels.INFO if (ctx.res.statusCode >= 300) level = levels.WARN if (ctx.res.statusCode >= 400) level = levels.ERROR } if (thislogger.isLevelEnabled(level)) { let combinedTokens = assembleTokens(ctx, options.tokens || []) if (typeof fmt === 'function') { let line = fmt(ctx, function (str) { return format(str, combinedTokens) }) if (line) thislogger.log(level, line) } else { thislogger.log(level, format(fmt, combinedTokens)) } } } else { // ensure next gets always called await next() } } }
[ "function", "getKoaLogger", "(", "logger4js", ",", "options", ")", "{", "if", "(", "typeof", "options", "===", "'object'", ")", "{", "options", "=", "options", "||", "{", "}", "}", "else", "if", "(", "options", ")", "{", "options", "=", "{", "format", ":", "options", "}", "}", "else", "{", "options", "=", "{", "}", "}", "let", "thislogger", "=", "logger4js", "let", "level", "=", "levels", ".", "getLevel", "(", "options", ".", "level", ",", "levels", ".", "INFO", ")", "let", "fmt", "=", "options", ".", "format", "||", "DEFAULT_FORMAT", "let", "nolog", "=", "options", ".", "nolog", "?", "createNoLogCondition", "(", "options", ".", "nolog", ")", ":", "null", "return", "async", "(", "ctx", ",", "next", ")", "=>", "{", "if", "(", "ctx", ".", "request", ".", "_logging", ")", "{", "await", "next", "(", ")", "return", "}", "if", "(", "nolog", "&&", "nolog", ".", "test", "(", "ctx", ".", "originalUrl", ")", ")", "{", "await", "next", "(", ")", "return", "}", "if", "(", "thislogger", ".", "isLevelEnabled", "(", "level", ")", "||", "options", ".", "level", "===", "'auto'", ")", "{", "let", "start", "=", "new", "Date", "(", ")", "let", "writeHead", "=", "ctx", ".", "response", ".", "writeHead", "ctx", ".", "request", ".", "_logging", "=", "true", "ctx", ".", "response", ".", "writeHead", "=", "function", "(", "code", ",", "headers", ")", "{", "ctx", ".", "response", ".", "writeHead", "=", "writeHead", "ctx", ".", "response", ".", "writeHead", "(", "code", ",", "headers", ")", "ctx", ".", "response", ".", "__statusCode", "=", "code", "ctx", ".", "response", ".", "__headers", "=", "headers", "||", "{", "}", "if", "(", "options", ".", "level", "===", "'auto'", ")", "{", "level", "=", "levels", ".", "INFO", "if", "(", "code", ">=", "300", ")", "level", "=", "levels", ".", "WARN", "if", "(", "code", ">=", "400", ")", "level", "=", "levels", ".", "ERROR", "}", "else", "{", "level", "=", "levels", ".", "getLevel", "(", "options", ".", "level", ",", "levels", ".", "INFO", ")", "}", "}", "await", "next", "(", ")", "ctx", ".", "response", ".", "responseTime", "=", "new", "Date", "(", ")", "-", "start", "if", "(", "ctx", ".", "res", ".", "statusCode", "&&", "options", ".", "level", "===", "'auto'", ")", "{", "level", "=", "levels", ".", "INFO", "if", "(", "ctx", ".", "res", ".", "statusCode", ">=", "300", ")", "level", "=", "levels", ".", "WARN", "if", "(", "ctx", ".", "res", ".", "statusCode", ">=", "400", ")", "level", "=", "levels", ".", "ERROR", "}", "if", "(", "thislogger", ".", "isLevelEnabled", "(", "level", ")", ")", "{", "let", "combinedTokens", "=", "assembleTokens", "(", "ctx", ",", "options", ".", "tokens", "||", "[", "]", ")", "if", "(", "typeof", "fmt", "===", "'function'", ")", "{", "let", "line", "=", "fmt", "(", "ctx", ",", "function", "(", "str", ")", "{", "return", "format", "(", "str", ",", "combinedTokens", ")", "}", ")", "if", "(", "line", ")", "thislogger", ".", "log", "(", "level", ",", "line", ")", "}", "else", "{", "thislogger", ".", "log", "(", "level", ",", "format", "(", "fmt", ",", "combinedTokens", ")", ")", "}", "}", "}", "else", "{", "await", "next", "(", ")", "}", "}", "}" ]
Log requests with the given `options` or a `format` string. Use for Koa v1 Options: - `format` Format string, see below for tokens - `level` A log4js levels instance. Supports also 'auto' Tokens: - `:req[header]` ex: `:req[Accept]` - `:res[header]` ex: `:res[Content-Length]` - `:http-version` - `:response-time` - `:remote-addr` - `:date` - `:method` - `:url` - `:referrer` - `:user-agent` - `:status` @param {String|Function|Object} format or options @return {Function} @api public
[ "Log", "requests", "with", "the", "given", "options", "or", "a", "format", "string", ".", "Use", "for", "Koa", "v1" ]
c129c9e7d1145553ecbf14938022aac7998a0710
https://github.com/dominhhai/koa-log4js/blob/c129c9e7d1145553ecbf14938022aac7998a0710/koa-logger.js#L36-L111
train
dominhhai/koa-log4js
koa-logger.js
format
function format (str, tokens) { for (let i = 0; i < tokens.length; i++) { str = str.replace(tokens[i].token, tokens[i].replacement) } return str }
javascript
function format (str, tokens) { for (let i = 0; i < tokens.length; i++) { str = str.replace(tokens[i].token, tokens[i].replacement) } return str }
[ "function", "format", "(", "str", ",", "tokens", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "tokens", ".", "length", ";", "i", "++", ")", "{", "str", "=", "str", ".", "replace", "(", "tokens", "[", "i", "]", ".", "token", ",", "tokens", "[", "i", "]", ".", "replacement", ")", "}", "return", "str", "}" ]
Return formatted log line. @param {String} str @param {IncomingMessage} req @param {ServerResponse} res @return {String} @api private
[ "Return", "formatted", "log", "line", "." ]
c129c9e7d1145553ecbf14938022aac7998a0710
https://github.com/dominhhai/koa-log4js/blob/c129c9e7d1145553ecbf14938022aac7998a0710/koa-logger.js#L198-L203
train
dominhhai/koa-log4js
koa-logger.js
createNoLogCondition
function createNoLogCondition (nolog) { let regexp = null if (nolog) { if (nolog instanceof RegExp) { regexp = nolog } if (typeof nolog === 'string') { regexp = new RegExp(nolog) } if (Array.isArray(nolog)) { let regexpsAsStrings = nolog.map((o) => (o.source ? o.source : o)) regexp = new RegExp(regexpsAsStrings.join('|')) } } return regexp }
javascript
function createNoLogCondition (nolog) { let regexp = null if (nolog) { if (nolog instanceof RegExp) { regexp = nolog } if (typeof nolog === 'string') { regexp = new RegExp(nolog) } if (Array.isArray(nolog)) { let regexpsAsStrings = nolog.map((o) => (o.source ? o.source : o)) regexp = new RegExp(regexpsAsStrings.join('|')) } } return regexp }
[ "function", "createNoLogCondition", "(", "nolog", ")", "{", "let", "regexp", "=", "null", "if", "(", "nolog", ")", "{", "if", "(", "nolog", "instanceof", "RegExp", ")", "{", "regexp", "=", "nolog", "}", "if", "(", "typeof", "nolog", "===", "'string'", ")", "{", "regexp", "=", "new", "RegExp", "(", "nolog", ")", "}", "if", "(", "Array", ".", "isArray", "(", "nolog", ")", ")", "{", "let", "regexpsAsStrings", "=", "nolog", ".", "map", "(", "(", "o", ")", "=>", "(", "o", ".", "source", "?", "o", ".", "source", ":", "o", ")", ")", "regexp", "=", "new", "RegExp", "(", "regexpsAsStrings", ".", "join", "(", "'|'", ")", ")", "}", "}", "return", "regexp", "}" ]
Return RegExp Object about nolog @param {String} nolog @return {RegExp} @api private syntax 1. String 1.1 "\\.gif" NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.gif?fuga LOGGING http://example.com/hoge.agif 1.2 in "\\.gif|\\.jpg$" NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.gif?fuga and http://example.com/hoge.jpg?fuga LOGGING http://example.com/hoge.agif, http://example.com/hoge.ajpg and http://example.com/hoge.jpg?hoge 1.3 in "\\.(gif|jpe?g|png)$" NOT LOGGING http://example.com/hoge.gif and http://example.com/hoge.jpeg LOGGING http://example.com/hoge.gif?uid=2 and http://example.com/hoge.jpg?pid=3 2. RegExp 2.1 in /\.(gif|jpe?g|png)$/ SAME AS 1.3 3. Array 3.1 ["\\.jpg$", "\\.png", "\\.gif"] SAME AS "\\.jpg|\\.png|\\.gif"
[ "Return", "RegExp", "Object", "about", "nolog" ]
c129c9e7d1145553ecbf14938022aac7998a0710
https://github.com/dominhhai/koa-log4js/blob/c129c9e7d1145553ecbf14938022aac7998a0710/koa-logger.js#L232-L250
train
BioPhoton/angular1-star-rating
chore/gulp/helper.js
log
function log(msg, color) { if (typeof(msg) === 'object') { for (var item in msg) { if (msg.hasOwnProperty(item)) { if(color && color in $.util.colors) { $.util.log($.util.colors[color](msg[item])); } $.util.log($.util.colors.lightgreen(msg[item])); } } } else { $.util.log($.util.colors.green(msg)); } }
javascript
function log(msg, color) { if (typeof(msg) === 'object') { for (var item in msg) { if (msg.hasOwnProperty(item)) { if(color && color in $.util.colors) { $.util.log($.util.colors[color](msg[item])); } $.util.log($.util.colors.lightgreen(msg[item])); } } } else { $.util.log($.util.colors.green(msg)); } }
[ "function", "log", "(", "msg", ",", "color", ")", "{", "if", "(", "typeof", "(", "msg", ")", "===", "'object'", ")", "{", "for", "(", "var", "item", "in", "msg", ")", "{", "if", "(", "msg", ".", "hasOwnProperty", "(", "item", ")", ")", "{", "if", "(", "color", "&&", "color", "in", "$", ".", "util", ".", "colors", ")", "{", "$", ".", "util", ".", "log", "(", "$", ".", "util", ".", "colors", "[", "color", "]", "(", "msg", "[", "item", "]", ")", ")", ";", "}", "$", ".", "util", ".", "log", "(", "$", ".", "util", ".", "colors", ".", "lightgreen", "(", "msg", "[", "item", "]", ")", ")", ";", "}", "}", "}", "else", "{", "$", ".", "util", ".", "log", "(", "$", ".", "util", ".", "colors", ".", "green", "(", "msg", ")", ")", ";", "}", "}" ]
Log a message or series of messages using chalk's green color. Can pass in a string, object or array.
[ "Log", "a", "message", "or", "series", "of", "messages", "using", "chalk", "s", "green", "color", ".", "Can", "pass", "in", "a", "string", "object", "or", "array", "." ]
dfff7d9a399f59ad0b8dd8a8309360d4930664a4
https://github.com/BioPhoton/angular1-star-rating/blob/dfff7d9a399f59ad0b8dd8a8309360d4930664a4/chore/gulp/helper.js#L73-L86
train
BioPhoton/angular1-star-rating
chore/gulp/helper.js
clean
function clean(path, done) { log('Cleaning: ' + $.util.colors.green(path)); return del(path, done); }
javascript
function clean(path, done) { log('Cleaning: ' + $.util.colors.green(path)); return del(path, done); }
[ "function", "clean", "(", "path", ",", "done", ")", "{", "log", "(", "'Cleaning: '", "+", "$", ".", "util", ".", "colors", ".", "green", "(", "path", ")", ")", ";", "return", "del", "(", "path", ",", "done", ")", ";", "}" ]
Delete all files in a given path @param {Array} path - array of paths to delete @param {Function} done - callback when complete
[ "Delete", "all", "files", "in", "a", "given", "path" ]
dfff7d9a399f59ad0b8dd8a8309360d4930664a4
https://github.com/BioPhoton/angular1-star-rating/blob/dfff7d9a399f59ad0b8dd8a8309360d4930664a4/chore/gulp/helper.js#L117-L120
train
BioPhoton/angular1-star-rating
chore/gulp/helper.js
bytediffFormatter
function bytediffFormatter(data) { var difference = (data.savings > 0) ? ' smaller.' : ' larger.'; return data.fileName + ' went from ' + (data.startSize / 1000).toFixed(2) + ' kB to ' + (data.endSize / 1000).toFixed(2) + ' kB and is ' + formatPercent(1 - data.percent, 2) + '%' + difference; }
javascript
function bytediffFormatter(data) { var difference = (data.savings > 0) ? ' smaller.' : ' larger.'; return data.fileName + ' went from ' + (data.startSize / 1000).toFixed(2) + ' kB to ' + (data.endSize / 1000).toFixed(2) + ' kB and is ' + formatPercent(1 - data.percent, 2) + '%' + difference; }
[ "function", "bytediffFormatter", "(", "data", ")", "{", "var", "difference", "=", "(", "data", ".", "savings", ">", "0", ")", "?", "' smaller.'", ":", "' larger.'", ";", "return", "data", ".", "fileName", "+", "' went from '", "+", "(", "data", ".", "startSize", "/", "1000", ")", ".", "toFixed", "(", "2", ")", "+", "' kB to '", "+", "(", "data", ".", "endSize", "/", "1000", ")", ".", "toFixed", "(", "2", ")", "+", "' kB and is '", "+", "formatPercent", "(", "1", "-", "data", ".", "percent", ",", "2", ")", "+", "'%'", "+", "difference", ";", "}" ]
Formatter for bytediff to display the size changes after processing @param {Object} data - byte data @return {String} Difference in bytes, formatted
[ "Formatter", "for", "bytediff", "to", "display", "the", "size", "changes", "after", "processing" ]
dfff7d9a399f59ad0b8dd8a8309360d4930664a4
https://github.com/BioPhoton/angular1-star-rating/blob/dfff7d9a399f59ad0b8dd8a8309360d4930664a4/chore/gulp/helper.js#L144-L150
train
devanandb/webpack-mix
src/config.js
function() { let options = {}; tap(Mix.paths.root('.babelrc'), babelrc => { if (File.exists(babelrc)) { options = JSON.parse(File.find(babelrc).read()); } }); if (this.babelConfig) { options = webpackMerge.smart(options, this.babelConfig); } return webpackMerge.smart( { cacheDirectory: true, presets: [ [ 'env', { modules: false, targets: { browsers: ['> 2%'], uglify: true } } ] ], plugins: [ 'transform-object-rest-spread', [ 'transform-runtime', { polyfill: false, helpers: false } ] ] }, options ); }
javascript
function() { let options = {}; tap(Mix.paths.root('.babelrc'), babelrc => { if (File.exists(babelrc)) { options = JSON.parse(File.find(babelrc).read()); } }); if (this.babelConfig) { options = webpackMerge.smart(options, this.babelConfig); } return webpackMerge.smart( { cacheDirectory: true, presets: [ [ 'env', { modules: false, targets: { browsers: ['> 2%'], uglify: true } } ] ], plugins: [ 'transform-object-rest-spread', [ 'transform-runtime', { polyfill: false, helpers: false } ] ] }, options ); }
[ "function", "(", ")", "{", "let", "options", "=", "{", "}", ";", "tap", "(", "Mix", ".", "paths", ".", "root", "(", "'.babelrc'", ")", ",", "babelrc", "=>", "{", "if", "(", "File", ".", "exists", "(", "babelrc", ")", ")", "{", "options", "=", "JSON", ".", "parse", "(", "File", ".", "find", "(", "babelrc", ")", ".", "read", "(", ")", ")", ";", "}", "}", ")", ";", "if", "(", "this", ".", "babelConfig", ")", "{", "options", "=", "webpackMerge", ".", "smart", "(", "options", ",", "this", ".", "babelConfig", ")", ";", "}", "return", "webpackMerge", ".", "smart", "(", "{", "cacheDirectory", ":", "true", ",", "presets", ":", "[", "[", "'env'", ",", "{", "modules", ":", "false", ",", "targets", ":", "{", "browsers", ":", "[", "'> 2%'", "]", ",", "uglify", ":", "true", "}", "}", "]", "]", ",", "plugins", ":", "[", "'transform-object-rest-spread'", ",", "[", "'transform-runtime'", ",", "{", "polyfill", ":", "false", ",", "helpers", ":", "false", "}", "]", "]", "}", ",", "options", ")", ";", "}" ]
The default Babel configuration. @type {Object}
[ "The", "default", "Babel", "configuration", "." ]
0f61f71cf302acfcfb9f2e42004404f95eefbef4
https://github.com/devanandb/webpack-mix/blob/0f61f71cf302acfcfb9f2e42004404f95eefbef4/src/config.js#L139-L180
train
devanandb/webpack-mix
src/webpackPlugins/MixDefinitionsPlugin.js
MixDefinitionsPlugin
function MixDefinitionsPlugin(envPath) { expand( dotenv.config({ path: envPath || Mix.paths.root('.env') }) ); }
javascript
function MixDefinitionsPlugin(envPath) { expand( dotenv.config({ path: envPath || Mix.paths.root('.env') }) ); }
[ "function", "MixDefinitionsPlugin", "(", "envPath", ")", "{", "expand", "(", "dotenv", ".", "config", "(", "{", "path", ":", "envPath", "||", "Mix", ".", "paths", ".", "root", "(", "'.env'", ")", "}", ")", ")", ";", "}" ]
Create a new plugin instance. @param {string} envPath
[ "Create", "a", "new", "plugin", "instance", "." ]
0f61f71cf302acfcfb9f2e42004404f95eefbef4
https://github.com/devanandb/webpack-mix/blob/0f61f71cf302acfcfb9f2e42004404f95eefbef4/src/webpackPlugins/MixDefinitionsPlugin.js#L10-L16
train
ghybs/leaflet-defaulticon-compatibility
src/Icon.Default.compatibility.js
function (name) { // @option imagePath: String // `Icon.Default` will try to auto-detect the location of // the blue icon images. If you are placing these images in a // non-standard way, set this option to point to the right // path, before any marker is added to a map. // Caution: do not use this option with inline base64 image(s). var imagePath = this.options.imagePath || L.Icon.Default.imagePath || ''; // Deprecated (IconDefault.imagePath), backwards-compatibility only if (this._needsInit) { // Modifying imagePath option after _getIconUrl has been called // once in this instance of IconDefault will no longer have any // effect. this._initializeOptions(imagePath); } return imagePath + L.Icon.prototype._getIconUrl.call(this, name); }
javascript
function (name) { // @option imagePath: String // `Icon.Default` will try to auto-detect the location of // the blue icon images. If you are placing these images in a // non-standard way, set this option to point to the right // path, before any marker is added to a map. // Caution: do not use this option with inline base64 image(s). var imagePath = this.options.imagePath || L.Icon.Default.imagePath || ''; // Deprecated (IconDefault.imagePath), backwards-compatibility only if (this._needsInit) { // Modifying imagePath option after _getIconUrl has been called // once in this instance of IconDefault will no longer have any // effect. this._initializeOptions(imagePath); } return imagePath + L.Icon.prototype._getIconUrl.call(this, name); }
[ "function", "(", "name", ")", "{", "var", "imagePath", "=", "this", ".", "options", ".", "imagePath", "||", "L", ".", "Icon", ".", "Default", ".", "imagePath", "||", "''", ";", "if", "(", "this", ".", "_needsInit", ")", "{", "this", ".", "_initializeOptions", "(", "imagePath", ")", ";", "}", "return", "imagePath", "+", "L", ".", "Icon", ".", "prototype", ".", "_getIconUrl", ".", "call", "(", "this", ",", "name", ")", ";", "}" ]
Override to make sure options are retrieved from CSS.
[ "Override", "to", "make", "sure", "options", "are", "retrieved", "from", "CSS", "." ]
23ebe7654149e1b41c9904a62a6a93822896852e
https://github.com/ghybs/leaflet-defaulticon-compatibility/blob/23ebe7654149e1b41c9904a62a6a93822896852e/src/Icon.Default.compatibility.js#L28-L46
train
ghybs/leaflet-defaulticon-compatibility
src/Icon.Default.compatibility.js
function (imagePath) { this._setOptions('icon', _detectIconOptions, imagePath); this._setOptions('shadow', _detectIconOptions, imagePath); this._setOptions('popup', _detectDivOverlayOptions); this._setOptions('tooltip', _detectDivOverlayOptions); this._needsInit = false; }
javascript
function (imagePath) { this._setOptions('icon', _detectIconOptions, imagePath); this._setOptions('shadow', _detectIconOptions, imagePath); this._setOptions('popup', _detectDivOverlayOptions); this._setOptions('tooltip', _detectDivOverlayOptions); this._needsInit = false; }
[ "function", "(", "imagePath", ")", "{", "this", ".", "_setOptions", "(", "'icon'", ",", "_detectIconOptions", ",", "imagePath", ")", ";", "this", ".", "_setOptions", "(", "'shadow'", ",", "_detectIconOptions", ",", "imagePath", ")", ";", "this", ".", "_setOptions", "(", "'popup'", ",", "_detectDivOverlayOptions", ")", ";", "this", ".", "_setOptions", "(", "'tooltip'", ",", "_detectDivOverlayOptions", ")", ";", "this", ".", "_needsInit", "=", "false", ";", "}" ]
Initialize all necessary options for this instance.
[ "Initialize", "all", "necessary", "options", "for", "this", "instance", "." ]
23ebe7654149e1b41c9904a62a6a93822896852e
https://github.com/ghybs/leaflet-defaulticon-compatibility/blob/23ebe7654149e1b41c9904a62a6a93822896852e/src/Icon.Default.compatibility.js#L49-L55
train
ghybs/leaflet-defaulticon-compatibility
src/Icon.Default.compatibility.js
function (name, detectorFn, imagePath) { var options = this.options, prefix = options.classNamePrefix, optionValues = detectorFn(prefix + name, imagePath); for (var optionName in optionValues) { options[name + optionName] = options[name + optionName] || optionValues[optionName]; } }
javascript
function (name, detectorFn, imagePath) { var options = this.options, prefix = options.classNamePrefix, optionValues = detectorFn(prefix + name, imagePath); for (var optionName in optionValues) { options[name + optionName] = options[name + optionName] || optionValues[optionName]; } }
[ "function", "(", "name", ",", "detectorFn", ",", "imagePath", ")", "{", "var", "options", "=", "this", ".", "options", ",", "prefix", "=", "options", ".", "classNamePrefix", ",", "optionValues", "=", "detectorFn", "(", "prefix", "+", "name", ",", "imagePath", ")", ";", "for", "(", "var", "optionName", "in", "optionValues", ")", "{", "options", "[", "name", "+", "optionName", "]", "=", "options", "[", "name", "+", "optionName", "]", "||", "optionValues", "[", "optionName", "]", ";", "}", "}" ]
Retrieve values from CSS and assign to this instance options.
[ "Retrieve", "values", "from", "CSS", "and", "assign", "to", "this", "instance", "options", "." ]
23ebe7654149e1b41c9904a62a6a93822896852e
https://github.com/ghybs/leaflet-defaulticon-compatibility/blob/23ebe7654149e1b41c9904a62a6a93822896852e/src/Icon.Default.compatibility.js#L58-L66
train
ghybs/leaflet-defaulticon-compatibility
src/Icon.Default.compatibility.js
_getStyle
function _getStyle(el, style) { return L.DomUtil.getStyle(el, style) || L.DomUtil.getStyle(el, _kebabToCamelCase(style)); }
javascript
function _getStyle(el, style) { return L.DomUtil.getStyle(el, style) || L.DomUtil.getStyle(el, _kebabToCamelCase(style)); }
[ "function", "_getStyle", "(", "el", ",", "style", ")", "{", "return", "L", ".", "DomUtil", ".", "getStyle", "(", "el", ",", "style", ")", "||", "L", ".", "DomUtil", ".", "getStyle", "(", "el", ",", "_kebabToCamelCase", "(", "style", ")", ")", ";", "}" ]
Factorize style reading fallback for IE8.
[ "Factorize", "style", "reading", "fallback", "for", "IE8", "." ]
23ebe7654149e1b41c9904a62a6a93822896852e
https://github.com/ghybs/leaflet-defaulticon-compatibility/blob/23ebe7654149e1b41c9904a62a6a93822896852e/src/Icon.Default.compatibility.js#L134-L136
train
gocanto/lazy-vue
src/js/image.js
fadeIn
function fadeIn(el) { el.style.opacity = 0; el.style.display = "block"; (function fadeIn() { let val = parseFloat(el.style.opacity); if (! ((val += .1) > 1)) { el.style.opacity = val; setTimeout(fadeIn, 40); } })(); }
javascript
function fadeIn(el) { el.style.opacity = 0; el.style.display = "block"; (function fadeIn() { let val = parseFloat(el.style.opacity); if (! ((val += .1) > 1)) { el.style.opacity = val; setTimeout(fadeIn, 40); } })(); }
[ "function", "fadeIn", "(", "el", ")", "{", "el", ".", "style", ".", "opacity", "=", "0", ";", "el", ".", "style", ".", "display", "=", "\"block\"", ";", "(", "function", "fadeIn", "(", ")", "{", "let", "val", "=", "parseFloat", "(", "el", ".", "style", ".", "opacity", ")", ";", "if", "(", "!", "(", "(", "val", "+=", ".1", ")", ">", "1", ")", ")", "{", "el", ".", "style", ".", "opacity", "=", "val", ";", "setTimeout", "(", "fadeIn", ",", "40", ")", ";", "}", "}", ")", "(", ")", ";", "}" ]
Apply a fade in effect to a given element. @param {Object} el @return {Void}
[ "Apply", "a", "fade", "in", "effect", "to", "a", "given", "element", "." ]
c2113455c6a662ad627f52357958b1a0997ddcb3
https://github.com/gocanto/lazy-vue/blob/c2113455c6a662ad627f52357958b1a0997ddcb3/src/js/image.js#L27-L39
train
linkedin/Fiber
src/fiber.js
copy
function copy(from, to) { var name; for (name in from) { if (from.hasOwnProperty(name)) { to[name] = from[name]; } } }
javascript
function copy(from, to) { var name; for (name in from) { if (from.hasOwnProperty(name)) { to[name] = from[name]; } } }
[ "function", "copy", "(", "from", ",", "to", ")", "{", "var", "name", ";", "for", "(", "name", "in", "from", ")", "{", "if", "(", "from", ".", "hasOwnProperty", "(", "name", ")", ")", "{", "to", "[", "name", "]", "=", "from", "[", "name", "]", ";", "}", "}", "}" ]
Helper function to copy properties from one object to the other.
[ "Helper", "function", "to", "copy", "properties", "from", "one", "object", "to", "the", "other", "." ]
e930b220a95246357b4929b37a6a5e9e6679843f
https://github.com/linkedin/Fiber/blob/e930b220a95246357b4929b37a6a5e9e6679843f/src/fiber.js#L54-L61
train
Foxandxss/koa-unless
index.js
matchesCustom
function matchesCustom(ctx, opts) { if (opts.custom) { return opts.custom.call(ctx); } return false; }
javascript
function matchesCustom(ctx, opts) { if (opts.custom) { return opts.custom.call(ctx); } return false; }
[ "function", "matchesCustom", "(", "ctx", ",", "opts", ")", "{", "if", "(", "opts", ".", "custom", ")", "{", "return", "opts", ".", "custom", ".", "call", "(", "ctx", ")", ";", "}", "return", "false", ";", "}" ]
Returns boolean indicating whether the custom function returns true. @param ctx - Koa context @param opts - unless configuration @returns {boolean}
[ "Returns", "boolean", "indicating", "whether", "the", "custom", "function", "returns", "true", "." ]
d692252c06b5f2572fe70187722b9be0dba2014f
https://github.com/Foxandxss/koa-unless/blob/d692252c06b5f2572fe70187722b9be0dba2014f/index.js#L38-L43
train
Foxandxss/koa-unless
index.js
matchesPath
function matchesPath(requestedUrl, opts) { var paths = !opts.path || Array.isArray(opts.path) ? opts.path : [opts.path]; if (paths) { return paths.some(function(p) { return (typeof p === 'string' && p === requestedUrl.pathname) || (p instanceof RegExp && !! p.exec(requestedUrl.pathname)); }); } return false; }
javascript
function matchesPath(requestedUrl, opts) { var paths = !opts.path || Array.isArray(opts.path) ? opts.path : [opts.path]; if (paths) { return paths.some(function(p) { return (typeof p === 'string' && p === requestedUrl.pathname) || (p instanceof RegExp && !! p.exec(requestedUrl.pathname)); }); } return false; }
[ "function", "matchesPath", "(", "requestedUrl", ",", "opts", ")", "{", "var", "paths", "=", "!", "opts", ".", "path", "||", "Array", ".", "isArray", "(", "opts", ".", "path", ")", "?", "opts", ".", "path", ":", "[", "opts", ".", "path", "]", ";", "if", "(", "paths", ")", "{", "return", "paths", ".", "some", "(", "function", "(", "p", ")", "{", "return", "(", "typeof", "p", "===", "'string'", "&&", "p", "===", "requestedUrl", ".", "pathname", ")", "||", "(", "p", "instanceof", "RegExp", "&&", "!", "!", "p", ".", "exec", "(", "requestedUrl", ".", "pathname", ")", ")", ";", "}", ")", ";", "}", "return", "false", ";", "}" ]
Returns boolean indicating whether the requestUrl matches against the paths configured. @param requestedUrl - url requested by user @param opts - unless configuration @returns {boolean}
[ "Returns", "boolean", "indicating", "whether", "the", "requestUrl", "matches", "against", "the", "paths", "configured", "." ]
d692252c06b5f2572fe70187722b9be0dba2014f
https://github.com/Foxandxss/koa-unless/blob/d692252c06b5f2572fe70187722b9be0dba2014f/index.js#L52-L64
train
Foxandxss/koa-unless
index.js
matchesExtension
function matchesExtension(requestedUrl, opts) { var exts = !opts.ext || Array.isArray(opts.ext) ? opts.ext : [opts.ext]; if (exts) { return exts.some(function(ext) { return requestedUrl.pathname.substr(ext.length * -1) === ext; }); } }
javascript
function matchesExtension(requestedUrl, opts) { var exts = !opts.ext || Array.isArray(opts.ext) ? opts.ext : [opts.ext]; if (exts) { return exts.some(function(ext) { return requestedUrl.pathname.substr(ext.length * -1) === ext; }); } }
[ "function", "matchesExtension", "(", "requestedUrl", ",", "opts", ")", "{", "var", "exts", "=", "!", "opts", ".", "ext", "||", "Array", ".", "isArray", "(", "opts", ".", "ext", ")", "?", "opts", ".", "ext", ":", "[", "opts", ".", "ext", "]", ";", "if", "(", "exts", ")", "{", "return", "exts", ".", "some", "(", "function", "(", "ext", ")", "{", "return", "requestedUrl", ".", "pathname", ".", "substr", "(", "ext", ".", "length", "*", "-", "1", ")", "===", "ext", ";", "}", ")", ";", "}", "}" ]
Returns boolean indicating whether the requestUrl ends with the configured extensions. @param requestedUrl - url requested by user @param opts - unless configuration @returns {boolean}
[ "Returns", "boolean", "indicating", "whether", "the", "requestUrl", "ends", "with", "the", "configured", "extensions", "." ]
d692252c06b5f2572fe70187722b9be0dba2014f
https://github.com/Foxandxss/koa-unless/blob/d692252c06b5f2572fe70187722b9be0dba2014f/index.js#L73-L82
train
Foxandxss/koa-unless
index.js
matchesMethod
function matchesMethod(method, opts) { var methods = !opts.method || Array.isArray(opts.method) ? opts.method : [opts.method]; if (methods) { return !!~methods.indexOf(method); } }
javascript
function matchesMethod(method, opts) { var methods = !opts.method || Array.isArray(opts.method) ? opts.method : [opts.method]; if (methods) { return !!~methods.indexOf(method); } }
[ "function", "matchesMethod", "(", "method", ",", "opts", ")", "{", "var", "methods", "=", "!", "opts", ".", "method", "||", "Array", ".", "isArray", "(", "opts", ".", "method", ")", "?", "opts", ".", "method", ":", "[", "opts", ".", "method", "]", ";", "if", "(", "methods", ")", "{", "return", "!", "!", "~", "methods", ".", "indexOf", "(", "method", ")", ";", "}", "}" ]
Returns boolean indicating whether the request method matches the configured methods. @param requestedUrl - url requested by user @param opts - unless configuration @returns {boolean}
[ "Returns", "boolean", "indicating", "whether", "the", "request", "method", "matches", "the", "configured", "methods", "." ]
d692252c06b5f2572fe70187722b9be0dba2014f
https://github.com/Foxandxss/koa-unless/blob/d692252c06b5f2572fe70187722b9be0dba2014f/index.js#L91-L98
train
Skellington-Closet/slack-mock
examples/slack-app/controller.js
startRtm
function startRtm (token) { api.rtm.start(token, (err, bot) => { if (err) { return console.log(err) } bot.on(/hello/, (bot, message) => { bot.reply(message, 'GO CUBS') }) bot.on(/howdy/, (bot, message) => { bot.reply(message, 'GO TRIBE') }) }) }
javascript
function startRtm (token) { api.rtm.start(token, (err, bot) => { if (err) { return console.log(err) } bot.on(/hello/, (bot, message) => { bot.reply(message, 'GO CUBS') }) bot.on(/howdy/, (bot, message) => { bot.reply(message, 'GO TRIBE') }) }) }
[ "function", "startRtm", "(", "token", ")", "{", "api", ".", "rtm", ".", "start", "(", "token", ",", "(", "err", ",", "bot", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "console", ".", "log", "(", "err", ")", "}", "bot", ".", "on", "(", "/", "hello", "/", ",", "(", "bot", ",", "message", ")", "=>", "{", "bot", ".", "reply", "(", "message", ",", "'GO CUBS'", ")", "}", ")", "bot", ".", "on", "(", "/", "howdy", "/", ",", "(", "bot", ",", "message", ")", "=>", "{", "bot", ".", "reply", "(", "message", ",", "'GO TRIBE'", ")", "}", ")", "}", ")", "}" ]
starts the rtm connection
[ "starts", "the", "rtm", "connection" ]
7bf3eb5073a8a2c071ece360a7b8729390a37024
https://github.com/Skellington-Closet/slack-mock/blob/7bf3eb5073a8a2c071ece360a7b8729390a37024/examples/slack-app/controller.js#L64-L78
train
Skellington-Closet/slack-mock
src/mocker/rtm.js
sendToClient
function sendToClient (message, client) { return new Promise((resolve, reject) => { try { client.send(JSON.stringify(message), (e) => { if (e) { logger.error(`could not send rtm message to client`, e) return reject(e) } }) } catch (e) { logger.error(`could not send rtm message to client`, e) return reject(e) } resolve() }) }
javascript
function sendToClient (message, client) { return new Promise((resolve, reject) => { try { client.send(JSON.stringify(message), (e) => { if (e) { logger.error(`could not send rtm message to client`, e) return reject(e) } }) } catch (e) { logger.error(`could not send rtm message to client`, e) return reject(e) } resolve() }) }
[ "function", "sendToClient", "(", "message", ",", "client", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "try", "{", "client", ".", "send", "(", "JSON", ".", "stringify", "(", "message", ")", ",", "(", "e", ")", "=>", "{", "if", "(", "e", ")", "{", "logger", ".", "error", "(", "`", "`", ",", "e", ")", "return", "reject", "(", "e", ")", "}", "}", ")", "}", "catch", "(", "e", ")", "{", "logger", ".", "error", "(", "`", "`", ",", "e", ")", "return", "reject", "(", "e", ")", "}", "resolve", "(", ")", "}", ")", "}" ]
sends the given message to the given client
[ "sends", "the", "given", "message", "to", "the", "given", "client" ]
7bf3eb5073a8a2c071ece360a7b8729390a37024
https://github.com/Skellington-Closet/slack-mock/blob/7bf3eb5073a8a2c071ece360a7b8729390a37024/src/mocker/rtm.js#L66-L82
train
CSS-Tricks/AnythingZoomer
demo/page.js
scrollableElement
function scrollableElement(els) { for (var i = 0, argLength = arguments.length; i <argLength; i++) { var el = arguments[i], $scrollElement = $(el); if ($scrollElement.scrollTop()> 0) { return el; } else { $scrollElement.scrollTop(1); var isScrollable = $scrollElement.scrollTop()> 0; $scrollElement.scrollTop(0); if (isScrollable) { return el; } } } return []; }
javascript
function scrollableElement(els) { for (var i = 0, argLength = arguments.length; i <argLength; i++) { var el = arguments[i], $scrollElement = $(el); if ($scrollElement.scrollTop()> 0) { return el; } else { $scrollElement.scrollTop(1); var isScrollable = $scrollElement.scrollTop()> 0; $scrollElement.scrollTop(0); if (isScrollable) { return el; } } } return []; }
[ "function", "scrollableElement", "(", "els", ")", "{", "for", "(", "var", "i", "=", "0", ",", "argLength", "=", "arguments", ".", "length", ";", "i", "<", "argLength", ";", "i", "++", ")", "{", "var", "el", "=", "arguments", "[", "i", "]", ",", "$scrollElement", "=", "$", "(", "el", ")", ";", "if", "(", "$scrollElement", ".", "scrollTop", "(", ")", ">", "0", ")", "{", "return", "el", ";", "}", "else", "{", "$scrollElement", ".", "scrollTop", "(", "1", ")", ";", "var", "isScrollable", "=", "$scrollElement", ".", "scrollTop", "(", ")", ">", "0", ";", "$scrollElement", ".", "scrollTop", "(", "0", ")", ";", "if", "(", "isScrollable", ")", "{", "return", "el", ";", "}", "}", "}", "return", "[", "]", ";", "}" ]
use the first element that is "scrollable"
[ "use", "the", "first", "element", "that", "is", "scrollable" ]
5028f2ed79d5af7c4d66c0c63ef8325a6ba049c1
https://github.com/CSS-Tricks/AnythingZoomer/blob/5028f2ed79d5af7c4d66c0c63ef8325a6ba049c1/demo/page.js#L43-L59
train
arthurvaverko/ngx-highlight
dist/vendor.bundle.js
instantiationError
function instantiationError(injector, originalException, originalStack, key) { return injectionError(injector, key, function () { var /** @type {?} */ first = stringify(this.keys[0].token); return getOriginalError(this).message + ": Error during instantiation of " + first + "!" + constructResolvingPath(this.keys) + "."; }, originalException); }
javascript
function instantiationError(injector, originalException, originalStack, key) { return injectionError(injector, key, function () { var /** @type {?} */ first = stringify(this.keys[0].token); return getOriginalError(this).message + ": Error during instantiation of " + first + "!" + constructResolvingPath(this.keys) + "."; }, originalException); }
[ "function", "instantiationError", "(", "injector", ",", "originalException", ",", "originalStack", ",", "key", ")", "{", "return", "injectionError", "(", "injector", ",", "key", ",", "function", "(", ")", "{", "var", "first", "=", "stringify", "(", "this", ".", "keys", "[", "0", "]", ".", "token", ")", ";", "return", "getOriginalError", "(", "this", ")", ".", "message", "+", "\": Error during instantiation of \"", "+", "first", "+", "\"!\"", "+", "constructResolvingPath", "(", "this", ".", "keys", ")", "+", "\".\"", ";", "}", ",", "originalException", ")", ";", "}" ]
Thrown when a constructing type returns with an Error. The `InstantiationError` class contains the original error plus the dependency graph which caused this object to be instantiated. ### Example ([live demo](http://plnkr.co/edit/7aWYdcqTQsP0eNqEdUAf?p=preview)) ```typescript class A { constructor() { throw new Error('message'); } } var injector = Injector.resolveAndCreate([A]); try { injector.get(A); } catch (e) { expect(e instanceof InstantiationError).toBe(true); expect(e.originalException.message).toEqual("message"); expect(e.originalStack).toBeDefined(); } ``` @param {?} injector @param {?} originalException @param {?} originalStack @param {?} key @return {?}
[ "Thrown", "when", "a", "constructing", "type", "returns", "with", "an", "Error", "." ]
4e98e58e0d718a093cfe4d31ac03a21b3d1e1405
https://github.com/arthurvaverko/ngx-highlight/blob/4e98e58e0d718a093cfe4d31ac03a21b3d1e1405/dist/vendor.bundle.js#L1541-L1546
train
arthurvaverko/ngx-highlight
dist/vendor.bundle.js
templateVisitAll
function templateVisitAll(visitor, asts, context) { if (context === void 0) { context = null; } var /** @type {?} */ result = []; var /** @type {?} */ visit = visitor.visit ? function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } : function (ast) { return ast.visit(visitor, context); }; asts.forEach(function (ast) { var /** @type {?} */ astResult = visit(ast); if (astResult) { result.push(astResult); } }); return result; }
javascript
function templateVisitAll(visitor, asts, context) { if (context === void 0) { context = null; } var /** @type {?} */ result = []; var /** @type {?} */ visit = visitor.visit ? function (ast) { return visitor.visit(ast, context) || ast.visit(visitor, context); } : function (ast) { return ast.visit(visitor, context); }; asts.forEach(function (ast) { var /** @type {?} */ astResult = visit(ast); if (astResult) { result.push(astResult); } }); return result; }
[ "function", "templateVisitAll", "(", "visitor", ",", "asts", ",", "context", ")", "{", "if", "(", "context", "===", "void", "0", ")", "{", "context", "=", "null", ";", "}", "var", "result", "=", "[", "]", ";", "var", "visit", "=", "visitor", ".", "visit", "?", "function", "(", "ast", ")", "{", "return", "visitor", ".", "visit", "(", "ast", ",", "context", ")", "||", "ast", ".", "visit", "(", "visitor", ",", "context", ")", ";", "}", ":", "function", "(", "ast", ")", "{", "return", "ast", ".", "visit", "(", "visitor", ",", "context", ")", ";", "}", ";", "asts", ".", "forEach", "(", "function", "(", "ast", ")", "{", "var", "astResult", "=", "visit", "(", "ast", ")", ";", "if", "(", "astResult", ")", "{", "result", ".", "push", "(", "astResult", ")", ";", "}", "}", ")", ";", "return", "result", ";", "}" ]
Visit every node in a list of {\@link TemplateAst}s with the given {\@link TemplateAstVisitor}. @param {?} visitor @param {?} asts @param {?=} context @return {?}
[ "Visit", "every", "node", "in", "a", "list", "of", "{", "\\" ]
4e98e58e0d718a093cfe4d31ac03a21b3d1e1405
https://github.com/arthurvaverko/ngx-highlight/blob/4e98e58e0d718a093cfe4d31ac03a21b3d1e1405/dist/vendor.bundle.js#L24668-L24681
train
seeden/mongoose-hrbac
src/index.js
can
function can(rbac, action, resource, cb) { // check existance of permission rbac.getPermission(action, resource, (err, permission) => { if (err) { return cb(err); } if (!permission) { return cb(null, false); } // check user additional permissions if (indexOf(this.permissions, permission.name) !== -1) { return cb(null, true); } if (!this.role) { return cb(null, false); } // check permission inside user role return rbac.can(this.role, action, resource, cb); }); return this; }
javascript
function can(rbac, action, resource, cb) { // check existance of permission rbac.getPermission(action, resource, (err, permission) => { if (err) { return cb(err); } if (!permission) { return cb(null, false); } // check user additional permissions if (indexOf(this.permissions, permission.name) !== -1) { return cb(null, true); } if (!this.role) { return cb(null, false); } // check permission inside user role return rbac.can(this.role, action, resource, cb); }); return this; }
[ "function", "can", "(", "rbac", ",", "action", ",", "resource", ",", "cb", ")", "{", "rbac", ".", "getPermission", "(", "action", ",", "resource", ",", "(", "err", ",", "permission", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "if", "(", "!", "permission", ")", "{", "return", "cb", "(", "null", ",", "false", ")", ";", "}", "if", "(", "indexOf", "(", "this", ".", "permissions", ",", "permission", ".", "name", ")", "!==", "-", "1", ")", "{", "return", "cb", "(", "null", ",", "true", ")", ";", "}", "if", "(", "!", "this", ".", "role", ")", "{", "return", "cb", "(", "null", ",", "false", ")", ";", "}", "return", "rbac", ".", "can", "(", "this", ".", "role", ",", "action", ",", "resource", ",", "cb", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
Check if user has assigned a specific permission @param {RBAC} rbac Instance of RBAC @param {String} action Name of action @param {String} resource Name of resource @return {Boolean}
[ "Check", "if", "user", "has", "assigned", "a", "specific", "permission" ]
4239f40635d3fead299b8721acfdb7145bc2f9e2
https://github.com/seeden/mongoose-hrbac/blob/4239f40635d3fead299b8721acfdb7145bc2f9e2/src/index.js#L27-L52
train
seeden/mongoose-hrbac
src/index.js
addPermission
function addPermission(rbac, action, resource, cb) { rbac.getPermission(action, resource, (err, permission) => { if (err) { return cb(err); } if (!permission) { return cb(new Error('Permission not exists')); } if (indexOf(this.permissions, permission.name) !== -1) { return cb(new Error('Permission is already assigned')); } this.permissions.push(permission.name); return this.save((err2, user) => { if (err2) { return cb(err2); } if (!user) { return cb(new Error('User is undefined')); } return cb(null, true); }); }); return this; }
javascript
function addPermission(rbac, action, resource, cb) { rbac.getPermission(action, resource, (err, permission) => { if (err) { return cb(err); } if (!permission) { return cb(new Error('Permission not exists')); } if (indexOf(this.permissions, permission.name) !== -1) { return cb(new Error('Permission is already assigned')); } this.permissions.push(permission.name); return this.save((err2, user) => { if (err2) { return cb(err2); } if (!user) { return cb(new Error('User is undefined')); } return cb(null, true); }); }); return this; }
[ "function", "addPermission", "(", "rbac", ",", "action", ",", "resource", ",", "cb", ")", "{", "rbac", ".", "getPermission", "(", "action", ",", "resource", ",", "(", "err", ",", "permission", ")", "=>", "{", "if", "(", "err", ")", "{", "return", "cb", "(", "err", ")", ";", "}", "if", "(", "!", "permission", ")", "{", "return", "cb", "(", "new", "Error", "(", "'Permission not exists'", ")", ")", ";", "}", "if", "(", "indexOf", "(", "this", ".", "permissions", ",", "permission", ".", "name", ")", "!==", "-", "1", ")", "{", "return", "cb", "(", "new", "Error", "(", "'Permission is already assigned'", ")", ")", ";", "}", "this", ".", "permissions", ".", "push", "(", "permission", ".", "name", ")", ";", "return", "this", ".", "save", "(", "(", "err2", ",", "user", ")", "=>", "{", "if", "(", "err2", ")", "{", "return", "cb", "(", "err2", ")", ";", "}", "if", "(", "!", "user", ")", "{", "return", "cb", "(", "new", "Error", "(", "'User is undefined'", ")", ")", ";", "}", "return", "cb", "(", "null", ",", "true", ")", ";", "}", ")", ";", "}", ")", ";", "return", "this", ";", "}" ]
Assign additional permissions to the user @param {String|Array} permissions Array of permissions or string representing of permission @param {Function} cb Callback
[ "Assign", "additional", "permissions", "to", "the", "user" ]
4239f40635d3fead299b8721acfdb7145bc2f9e2
https://github.com/seeden/mongoose-hrbac/blob/4239f40635d3fead299b8721acfdb7145bc2f9e2/src/index.js#L59-L88
train
seeden/mongoose-hrbac
src/index.js
hasRole
function hasRole(rbac, role, cb) { if (!this.role) { cb(null, false); return this; } // check existance of permission rbac.hasRole(this.role, role, cb); return this; }
javascript
function hasRole(rbac, role, cb) { if (!this.role) { cb(null, false); return this; } // check existance of permission rbac.hasRole(this.role, role, cb); return this; }
[ "function", "hasRole", "(", "rbac", ",", "role", ",", "cb", ")", "{", "if", "(", "!", "this", ".", "role", ")", "{", "cb", "(", "null", ",", "false", ")", ";", "return", "this", ";", "}", "rbac", ".", "hasRole", "(", "this", ".", "role", ",", "role", ",", "cb", ")", ";", "return", "this", ";", "}" ]
Check if user has assigned a specific role @param {RBAC} rbac Instance of RBAC @param {String} name Name of role @return {Boolean} [description]
[ "Check", "if", "user", "has", "assigned", "a", "specific", "role" ]
4239f40635d3fead299b8721acfdb7145bc2f9e2
https://github.com/seeden/mongoose-hrbac/blob/4239f40635d3fead299b8721acfdb7145bc2f9e2/src/index.js#L142-L151
train
liorwohl/html5-simple-date-input-polyfill
html5-simple-date-input-polyfill.js
addcalendarExtenderToDateInputs
function addcalendarExtenderToDateInputs () { //get and loop all the input[type=date]s in the page that dont have "haveCal" class yet var dateInputs = document.querySelectorAll('input[type=date]:not(.haveCal)'); [].forEach.call(dateInputs, function (dateInput) { //call calendarExtender function on the input new calendarExtender(dateInput); //mark that it have calendar dateInput.classList.add('haveCal'); }); }
javascript
function addcalendarExtenderToDateInputs () { //get and loop all the input[type=date]s in the page that dont have "haveCal" class yet var dateInputs = document.querySelectorAll('input[type=date]:not(.haveCal)'); [].forEach.call(dateInputs, function (dateInput) { //call calendarExtender function on the input new calendarExtender(dateInput); //mark that it have calendar dateInput.classList.add('haveCal'); }); }
[ "function", "addcalendarExtenderToDateInputs", "(", ")", "{", "var", "dateInputs", "=", "document", ".", "querySelectorAll", "(", "'input[type=date]:not(.haveCal)'", ")", ";", "[", "]", ".", "forEach", ".", "call", "(", "dateInputs", ",", "function", "(", "dateInput", ")", "{", "new", "calendarExtender", "(", "dateInput", ")", ";", "dateInput", ".", "classList", ".", "add", "(", "'haveCal'", ")", ";", "}", ")", ";", "}" ]
will add the calendarExtender to all inputs in the page
[ "will", "add", "the", "calendarExtender", "to", "all", "inputs", "in", "the", "page" ]
8882f82c9eb1ef3bff1fdc41a7fb3bb4730c0abe
https://github.com/liorwohl/html5-simple-date-input-polyfill/blob/8882f82c9eb1ef3bff1fdc41a7fb3bb4730c0abe/html5-simple-date-input-polyfill.js#L222-L231
train
SamVerschueren/mongoose-seeder
index.js
function(data, done) { try { // Retrieve all the dependencies _.forEach(data._dependencies || {}, function(value, key) { if(this.sandbox[key] !== undefined) { // Do nothing if the dependency is already defined return; } this.sandbox[key] = module.parent.require(value); }.bind(this)); // Remove the dependencies property delete data._dependencies; } catch(e) { // Stop execution and return the MODULE_NOT_FOUND error return done(e); } // Iterate over all the data objects async.eachSeries(Object.keys(data), function(key, next) { _this.result[key] = {}; var value = data[key]; try { if(!value._model) { // Throw an error if the model could not be found throw new Error('Please provide a _model property that describes which database model should be used.'); } var modelName = value._model; // Remove model and unique properties delete value._model; // retrieve the model depending on the name provided var Model = mongoose.model(modelName); async.series([ function(callback) { if(_this.options.dropCollections === true) { // Drop the collection mongoose.connection.db.dropCollection(Model.collection.name, function(err) { callback(); }); } else { callback(); } }, function(callback) { async.eachSeries(Object.keys(value), function(k, innerNext) { var modelData = value[k], data = _this._unwind(modelData); // Create the model Model.create(data, function(err, result) { if(err) { // Do not stop execution if an error occurs return innerNext(err); } _this.result[key][k] = result; innerNext(); }); }, callback); } ], next); } catch(err) { // If the model does not exist, stop the execution return next(err); } }, function(err) { if(err) { // Make sure to not return the result return done(err); } done(undefined, _this.result); }); }
javascript
function(data, done) { try { // Retrieve all the dependencies _.forEach(data._dependencies || {}, function(value, key) { if(this.sandbox[key] !== undefined) { // Do nothing if the dependency is already defined return; } this.sandbox[key] = module.parent.require(value); }.bind(this)); // Remove the dependencies property delete data._dependencies; } catch(e) { // Stop execution and return the MODULE_NOT_FOUND error return done(e); } // Iterate over all the data objects async.eachSeries(Object.keys(data), function(key, next) { _this.result[key] = {}; var value = data[key]; try { if(!value._model) { // Throw an error if the model could not be found throw new Error('Please provide a _model property that describes which database model should be used.'); } var modelName = value._model; // Remove model and unique properties delete value._model; // retrieve the model depending on the name provided var Model = mongoose.model(modelName); async.series([ function(callback) { if(_this.options.dropCollections === true) { // Drop the collection mongoose.connection.db.dropCollection(Model.collection.name, function(err) { callback(); }); } else { callback(); } }, function(callback) { async.eachSeries(Object.keys(value), function(k, innerNext) { var modelData = value[k], data = _this._unwind(modelData); // Create the model Model.create(data, function(err, result) { if(err) { // Do not stop execution if an error occurs return innerNext(err); } _this.result[key][k] = result; innerNext(); }); }, callback); } ], next); } catch(err) { // If the model does not exist, stop the execution return next(err); } }, function(err) { if(err) { // Make sure to not return the result return done(err); } done(undefined, _this.result); }); }
[ "function", "(", "data", ",", "done", ")", "{", "try", "{", "_", ".", "forEach", "(", "data", ".", "_dependencies", "||", "{", "}", ",", "function", "(", "value", ",", "key", ")", "{", "if", "(", "this", ".", "sandbox", "[", "key", "]", "!==", "undefined", ")", "{", "return", ";", "}", "this", ".", "sandbox", "[", "key", "]", "=", "module", ".", "parent", ".", "require", "(", "value", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "delete", "data", ".", "_dependencies", ";", "}", "catch", "(", "e", ")", "{", "return", "done", "(", "e", ")", ";", "}", "async", ".", "eachSeries", "(", "Object", ".", "keys", "(", "data", ")", ",", "function", "(", "key", ",", "next", ")", "{", "_this", ".", "result", "[", "key", "]", "=", "{", "}", ";", "var", "value", "=", "data", "[", "key", "]", ";", "try", "{", "if", "(", "!", "value", ".", "_model", ")", "{", "throw", "new", "Error", "(", "'Please provide a _model property that describes which database model should be used.'", ")", ";", "}", "var", "modelName", "=", "value", ".", "_model", ";", "delete", "value", ".", "_model", ";", "var", "Model", "=", "mongoose", ".", "model", "(", "modelName", ")", ";", "async", ".", "series", "(", "[", "function", "(", "callback", ")", "{", "if", "(", "_this", ".", "options", ".", "dropCollections", "===", "true", ")", "{", "mongoose", ".", "connection", ".", "db", ".", "dropCollection", "(", "Model", ".", "collection", ".", "name", ",", "function", "(", "err", ")", "{", "callback", "(", ")", ";", "}", ")", ";", "}", "else", "{", "callback", "(", ")", ";", "}", "}", ",", "function", "(", "callback", ")", "{", "async", ".", "eachSeries", "(", "Object", ".", "keys", "(", "value", ")", ",", "function", "(", "k", ",", "innerNext", ")", "{", "var", "modelData", "=", "value", "[", "k", "]", ",", "data", "=", "_this", ".", "_unwind", "(", "modelData", ")", ";", "Model", ".", "create", "(", "data", ",", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "return", "innerNext", "(", "err", ")", ";", "}", "_this", ".", "result", "[", "key", "]", "[", "k", "]", "=", "result", ";", "innerNext", "(", ")", ";", "}", ")", ";", "}", ",", "callback", ")", ";", "}", "]", ",", "next", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "next", "(", "err", ")", ";", "}", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", ";", "}", "done", "(", "undefined", ",", "_this", ".", "result", ")", ";", "}", ")", ";", "}" ]
The internal method for seeding the database. @param {Object} data The data that should be seeded. @param {Function} done The method that should be called when the seeding is done
[ "The", "internal", "method", "for", "seeding", "the", "database", "." ]
ea08d510228a76e5eafa08e1f94cbe8cf0a6614d
https://github.com/SamVerschueren/mongoose-seeder/blob/ea08d510228a76e5eafa08e1f94cbe8cf0a6614d/index.js#L37-L121
train
SamVerschueren/mongoose-seeder
index.js
function(ref) { var keys = ref.split('.'), key = keys.shift(), result = _this.result[key]; if(!result) { // If the result does not exist, return an empty throw new TypeError('Could not read property \'' + key + '\' from undefined'); } // Iterate over all the keys and find the property while((key = keys.shift())) { result = result[key]; } if(_.isObject(result) && !_.isArray(result)) { // Test if the result we have is an object. This means the user wants to reference // to the _id of the object. if(!result._id) { // If no _id property exists, throw a TypeError that the property could not be found throw new TypeError('Could not read property \'_id\' of ' + JSON.stringify(result)); } return result._id; } return result; }
javascript
function(ref) { var keys = ref.split('.'), key = keys.shift(), result = _this.result[key]; if(!result) { // If the result does not exist, return an empty throw new TypeError('Could not read property \'' + key + '\' from undefined'); } // Iterate over all the keys and find the property while((key = keys.shift())) { result = result[key]; } if(_.isObject(result) && !_.isArray(result)) { // Test if the result we have is an object. This means the user wants to reference // to the _id of the object. if(!result._id) { // If no _id property exists, throw a TypeError that the property could not be found throw new TypeError('Could not read property \'_id\' of ' + JSON.stringify(result)); } return result._id; } return result; }
[ "function", "(", "ref", ")", "{", "var", "keys", "=", "ref", ".", "split", "(", "'.'", ")", ",", "key", "=", "keys", ".", "shift", "(", ")", ",", "result", "=", "_this", ".", "result", "[", "key", "]", ";", "if", "(", "!", "result", ")", "{", "throw", "new", "TypeError", "(", "'Could not read property \\''", "+", "\\'", "+", "key", ")", ";", "}", "'\\' from undefined'", "\\'", "while", "(", "(", "key", "=", "keys", ".", "shift", "(", ")", ")", ")", "{", "result", "=", "result", "[", "key", "]", ";", "}", "}" ]
This method searches for the _id associated with the object represented by the reference provided. @param {String} ref The string representation of the reference. @return {String} The reference to the object.
[ "This", "method", "searches", "for", "the", "_id", "associated", "with", "the", "object", "represented", "by", "the", "reference", "provided", "." ]
ea08d510228a76e5eafa08e1f94cbe8cf0a6614d
https://github.com/SamVerschueren/mongoose-seeder/blob/ea08d510228a76e5eafa08e1f94cbe8cf0a6614d/index.js#L187-L214
train
SamVerschueren/mongoose-seeder
index.js
function(data, options, callback) { if(_.isFunction(options)) { // Set the correct callback function callback = options; options = {}; } // Create a deferred object for the promise var def = Q.defer(); // If no callback is provided, use a noop function callback = callback || function() {}; // Clear earlier results and options _this.result = {}; _this.options = {}; _this.sandbox = vm.createContext(); // Defaulting the options _this.options = _.extend(_.clone(DEFAULT_OPTIONS), options); if(_this.options.dropCollections === true && _this.options.dropDatabase === true) { // Only one of the two flags can be turned on. If both are true, this means the // user set the dropCollections itself and this should have higher priority then // the default values. _this.options.dropDatabase = false; } if(_this.options.dropDatabase === true) { // Make sure to drop the database first mongoose.connection.db.dropDatabase(function(err) { if(err) { // Stop seeding if an error occurred return done(err); } // Start seeding when the database is dropped _this._seed(_.cloneDeep(data), done); }); } else { // Do not drop the entire database, start seeding _this._seed(_.cloneDeep(data), done); } /** * This method will be invoked when the seeding is completed or when something * went wrong. This method will then call the callback and rejects or resolves * the promise object. This way, users of the library can use both. * * @param {*} err [description] * @param {Object} result [description] */ function done(err, result) { if(err) { def.reject(err); callback(err); return; } def.resolve(result); callback(undefined, result); } // Return the promise return def.promise; }
javascript
function(data, options, callback) { if(_.isFunction(options)) { // Set the correct callback function callback = options; options = {}; } // Create a deferred object for the promise var def = Q.defer(); // If no callback is provided, use a noop function callback = callback || function() {}; // Clear earlier results and options _this.result = {}; _this.options = {}; _this.sandbox = vm.createContext(); // Defaulting the options _this.options = _.extend(_.clone(DEFAULT_OPTIONS), options); if(_this.options.dropCollections === true && _this.options.dropDatabase === true) { // Only one of the two flags can be turned on. If both are true, this means the // user set the dropCollections itself and this should have higher priority then // the default values. _this.options.dropDatabase = false; } if(_this.options.dropDatabase === true) { // Make sure to drop the database first mongoose.connection.db.dropDatabase(function(err) { if(err) { // Stop seeding if an error occurred return done(err); } // Start seeding when the database is dropped _this._seed(_.cloneDeep(data), done); }); } else { // Do not drop the entire database, start seeding _this._seed(_.cloneDeep(data), done); } /** * This method will be invoked when the seeding is completed or when something * went wrong. This method will then call the callback and rejects or resolves * the promise object. This way, users of the library can use both. * * @param {*} err [description] * @param {Object} result [description] */ function done(err, result) { if(err) { def.reject(err); callback(err); return; } def.resolve(result); callback(undefined, result); } // Return the promise return def.promise; }
[ "function", "(", "data", ",", "options", ",", "callback", ")", "{", "if", "(", "_", ".", "isFunction", "(", "options", ")", ")", "{", "callback", "=", "options", ";", "options", "=", "{", "}", ";", "}", "var", "def", "=", "Q", ".", "defer", "(", ")", ";", "callback", "=", "callback", "||", "function", "(", ")", "{", "}", ";", "_this", ".", "result", "=", "{", "}", ";", "_this", ".", "options", "=", "{", "}", ";", "_this", ".", "sandbox", "=", "vm", ".", "createContext", "(", ")", ";", "_this", ".", "options", "=", "_", ".", "extend", "(", "_", ".", "clone", "(", "DEFAULT_OPTIONS", ")", ",", "options", ")", ";", "if", "(", "_this", ".", "options", ".", "dropCollections", "===", "true", "&&", "_this", ".", "options", ".", "dropDatabase", "===", "true", ")", "{", "_this", ".", "options", ".", "dropDatabase", "=", "false", ";", "}", "if", "(", "_this", ".", "options", ".", "dropDatabase", "===", "true", ")", "{", "mongoose", ".", "connection", ".", "db", ".", "dropDatabase", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", ";", "}", "_this", ".", "_seed", "(", "_", ".", "cloneDeep", "(", "data", ")", ",", "done", ")", ";", "}", ")", ";", "}", "else", "{", "_this", ".", "_seed", "(", "_", ".", "cloneDeep", "(", "data", ")", ",", "done", ")", ";", "}", "function", "done", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "def", ".", "reject", "(", "err", ")", ";", "callback", "(", "err", ")", ";", "return", ";", "}", "def", ".", "resolve", "(", "result", ")", ";", "callback", "(", "undefined", ",", "result", ")", ";", "}", "return", "def", ".", "promise", ";", "}" ]
Start seeding the database. @param {Object} data The data object that should be inserted in the database. @param {Object} options The options object to provide extras. @param {Function} callback The method that should be called when the seeding is done.
[ "Start", "seeding", "the", "database", "." ]
ea08d510228a76e5eafa08e1f94cbe8cf0a6614d
https://github.com/SamVerschueren/mongoose-seeder/blob/ea08d510228a76e5eafa08e1f94cbe8cf0a6614d/index.js#L225-L291
train
SamVerschueren/mongoose-seeder
index.js
done
function done(err, result) { if(err) { def.reject(err); callback(err); return; } def.resolve(result); callback(undefined, result); }
javascript
function done(err, result) { if(err) { def.reject(err); callback(err); return; } def.resolve(result); callback(undefined, result); }
[ "function", "done", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "{", "def", ".", "reject", "(", "err", ")", ";", "callback", "(", "err", ")", ";", "return", ";", "}", "def", ".", "resolve", "(", "result", ")", ";", "callback", "(", "undefined", ",", "result", ")", ";", "}" ]
This method will be invoked when the seeding is completed or when something went wrong. This method will then call the callback and rejects or resolves the promise object. This way, users of the library can use both. @param {*} err [description] @param {Object} result [description]
[ "This", "method", "will", "be", "invoked", "when", "the", "seeding", "is", "completed", "or", "when", "something", "went", "wrong", ".", "This", "method", "will", "then", "call", "the", "callback", "and", "rejects", "or", "resolves", "the", "promise", "object", ".", "This", "way", "users", "of", "the", "library", "can", "use", "both", "." ]
ea08d510228a76e5eafa08e1f94cbe8cf0a6614d
https://github.com/SamVerschueren/mongoose-seeder/blob/ea08d510228a76e5eafa08e1f94cbe8cf0a6614d/index.js#L278-L287
train
github/webpack-config-github
webpack.config.js
proxyConfig
function proxyConfig(path) { const config = {} const {endpointsExtension} = tryGetGraphQLProjectConfig() if (endpointsExtension) { const graphqlEndpoint = endpointsExtension.getEndpoint() const {url: target, headers} = graphqlEndpoint const changeOrigin = true const pathRewrite = {} pathRewrite[`^${path}`] = '' config[path] = {changeOrigin, headers, pathRewrite, target} } return config }
javascript
function proxyConfig(path) { const config = {} const {endpointsExtension} = tryGetGraphQLProjectConfig() if (endpointsExtension) { const graphqlEndpoint = endpointsExtension.getEndpoint() const {url: target, headers} = graphqlEndpoint const changeOrigin = true const pathRewrite = {} pathRewrite[`^${path}`] = '' config[path] = {changeOrigin, headers, pathRewrite, target} } return config }
[ "function", "proxyConfig", "(", "path", ")", "{", "const", "config", "=", "{", "}", "const", "{", "endpointsExtension", "}", "=", "tryGetGraphQLProjectConfig", "(", ")", "if", "(", "endpointsExtension", ")", "{", "const", "graphqlEndpoint", "=", "endpointsExtension", ".", "getEndpoint", "(", ")", "const", "{", "url", ":", "target", ",", "headers", "}", "=", "graphqlEndpoint", "const", "changeOrigin", "=", "true", "const", "pathRewrite", "=", "{", "}", "pathRewrite", "[", "`", "${", "path", "}", "`", "]", "=", "''", "config", "[", "path", "]", "=", "{", "changeOrigin", ",", "headers", ",", "pathRewrite", ",", "target", "}", "}", "return", "config", "}" ]
Get webpack proxy configuration as per .graphqlconfig.
[ "Get", "webpack", "proxy", "configuration", "as", "per", ".", "graphqlconfig", "." ]
cd56f9465db31ef6c0c2c07077ee2c3d25f97554
https://github.com/github/webpack-config-github/blob/cd56f9465db31ef6c0c2c07077ee2c3d25f97554/webpack.config.js#L315-L332
train
assemble/buttons
templates/helpers/helper-prettify.js
function(source, options) { try { return prettify(source, options); } catch (e) { console.error(e); console.warn('HTML beautification failed.'); } }
javascript
function(source, options) { try { return prettify(source, options); } catch (e) { console.error(e); console.warn('HTML beautification failed.'); } }
[ "function", "(", "source", ",", "options", ")", "{", "try", "{", "return", "prettify", "(", "source", ",", "options", ")", ";", "}", "catch", "(", "e", ")", "{", "console", ".", "error", "(", "e", ")", ";", "console", ".", "warn", "(", "'HTML beautification failed.'", ")", ";", "}", "}" ]
Format HTML with js-beautify, pass in options. @param {String} source [The un-prettified HTML.] @param {Object} options [Object of options passed to js-beautify.] @returns {String} [Stunning HTML.]
[ "Format", "HTML", "with", "js", "-", "beautify", "pass", "in", "options", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/templates/helpers/helper-prettify.js#L56-L63
train
assemble/buttons
_demo/assets/js/list-scroll.js
refresh
function refresh() { if( active ) { requestAnimFrame( refresh ); for( var i = 0, len = lists.length; i < len; i++ ) { lists[i].update(); } } }
javascript
function refresh() { if( active ) { requestAnimFrame( refresh ); for( var i = 0, len = lists.length; i < len; i++ ) { lists[i].update(); } } }
[ "function", "refresh", "(", ")", "{", "if", "(", "active", ")", "{", "requestAnimFrame", "(", "refresh", ")", ";", "for", "(", "var", "i", "=", "0", ",", "len", "=", "lists", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "lists", "[", "i", "]", ".", "update", "(", ")", ";", "}", "}", "}" ]
Updates all currently bound lists.
[ "Updates", "all", "currently", "bound", "lists", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/_demo/assets/js/list-scroll.js#L27-L35
train
assemble/buttons
_demo/assets/js/list-scroll.js
add
function add( element, options ) { // Only allow ul/ol if( !element.nodeName || /^(ul|li)$/i.test( element.nodeName ) === false ) { return false; } // Delete duplicates (but continue and re-bind this list to get the // latest properties and list items) else if( contains( element ) ) { remove( element ); } var list = IS_TOUCH_DEVICE ? new TouchList( element ) : new List( element ); // Handle options if( options && options.live ) { list.syncInterval = setInterval( function() { list.sync.call( list ); }, LIVE_INTERVAL ); } // Synchronize the list with the DOM list.sync(); // Add this element to the collection lists.push( list ); // Start refreshing if this was the first list to be added if( lists.length === 1 ) { active = true; refresh(); } }
javascript
function add( element, options ) { // Only allow ul/ol if( !element.nodeName || /^(ul|li)$/i.test( element.nodeName ) === false ) { return false; } // Delete duplicates (but continue and re-bind this list to get the // latest properties and list items) else if( contains( element ) ) { remove( element ); } var list = IS_TOUCH_DEVICE ? new TouchList( element ) : new List( element ); // Handle options if( options && options.live ) { list.syncInterval = setInterval( function() { list.sync.call( list ); }, LIVE_INTERVAL ); } // Synchronize the list with the DOM list.sync(); // Add this element to the collection lists.push( list ); // Start refreshing if this was the first list to be added if( lists.length === 1 ) { active = true; refresh(); } }
[ "function", "add", "(", "element", ",", "options", ")", "{", "if", "(", "!", "element", ".", "nodeName", "||", "/", "^(ul|li)$", "/", "i", ".", "test", "(", "element", ".", "nodeName", ")", "===", "false", ")", "{", "return", "false", ";", "}", "else", "if", "(", "contains", "(", "element", ")", ")", "{", "remove", "(", "element", ")", ";", "}", "var", "list", "=", "IS_TOUCH_DEVICE", "?", "new", "TouchList", "(", "element", ")", ":", "new", "List", "(", "element", ")", ";", "if", "(", "options", "&&", "options", ".", "live", ")", "{", "list", ".", "syncInterval", "=", "setInterval", "(", "function", "(", ")", "{", "list", ".", "sync", ".", "call", "(", "list", ")", ";", "}", ",", "LIVE_INTERVAL", ")", ";", "}", "list", ".", "sync", "(", ")", ";", "lists", ".", "push", "(", "list", ")", ";", "if", "(", "lists", ".", "length", "===", "1", ")", "{", "active", "=", "true", ";", "refresh", "(", ")", ";", "}", "}" ]
Starts monitoring a list and applies classes to each of its contained elements based on its position relative to the list's viewport. @param {HTMLElement} element @param {Object} options Additional arguments; - live; Flags if the DOM should be repeatedly checked for changes repeatedly. Useful if the list contents is changing. Use scarcely as it has an impact on performance.
[ "Starts", "monitoring", "a", "list", "and", "applies", "classes", "to", "each", "of", "its", "contained", "elements", "based", "on", "its", "position", "relative", "to", "the", "list", "s", "viewport", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/_demo/assets/js/list-scroll.js#L48-L79
train
assemble/buttons
_demo/assets/js/list-scroll.js
remove
function remove( element ) { for( var i = 0; i < lists.length; i++ ) { var list = lists[i]; if( list.element == element ) { list.destroy(); lists.splice( i, 1 ); i--; } } // Stopped refreshing if the last list was removed if( lists.length === 0 ) { active = false; } }
javascript
function remove( element ) { for( var i = 0; i < lists.length; i++ ) { var list = lists[i]; if( list.element == element ) { list.destroy(); lists.splice( i, 1 ); i--; } } // Stopped refreshing if the last list was removed if( lists.length === 0 ) { active = false; } }
[ "function", "remove", "(", "element", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "lists", ".", "length", ";", "i", "++", ")", "{", "var", "list", "=", "lists", "[", "i", "]", ";", "if", "(", "list", ".", "element", "==", "element", ")", "{", "list", ".", "destroy", "(", ")", ";", "lists", ".", "splice", "(", "i", ",", "1", ")", ";", "i", "--", ";", "}", "}", "if", "(", "lists", ".", "length", "===", "0", ")", "{", "active", "=", "false", ";", "}", "}" ]
Stops monitoring a list element and removes any classes that were applied to its list items. @param {HTMLElement} element
[ "Stops", "monitoring", "a", "list", "element", "and", "removes", "any", "classes", "that", "were", "applied", "to", "its", "list", "items", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/_demo/assets/js/list-scroll.js#L87-L102
train
assemble/buttons
_demo/assets/js/list-scroll.js
contains
function contains( element ) { for( var i = 0, len = lists.length; i < len; i++ ) { if( lists[i].element == element ) { return true; } } return false; }
javascript
function contains( element ) { for( var i = 0, len = lists.length; i < len; i++ ) { if( lists[i].element == element ) { return true; } } return false; }
[ "function", "contains", "(", "element", ")", "{", "for", "(", "var", "i", "=", "0", ",", "len", "=", "lists", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "lists", "[", "i", "]", ".", "element", "==", "element", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Checks if the specified element has already been bound.
[ "Checks", "if", "the", "specified", "element", "has", "already", "been", "bound", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/_demo/assets/js/list-scroll.js#L107-L114
train
assemble/buttons
_demo/assets/js/list-scroll.js
batch
function batch( target, method, options ) { var i, len; // Selector if( typeof target === 'string' ) { var targets = document.querySelectorAll( target ); for( i = 0, len = targets.length; i < len; i++ ) { method.call( null, targets[i], options ); } } // Array (jQuery) else if( typeof target === 'object' && typeof target.length === 'number' ) { for( i = 0, len = target.length; i < len; i++ ) { method.call( null, target[i], options ); } } // Single element else if( target.nodeName ) { method.call( null, target, options ); } else { throw 'Stroll target was of unexpected type.'; } }
javascript
function batch( target, method, options ) { var i, len; // Selector if( typeof target === 'string' ) { var targets = document.querySelectorAll( target ); for( i = 0, len = targets.length; i < len; i++ ) { method.call( null, targets[i], options ); } } // Array (jQuery) else if( typeof target === 'object' && typeof target.length === 'number' ) { for( i = 0, len = target.length; i < len; i++ ) { method.call( null, target[i], options ); } } // Single element else if( target.nodeName ) { method.call( null, target, options ); } else { throw 'Stroll target was of unexpected type.'; } }
[ "function", "batch", "(", "target", ",", "method", ",", "options", ")", "{", "var", "i", ",", "len", ";", "if", "(", "typeof", "target", "===", "'string'", ")", "{", "var", "targets", "=", "document", ".", "querySelectorAll", "(", "target", ")", ";", "for", "(", "i", "=", "0", ",", "len", "=", "targets", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "method", ".", "call", "(", "null", ",", "targets", "[", "i", "]", ",", "options", ")", ";", "}", "}", "else", "if", "(", "typeof", "target", "===", "'object'", "&&", "typeof", "target", ".", "length", "===", "'number'", ")", "{", "for", "(", "i", "=", "0", ",", "len", "=", "target", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "method", ".", "call", "(", "null", ",", "target", "[", "i", "]", ",", "options", ")", ";", "}", "}", "else", "if", "(", "target", ".", "nodeName", ")", "{", "method", ".", "call", "(", "null", ",", "target", ",", "options", ")", ";", "}", "else", "{", "throw", "'Stroll target was of unexpected type.'", ";", "}", "}" ]
Calls 'method' for each DOM element discovered in 'target'. @param target String selector / array of UL elements / jQuery object / single UL element @param method A function to call for each element target
[ "Calls", "method", "for", "each", "DOM", "element", "discovered", "in", "target", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/_demo/assets/js/list-scroll.js#L124-L148
train
assemble/buttons
_demo/assets/js/list-scroll.js
TouchList
function TouchList( element ) { this.element = element; this.element.style.overflow = 'hidden'; this.top = { value: 0, natural: 0 }; this.touch = { value: 0, offset: 0, start: 0, previous: 0, lastMove: Date.now(), accellerateTimeout: -1, isAccellerating: false, isActive: false }; this.velocity = 0; }
javascript
function TouchList( element ) { this.element = element; this.element.style.overflow = 'hidden'; this.top = { value: 0, natural: 0 }; this.touch = { value: 0, offset: 0, start: 0, previous: 0, lastMove: Date.now(), accellerateTimeout: -1, isAccellerating: false, isActive: false }; this.velocity = 0; }
[ "function", "TouchList", "(", "element", ")", "{", "this", ".", "element", "=", "element", ";", "this", ".", "element", ".", "style", ".", "overflow", "=", "'hidden'", ";", "this", ".", "top", "=", "{", "value", ":", "0", ",", "natural", ":", "0", "}", ";", "this", ".", "touch", "=", "{", "value", ":", "0", ",", "offset", ":", "0", ",", "start", ":", "0", ",", "previous", ":", "0", ",", "lastMove", ":", "Date", ".", "now", "(", ")", ",", "accellerateTimeout", ":", "-", "1", ",", "isAccellerating", ":", "false", ",", "isActive", ":", "false", "}", ";", "this", ".", "velocity", "=", "0", ";", "}" ]
A list specifically for touch devices. Simulates the style of scrolling you'd see on a touch device but does not rely on webkit-overflow-scrolling since that makes it impossible to read the up-to-date scroll position.
[ "A", "list", "specifically", "for", "touch", "devices", ".", "Simulates", "the", "style", "of", "scrolling", "you", "d", "see", "on", "a", "touch", "device", "but", "does", "not", "rely", "on", "webkit", "-", "overflow", "-", "scrolling", "since", "that", "makes", "it", "impossible", "to", "read", "the", "up", "-", "to", "-", "date", "scroll", "position", "." ]
7b02517713aa316ae7e9d7c23b46a66cde6c7834
https://github.com/assemble/buttons/blob/7b02517713aa316ae7e9d7c23b46a66cde6c7834/_demo/assets/js/list-scroll.js#L252-L273
train
calmh/yardstick
bin/yardstick.js
displayMetrics
function displayMetrics(file) { var prefix = ''; var code = fs.readFileSync(file, 'utf-8'); // We remove any shebang at the start of the file since that isn't valid // Javascript and will trip up the parser. code = code.replace(/^#!.*\n/, ''); var metrics = complexity(code); // Walk the metrics structure and add each member to the table rows. function walk(data, name) { // Fade out anonymous functions. if (name.indexOf('anon@') === 0) { name = name.grey; } rows.push([ prefix + name, data.ecc, data.arity, data.codeLines, data.commentLines, Math.round(100 * data.commentLines / data.codeLines) ]); // Add two spaces to the prefix before the next depth, to illustrate // the hierarchy in the table. prefix += ' '; _.each(data.children, walk); prefix = prefix.slice(0,prefix.length-2); } walk(metrics, path.basename(file).blue.bold); }
javascript
function displayMetrics(file) { var prefix = ''; var code = fs.readFileSync(file, 'utf-8'); // We remove any shebang at the start of the file since that isn't valid // Javascript and will trip up the parser. code = code.replace(/^#!.*\n/, ''); var metrics = complexity(code); // Walk the metrics structure and add each member to the table rows. function walk(data, name) { // Fade out anonymous functions. if (name.indexOf('anon@') === 0) { name = name.grey; } rows.push([ prefix + name, data.ecc, data.arity, data.codeLines, data.commentLines, Math.round(100 * data.commentLines / data.codeLines) ]); // Add two spaces to the prefix before the next depth, to illustrate // the hierarchy in the table. prefix += ' '; _.each(data.children, walk); prefix = prefix.slice(0,prefix.length-2); } walk(metrics, path.basename(file).blue.bold); }
[ "function", "displayMetrics", "(", "file", ")", "{", "var", "prefix", "=", "''", ";", "var", "code", "=", "fs", ".", "readFileSync", "(", "file", ",", "'utf-8'", ")", ";", "code", "=", "code", ".", "replace", "(", "/", "^#!.*\\n", "/", ",", "''", ")", ";", "var", "metrics", "=", "complexity", "(", "code", ")", ";", "function", "walk", "(", "data", ",", "name", ")", "{", "if", "(", "name", ".", "indexOf", "(", "'anon@'", ")", "===", "0", ")", "{", "name", "=", "name", ".", "grey", ";", "}", "rows", ".", "push", "(", "[", "prefix", "+", "name", ",", "data", ".", "ecc", ",", "data", ".", "arity", ",", "data", ".", "codeLines", ",", "data", ".", "commentLines", ",", "Math", ".", "round", "(", "100", "*", "data", ".", "commentLines", "/", "data", ".", "codeLines", ")", "]", ")", ";", "prefix", "+=", "' '", ";", "_", ".", "each", "(", "data", ".", "children", ",", "walk", ")", ";", "prefix", "=", "prefix", ".", "slice", "(", "0", ",", "prefix", ".", "length", "-", "2", ")", ";", "}", "walk", "(", "metrics", ",", "path", ".", "basename", "(", "file", ")", ".", "blue", ".", "bold", ")", ";", "}" ]
Analyze a file and add it's metrics to the table.
[ "Analyze", "a", "file", "and", "add", "it", "s", "metrics", "to", "the", "table", "." ]
3d3a8c94532c523a3b8b935bacb1fa444dcd8b3c
https://github.com/calmh/yardstick/blob/3d3a8c94532c523a3b8b935bacb1fa444dcd8b3c/bin/yardstick.js#L22-L53
train
calmh/yardstick
bin/yardstick.js
walk
function walk(data, name) { // Fade out anonymous functions. if (name.indexOf('anon@') === 0) { name = name.grey; } rows.push([ prefix + name, data.ecc, data.arity, data.codeLines, data.commentLines, Math.round(100 * data.commentLines / data.codeLines) ]); // Add two spaces to the prefix before the next depth, to illustrate // the hierarchy in the table. prefix += ' '; _.each(data.children, walk); prefix = prefix.slice(0,prefix.length-2); }
javascript
function walk(data, name) { // Fade out anonymous functions. if (name.indexOf('anon@') === 0) { name = name.grey; } rows.push([ prefix + name, data.ecc, data.arity, data.codeLines, data.commentLines, Math.round(100 * data.commentLines / data.codeLines) ]); // Add two spaces to the prefix before the next depth, to illustrate // the hierarchy in the table. prefix += ' '; _.each(data.children, walk); prefix = prefix.slice(0,prefix.length-2); }
[ "function", "walk", "(", "data", ",", "name", ")", "{", "if", "(", "name", ".", "indexOf", "(", "'anon@'", ")", "===", "0", ")", "{", "name", "=", "name", ".", "grey", ";", "}", "rows", ".", "push", "(", "[", "prefix", "+", "name", ",", "data", ".", "ecc", ",", "data", ".", "arity", ",", "data", ".", "codeLines", ",", "data", ".", "commentLines", ",", "Math", ".", "round", "(", "100", "*", "data", ".", "commentLines", "/", "data", ".", "codeLines", ")", "]", ")", ";", "prefix", "+=", "' '", ";", "_", ".", "each", "(", "data", ".", "children", ",", "walk", ")", ";", "prefix", "=", "prefix", ".", "slice", "(", "0", ",", "prefix", ".", "length", "-", "2", ")", ";", "}" ]
Walk the metrics structure and add each member to the table rows.
[ "Walk", "the", "metrics", "structure", "and", "add", "each", "member", "to", "the", "table", "rows", "." ]
3d3a8c94532c523a3b8b935bacb1fa444dcd8b3c
https://github.com/calmh/yardstick/blob/3d3a8c94532c523a3b8b935bacb1fa444dcd8b3c/bin/yardstick.js#L36-L51
train
homerjam/angular-scroll-magic
bower_components/gsap/src/uncompressed/TweenMax.js
function(v) { var t = this.t, //refers to the element's style property filters = t.filter || _getStyle(this.data, "filter") || "", val = (this.s + this.c * v) | 0, skip; if (val === 100) { //for older versions of IE that need to use a filter to apply opacity, we should remove the filter if opacity hits 1 in order to improve performance, but make sure there isn't a transform (matrix) or gradient in the filters. if (filters.indexOf("atrix(") === -1 && filters.indexOf("radient(") === -1 && filters.indexOf("oader(") === -1) { t.removeAttribute("filter"); skip = (!_getStyle(this.data, "filter")); //if a class is applied that has an alpha filter, it will take effect (we don't want that), so re-apply our alpha filter in that case. We must first remove it and then check. } else { t.filter = filters.replace(_alphaFilterExp, ""); skip = true; } } if (!skip) { if (this.xn1) { t.filter = filters = filters || ("alpha(opacity=" + val + ")"); //works around bug in IE7/8 that prevents changes to "visibility" from being applied properly if the filter is changed to a different alpha on the same frame. } if (filters.indexOf("pacity") === -1) { //only used if browser doesn't support the standard opacity style property (IE 7 and 8). We omit the "O" to avoid case-sensitivity issues if (val !== 0 || !this.xn1) { //bugs in IE7/8 won't render the filter properly if opacity is ADDED on the same frame/render as "visibility" changes (this.xn1 is 1 if this tween is an "autoAlpha" tween) t.filter = filters + " alpha(opacity=" + val + ")"; //we round the value because otherwise, bugs in IE7/8 can prevent "visibility" changes from being applied properly. } } else { t.filter = filters.replace(_opacityExp, "opacity=" + val); } } }
javascript
function(v) { var t = this.t, //refers to the element's style property filters = t.filter || _getStyle(this.data, "filter") || "", val = (this.s + this.c * v) | 0, skip; if (val === 100) { //for older versions of IE that need to use a filter to apply opacity, we should remove the filter if opacity hits 1 in order to improve performance, but make sure there isn't a transform (matrix) or gradient in the filters. if (filters.indexOf("atrix(") === -1 && filters.indexOf("radient(") === -1 && filters.indexOf("oader(") === -1) { t.removeAttribute("filter"); skip = (!_getStyle(this.data, "filter")); //if a class is applied that has an alpha filter, it will take effect (we don't want that), so re-apply our alpha filter in that case. We must first remove it and then check. } else { t.filter = filters.replace(_alphaFilterExp, ""); skip = true; } } if (!skip) { if (this.xn1) { t.filter = filters = filters || ("alpha(opacity=" + val + ")"); //works around bug in IE7/8 that prevents changes to "visibility" from being applied properly if the filter is changed to a different alpha on the same frame. } if (filters.indexOf("pacity") === -1) { //only used if browser doesn't support the standard opacity style property (IE 7 and 8). We omit the "O" to avoid case-sensitivity issues if (val !== 0 || !this.xn1) { //bugs in IE7/8 won't render the filter properly if opacity is ADDED on the same frame/render as "visibility" changes (this.xn1 is 1 if this tween is an "autoAlpha" tween) t.filter = filters + " alpha(opacity=" + val + ")"; //we round the value because otherwise, bugs in IE7/8 can prevent "visibility" changes from being applied properly. } } else { t.filter = filters.replace(_opacityExp, "opacity=" + val); } } }
[ "function", "(", "v", ")", "{", "var", "t", "=", "this", ".", "t", ",", "filters", "=", "t", ".", "filter", "||", "_getStyle", "(", "this", ".", "data", ",", "\"filter\"", ")", "||", "\"\"", ",", "val", "=", "(", "this", ".", "s", "+", "this", ".", "c", "*", "v", ")", "|", "0", ",", "skip", ";", "if", "(", "val", "===", "100", ")", "{", "if", "(", "filters", ".", "indexOf", "(", "\"atrix(\"", ")", "===", "-", "1", "&&", "filters", ".", "indexOf", "(", "\"radient(\"", ")", "===", "-", "1", "&&", "filters", ".", "indexOf", "(", "\"oader(\"", ")", "===", "-", "1", ")", "{", "t", ".", "removeAttribute", "(", "\"filter\"", ")", ";", "skip", "=", "(", "!", "_getStyle", "(", "this", ".", "data", ",", "\"filter\"", ")", ")", ";", "}", "else", "{", "t", ".", "filter", "=", "filters", ".", "replace", "(", "_alphaFilterExp", ",", "\"\"", ")", ";", "skip", "=", "true", ";", "}", "}", "if", "(", "!", "skip", ")", "{", "if", "(", "this", ".", "xn1", ")", "{", "t", ".", "filter", "=", "filters", "=", "filters", "||", "(", "\"alpha(opacity=\"", "+", "val", "+", "\")\"", ")", ";", "}", "if", "(", "filters", ".", "indexOf", "(", "\"pacity\"", ")", "===", "-", "1", ")", "{", "if", "(", "val", "!==", "0", "||", "!", "this", ".", "xn1", ")", "{", "t", ".", "filter", "=", "filters", "+", "\" alpha(opacity=\"", "+", "val", "+", "\")\"", ";", "}", "}", "else", "{", "t", ".", "filter", "=", "filters", ".", "replace", "(", "_opacityExp", ",", "\"opacity=\"", "+", "val", ")", ";", "}", "}", "}" ]
opacity-related
[ "opacity", "-", "related" ]
82b2a1d14497fa74d060be53b0e042f1c496351b
https://github.com/homerjam/angular-scroll-magic/blob/82b2a1d14497fa74d060be53b0e042f1c496351b/bower_components/gsap/src/uncompressed/TweenMax.js#L4488-L4514
train
hashchange/jquery.documentsize
dist/jquery.documentsize.js
isVisualViewport
function isVisualViewport ( name ) { var viewport = isString( name ) && name.toLowerCase(); if ( name && !viewport ) throw new Error( "Invalid viewport option: " + name ); if ( viewport && viewport !== "visual" && viewport !== "layout" ) throw new Error( "Invalid viewport name: " + name ); return viewport === "visual"; }
javascript
function isVisualViewport ( name ) { var viewport = isString( name ) && name.toLowerCase(); if ( name && !viewport ) throw new Error( "Invalid viewport option: " + name ); if ( viewport && viewport !== "visual" && viewport !== "layout" ) throw new Error( "Invalid viewport name: " + name ); return viewport === "visual"; }
[ "function", "isVisualViewport", "(", "name", ")", "{", "var", "viewport", "=", "isString", "(", "name", ")", "&&", "name", ".", "toLowerCase", "(", ")", ";", "if", "(", "name", "&&", "!", "viewport", ")", "throw", "new", "Error", "(", "\"Invalid viewport option: \"", "+", "name", ")", ";", "if", "(", "viewport", "&&", "viewport", "!==", "\"visual\"", "&&", "viewport", "!==", "\"layout\"", ")", "throw", "new", "Error", "(", "\"Invalid viewport name: \"", "+", "name", ")", ";", "return", "viewport", "===", "\"visual\"", ";", "}" ]
Checks if the argument is the name of the visual viewport. The check is case-insensitive. Expects a string. Tolerates falsy values, returning false then (argument is not naming the visual viewport). Throws an error for everything else. Also throws an error if the viewport name is a string but not recognized (typo alert). Helper for getWindowQueryConfig(). @param {string} [name] strings "visual", "layout" (case-insensitive) @returns {boolean}
[ "Checks", "if", "the", "argument", "is", "the", "name", "of", "the", "visual", "viewport", ".", "The", "check", "is", "case", "-", "insensitive", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/dist/jquery.documentsize.js#L340-L347
train
hashchange/jquery.documentsize
dist/jquery.documentsize.js
restoreGlobalDocument
function restoreGlobalDocument ( previousState ) { if ( previousState.documentElement.modified ) document.documentElement.style.overflowX = previousState.documentElement.styleOverflowX; if ( previousState.body.modified ) document.body.style.overflowX = previousState.body.styleOverflowX; }
javascript
function restoreGlobalDocument ( previousState ) { if ( previousState.documentElement.modified ) document.documentElement.style.overflowX = previousState.documentElement.styleOverflowX; if ( previousState.body.modified ) document.body.style.overflowX = previousState.body.styleOverflowX; }
[ "function", "restoreGlobalDocument", "(", "previousState", ")", "{", "if", "(", "previousState", ".", "documentElement", ".", "modified", ")", "document", ".", "documentElement", ".", "style", ".", "overflowX", "=", "previousState", ".", "documentElement", ".", "styleOverflowX", ";", "if", "(", "previousState", ".", "body", ".", "modified", ")", "document", ".", "body", ".", "style", ".", "overflowX", "=", "previousState", ".", "body", ".", "styleOverflowX", ";", "}" ]
Restores the body and documentElement styles to their initial state, which is passed in as an argument. Works with the global document. Used only if iframe creation or access has failed for some reason. @param {Object} previousState the initial state, as returned by prepareGlobalDocument()
[ "Restores", "the", "body", "and", "documentElement", "styles", "to", "their", "initial", "state", "which", "is", "passed", "in", "as", "an", "argument", ".", "Works", "with", "the", "global", "document", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/dist/jquery.documentsize.js#L560-L565
train
hashchange/jquery.documentsize
dist/jquery.documentsize.js
guessDocumentSize
function guessDocumentSize( dimension, _document ) { var ddE = _document.documentElement; return Math.max( ddE.body[ "scroll" + dimension ], _document[ "scroll" + dimension ], ddE.body[ "offset" + dimension ], _document[ "offset" + dimension ], _document[ "client" + dimension ] ); }
javascript
function guessDocumentSize( dimension, _document ) { var ddE = _document.documentElement; return Math.max( ddE.body[ "scroll" + dimension ], _document[ "scroll" + dimension ], ddE.body[ "offset" + dimension ], _document[ "offset" + dimension ], _document[ "client" + dimension ] ); }
[ "function", "guessDocumentSize", "(", "dimension", ",", "_document", ")", "{", "var", "ddE", "=", "_document", ".", "documentElement", ";", "return", "Math", ".", "max", "(", "ddE", ".", "body", "[", "\"scroll\"", "+", "dimension", "]", ",", "_document", "[", "\"scroll\"", "+", "dimension", "]", ",", "ddE", ".", "body", "[", "\"offset\"", "+", "dimension", "]", ",", "_document", "[", "\"offset\"", "+", "dimension", "]", ",", "_document", "[", "\"client\"", "+", "dimension", "]", ")", ";", "}" ]
Returns a best guess for the window width or height. Used as a fallback for unsupported browsers which are too broken to even run the feature test. The conventional jQuery method of guessing the document size is used here: every conceivable value is queried and the largest one is picked. @param {string} dimension accepted values are "Width" or "Height" (capitalized first letter!) @param {Document} [_document]
[ "Returns", "a", "best", "guess", "for", "the", "window", "width", "or", "height", ".", "Used", "as", "a", "fallback", "for", "unsupported", "browsers", "which", "are", "too", "broken", "to", "even", "run", "the", "feature", "test", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/dist/jquery.documentsize.js#L577-L585
train
hashchange/jquery.documentsize
dist/jquery.documentsize.js
getWindowInnerSize
function getWindowInnerSize ( dimension, _window ) { var size = ( _window || window ).visualViewport ? ( _window || window ).visualViewport[ dimension.toLowerCase() ] : ( _window || window )[ "inner" + dimension]; // Check for fractions. Exclude undefined return values in browsers which don't support window.innerWidth/Height. if ( size ) checkForFractions( size ); return size; }
javascript
function getWindowInnerSize ( dimension, _window ) { var size = ( _window || window ).visualViewport ? ( _window || window ).visualViewport[ dimension.toLowerCase() ] : ( _window || window )[ "inner" + dimension]; // Check for fractions. Exclude undefined return values in browsers which don't support window.innerWidth/Height. if ( size ) checkForFractions( size ); return size; }
[ "function", "getWindowInnerSize", "(", "dimension", ",", "_window", ")", "{", "var", "size", "=", "(", "_window", "||", "window", ")", ".", "visualViewport", "?", "(", "_window", "||", "window", ")", ".", "visualViewport", "[", "dimension", ".", "toLowerCase", "(", ")", "]", ":", "(", "_window", "||", "window", ")", "[", "\"inner\"", "+", "dimension", "]", ";", "if", "(", "size", ")", "checkForFractions", "(", "size", ")", ";", "return", "size", ";", "}" ]
Returns window.visualViewport.width if available, or window.innerWidth otherwise, for width. Likewise, it returns window.visualViewport.height or window.innerHeight for height. The dimension argument determines whether width or height is returned. Along the way, the return value is examined to see if the browser supports sub-pixel accuracy (floating-point values). If the visualViewport API is available, it is preferred over window.innerWidth/Height. That's because Chrome, from version 62, has changed the behaviour of window.innerWidth/Height, which used to return the size of the visual viewport. In Chrome, it now returns the size of the layout viewport, breaking compatibility with all other browsers and its own past behaviour. Other browsers may follow suit, though. See - https://www.quirksmode.org/blog/archives/2017/09/chrome_breaks_v.html - https://developers.google.com/web/updates/2017/09/visual-viewport-api - https://bugs.chromium.org/p/chromium/issues/detail?id=767388#c8 @param {string} dimension must be "Width" or "Height" (upper case!) @param {Window} [_window=window] @returns {number}
[ "Returns", "window", ".", "visualViewport", ".", "width", "if", "available", "or", "window", ".", "innerWidth", "otherwise", "for", "width", ".", "Likewise", "it", "returns", "window", ".", "visualViewport", ".", "height", "or", "window", ".", "innerHeight", "for", "height", ".", "The", "dimension", "argument", "determines", "whether", "width", "or", "height", "is", "returned", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/dist/jquery.documentsize.js#L634-L642
train
hashchange/jquery.documentsize
dist/jquery.documentsize.js
getIEVersion
function getIEVersion () { var userAgent, userAgentTestRx; if ( ieVersion === undefined ) { ieVersion = false; userAgent = navigator && navigator.userAgent; if ( navigator && navigator.appName === "Microsoft Internet Explorer" && userAgent ) { userAgentTestRx = new RegExp( "MSIE ([0-9]{1,}[\.0-9]{0,})" ); // jshint ignore:line if ( userAgentTestRx.exec( userAgent ) != null ) ieVersion = parseFloat( RegExp.$1 ); } } return ieVersion; }
javascript
function getIEVersion () { var userAgent, userAgentTestRx; if ( ieVersion === undefined ) { ieVersion = false; userAgent = navigator && navigator.userAgent; if ( navigator && navigator.appName === "Microsoft Internet Explorer" && userAgent ) { userAgentTestRx = new RegExp( "MSIE ([0-9]{1,}[\.0-9]{0,})" ); // jshint ignore:line if ( userAgentTestRx.exec( userAgent ) != null ) ieVersion = parseFloat( RegExp.$1 ); } } return ieVersion; }
[ "function", "getIEVersion", "(", ")", "{", "var", "userAgent", ",", "userAgentTestRx", ";", "if", "(", "ieVersion", "===", "undefined", ")", "{", "ieVersion", "=", "false", ";", "userAgent", "=", "navigator", "&&", "navigator", ".", "userAgent", ";", "if", "(", "navigator", "&&", "navigator", ".", "appName", "===", "\"Microsoft Internet Explorer\"", "&&", "userAgent", ")", "{", "userAgentTestRx", "=", "new", "RegExp", "(", "\"MSIE ([0-9]{1,}[\\.0-9]{0,})\"", ")", ";", "\\.", "}", "}", "if", "(", "userAgentTestRx", ".", "exec", "(", "userAgent", ")", "!=", "null", ")", "ieVersion", "=", "parseFloat", "(", "RegExp", ".", "$1", ")", ";", "}" ]
Returns the IE version, or false if the browser is not IE. The result is determined by browser sniffing, rather than a test tailored to the use case. The function must only be called as a last resort, for scenarios where there is no alternative to browser sniffing. These scenarios include: - Preventing IE6 and IE7 from crashing - Preventing IE9 from blocking or delaying the load event The test follows the MSDN recommendation at https://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx#parsingua The result is cached. @returns {number|boolean}
[ "Returns", "the", "IE", "version", "or", "false", "if", "the", "browser", "is", "not", "IE", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/dist/jquery.documentsize.js#L739-L755
train
hashchange/jquery.documentsize
demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js
function() { this.$container = $(this.options.buttonContainer); this.$container.on('show.bs.dropdown', this.options.onDropdownShow); this.$container.on('hide.bs.dropdown', this.options.onDropdownHide); this.$container.on('shown.bs.dropdown', this.options.onDropdownShown); this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden); }
javascript
function() { this.$container = $(this.options.buttonContainer); this.$container.on('show.bs.dropdown', this.options.onDropdownShow); this.$container.on('hide.bs.dropdown', this.options.onDropdownHide); this.$container.on('shown.bs.dropdown', this.options.onDropdownShown); this.$container.on('hidden.bs.dropdown', this.options.onDropdownHidden); }
[ "function", "(", ")", "{", "this", ".", "$container", "=", "$", "(", "this", ".", "options", ".", "buttonContainer", ")", ";", "this", ".", "$container", ".", "on", "(", "'show.bs.dropdown'", ",", "this", ".", "options", ".", "onDropdownShow", ")", ";", "this", ".", "$container", ".", "on", "(", "'hide.bs.dropdown'", ",", "this", ".", "options", ".", "onDropdownHide", ")", ";", "this", ".", "$container", ".", "on", "(", "'shown.bs.dropdown'", ",", "this", ".", "options", ".", "onDropdownShown", ")", ";", "this", ".", "$container", ".", "on", "(", "'hidden.bs.dropdown'", ",", "this", ".", "options", ".", "onDropdownHidden", ")", ";", "}" ]
Builds the container of the multiselect.
[ "Builds", "the", "container", "of", "the", "multiselect", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js#L351-L357
train
hashchange/jquery.documentsize
demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js
function() { if (typeof this.options.selectAllValue === 'number') { this.options.selectAllValue = this.options.selectAllValue.toString(); } var alreadyHasSelectAll = this.hasSelectAll(); if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) { // Check whether to add a divider after the select all. if (this.options.includeSelectAllDivider) { this.$ul.prepend($(this.options.templates.divider)); } var $li = $(this.options.templates.li); $('label', $li).addClass("checkbox"); if (this.options.enableHTML) { $('label', $li).html(" " + this.options.selectAllText); } else { $('label', $li).text(" " + this.options.selectAllText); } if (this.options.selectAllName) { $('label', $li).prepend('<input type="checkbox" name="' + this.options.selectAllName + '" />'); } else { $('label', $li).prepend('<input type="checkbox" />'); } var $checkbox = $('input', $li); $checkbox.val(this.options.selectAllValue); $li.addClass("multiselect-item multiselect-all"); $checkbox.parent().parent() .addClass('multiselect-all'); this.$ul.prepend($li); $checkbox.prop('checked', false); } }
javascript
function() { if (typeof this.options.selectAllValue === 'number') { this.options.selectAllValue = this.options.selectAllValue.toString(); } var alreadyHasSelectAll = this.hasSelectAll(); if (!alreadyHasSelectAll && this.options.includeSelectAllOption && this.options.multiple && $('option', this.$select).length > this.options.includeSelectAllIfMoreThan) { // Check whether to add a divider after the select all. if (this.options.includeSelectAllDivider) { this.$ul.prepend($(this.options.templates.divider)); } var $li = $(this.options.templates.li); $('label', $li).addClass("checkbox"); if (this.options.enableHTML) { $('label', $li).html(" " + this.options.selectAllText); } else { $('label', $li).text(" " + this.options.selectAllText); } if (this.options.selectAllName) { $('label', $li).prepend('<input type="checkbox" name="' + this.options.selectAllName + '" />'); } else { $('label', $li).prepend('<input type="checkbox" />'); } var $checkbox = $('input', $li); $checkbox.val(this.options.selectAllValue); $li.addClass("multiselect-item multiselect-all"); $checkbox.parent().parent() .addClass('multiselect-all'); this.$ul.prepend($li); $checkbox.prop('checked', false); } }
[ "function", "(", ")", "{", "if", "(", "typeof", "this", ".", "options", ".", "selectAllValue", "===", "'number'", ")", "{", "this", ".", "options", ".", "selectAllValue", "=", "this", ".", "options", ".", "selectAllValue", ".", "toString", "(", ")", ";", "}", "var", "alreadyHasSelectAll", "=", "this", ".", "hasSelectAll", "(", ")", ";", "if", "(", "!", "alreadyHasSelectAll", "&&", "this", ".", "options", ".", "includeSelectAllOption", "&&", "this", ".", "options", ".", "multiple", "&&", "$", "(", "'option'", ",", "this", ".", "$select", ")", ".", "length", ">", "this", ".", "options", ".", "includeSelectAllIfMoreThan", ")", "{", "if", "(", "this", ".", "options", ".", "includeSelectAllDivider", ")", "{", "this", ".", "$ul", ".", "prepend", "(", "$", "(", "this", ".", "options", ".", "templates", ".", "divider", ")", ")", ";", "}", "var", "$li", "=", "$", "(", "this", ".", "options", ".", "templates", ".", "li", ")", ";", "$", "(", "'label'", ",", "$li", ")", ".", "addClass", "(", "\"checkbox\"", ")", ";", "if", "(", "this", ".", "options", ".", "enableHTML", ")", "{", "$", "(", "'label'", ",", "$li", ")", ".", "html", "(", "\" \"", "+", "this", ".", "options", ".", "selectAllText", ")", ";", "}", "else", "{", "$", "(", "'label'", ",", "$li", ")", ".", "text", "(", "\" \"", "+", "this", ".", "options", ".", "selectAllText", ")", ";", "}", "if", "(", "this", ".", "options", ".", "selectAllName", ")", "{", "$", "(", "'label'", ",", "$li", ")", ".", "prepend", "(", "'<input type=\"checkbox\" name=\"'", "+", "this", ".", "options", ".", "selectAllName", "+", "'\" />'", ")", ";", "}", "else", "{", "$", "(", "'label'", ",", "$li", ")", ".", "prepend", "(", "'<input type=\"checkbox\" />'", ")", ";", "}", "var", "$checkbox", "=", "$", "(", "'input'", ",", "$li", ")", ";", "$checkbox", ".", "val", "(", "this", ".", "options", ".", "selectAllValue", ")", ";", "$li", ".", "addClass", "(", "\"multiselect-item multiselect-all\"", ")", ";", "$checkbox", ".", "parent", "(", ")", ".", "parent", "(", ")", ".", "addClass", "(", "'multiselect-all'", ")", ";", "this", ".", "$ul", ".", "prepend", "(", "$li", ")", ";", "$checkbox", ".", "prop", "(", "'checked'", ",", "false", ")", ";", "}", "}" ]
Build the selct all. Checks if a select all has already been created.
[ "Build", "the", "selct", "all", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js#L778-L821
train
hashchange/jquery.documentsize
demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js
function (justVisible) { var justVisible = typeof justVisible === 'undefined' ? true : justVisible; if(justVisible) { var visibleCheckboxes = $("li input[type='checkbox']:not(:disabled)", this.$ul).filter(":visible"); visibleCheckboxes.prop('checked', false); var values = visibleCheckboxes.map(function() { return $(this).val(); }).get(); $("option:enabled", this.$select).filter(function(index) { return $.inArray($(this).val(), values) !== -1; }).prop('selected', false); if (this.options.selectedClass) { $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").removeClass(this.options.selectedClass); } } else { $("li input[type='checkbox']:enabled", this.$ul).prop('checked', false); $("option:enabled", this.$select).prop('selected', false); if (this.options.selectedClass) { $("li:not(.divider):not(.disabled)", this.$ul).removeClass(this.options.selectedClass); } } }
javascript
function (justVisible) { var justVisible = typeof justVisible === 'undefined' ? true : justVisible; if(justVisible) { var visibleCheckboxes = $("li input[type='checkbox']:not(:disabled)", this.$ul).filter(":visible"); visibleCheckboxes.prop('checked', false); var values = visibleCheckboxes.map(function() { return $(this).val(); }).get(); $("option:enabled", this.$select).filter(function(index) { return $.inArray($(this).val(), values) !== -1; }).prop('selected', false); if (this.options.selectedClass) { $("li:not(.divider):not(.disabled)", this.$ul).filter(":visible").removeClass(this.options.selectedClass); } } else { $("li input[type='checkbox']:enabled", this.$ul).prop('checked', false); $("option:enabled", this.$select).prop('selected', false); if (this.options.selectedClass) { $("li:not(.divider):not(.disabled)", this.$ul).removeClass(this.options.selectedClass); } } }
[ "function", "(", "justVisible", ")", "{", "var", "justVisible", "=", "typeof", "justVisible", "===", "'undefined'", "?", "true", ":", "justVisible", ";", "if", "(", "justVisible", ")", "{", "var", "visibleCheckboxes", "=", "$", "(", "\"li input[type='checkbox']:not(:disabled)\"", ",", "this", ".", "$ul", ")", ".", "filter", "(", "\":visible\"", ")", ";", "visibleCheckboxes", ".", "prop", "(", "'checked'", ",", "false", ")", ";", "var", "values", "=", "visibleCheckboxes", ".", "map", "(", "function", "(", ")", "{", "return", "$", "(", "this", ")", ".", "val", "(", ")", ";", "}", ")", ".", "get", "(", ")", ";", "$", "(", "\"option:enabled\"", ",", "this", ".", "$select", ")", ".", "filter", "(", "function", "(", "index", ")", "{", "return", "$", ".", "inArray", "(", "$", "(", "this", ")", ".", "val", "(", ")", ",", "values", ")", "!==", "-", "1", ";", "}", ")", ".", "prop", "(", "'selected'", ",", "false", ")", ";", "if", "(", "this", ".", "options", ".", "selectedClass", ")", "{", "$", "(", "\"li:not(.divider):not(.disabled)\"", ",", "this", ".", "$ul", ")", ".", "filter", "(", "\":visible\"", ")", ".", "removeClass", "(", "this", ".", "options", ".", "selectedClass", ")", ";", "}", "}", "else", "{", "$", "(", "\"li input[type='checkbox']:enabled\"", ",", "this", ".", "$ul", ")", ".", "prop", "(", "'checked'", ",", "false", ")", ";", "$", "(", "\"option:enabled\"", ",", "this", ".", "$select", ")", ".", "prop", "(", "'selected'", ",", "false", ")", ";", "if", "(", "this", ".", "options", ".", "selectedClass", ")", "{", "$", "(", "\"li:not(.divider):not(.disabled)\"", ",", "this", ".", "$ul", ")", ".", "removeClass", "(", "this", ".", "options", ".", "selectedClass", ")", ";", "}", "}", "}" ]
Deselects all options. If justVisible is true or not specified, only visible options are deselected. @param {Boolean} justVisible
[ "Deselects", "all", "options", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js#L1130-L1157
train
hashchange/jquery.documentsize
demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js
function() { this.$ul.html(''); // Important to distinguish between radios and checkboxes. this.options.multiple = this.$select.attr('multiple') === "multiple"; this.buildSelectAll(); this.buildDropdownOptions(); this.buildFilter(); this.updateButtonText(); this.updateSelectAll(); if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) { this.disable(); } else { this.enable(); } if (this.options.dropRight) { this.$ul.addClass('pull-right'); } }
javascript
function() { this.$ul.html(''); // Important to distinguish between radios and checkboxes. this.options.multiple = this.$select.attr('multiple') === "multiple"; this.buildSelectAll(); this.buildDropdownOptions(); this.buildFilter(); this.updateButtonText(); this.updateSelectAll(); if (this.options.disableIfEmpty && $('option', this.$select).length <= 0) { this.disable(); } else { this.enable(); } if (this.options.dropRight) { this.$ul.addClass('pull-right'); } }
[ "function", "(", ")", "{", "this", ".", "$ul", ".", "html", "(", "''", ")", ";", "this", ".", "options", ".", "multiple", "=", "this", ".", "$select", ".", "attr", "(", "'multiple'", ")", "===", "\"multiple\"", ";", "this", ".", "buildSelectAll", "(", ")", ";", "this", ".", "buildDropdownOptions", "(", ")", ";", "this", ".", "buildFilter", "(", ")", ";", "this", ".", "updateButtonText", "(", ")", ";", "this", ".", "updateSelectAll", "(", ")", ";", "if", "(", "this", ".", "options", ".", "disableIfEmpty", "&&", "$", "(", "'option'", ",", "this", ".", "$select", ")", ".", "length", "<=", "0", ")", "{", "this", ".", "disable", "(", ")", ";", "}", "else", "{", "this", ".", "enable", "(", ")", ";", "}", "if", "(", "this", ".", "options", ".", "dropRight", ")", "{", "this", ".", "$ul", ".", "addClass", "(", "'pull-right'", ")", ";", "}", "}" ]
Rebuild the plugin. Rebuilds the dropdown, the filter and the select all option.
[ "Rebuild", "the", "plugin", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js#L1164-L1187
train
hashchange/jquery.documentsize
demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js
function() { if (this.hasSelectAll()) { var allBoxes = $("li:not(.multiselect-item):not(.filter-hidden) input:enabled", this.$ul); var allBoxesLength = allBoxes.length; var checkedBoxesLength = allBoxes.filter(":checked").length; var selectAllLi = $("li.multiselect-all", this.$ul); var selectAllInput = selectAllLi.find("input"); if (checkedBoxesLength > 0 && checkedBoxesLength === allBoxesLength) { selectAllInput.prop("checked", true); selectAllLi.addClass(this.options.selectedClass); this.options.onSelectAll(); } else { selectAllInput.prop("checked", false); selectAllLi.removeClass(this.options.selectedClass); } } }
javascript
function() { if (this.hasSelectAll()) { var allBoxes = $("li:not(.multiselect-item):not(.filter-hidden) input:enabled", this.$ul); var allBoxesLength = allBoxes.length; var checkedBoxesLength = allBoxes.filter(":checked").length; var selectAllLi = $("li.multiselect-all", this.$ul); var selectAllInput = selectAllLi.find("input"); if (checkedBoxesLength > 0 && checkedBoxesLength === allBoxesLength) { selectAllInput.prop("checked", true); selectAllLi.addClass(this.options.selectedClass); this.options.onSelectAll(); } else { selectAllInput.prop("checked", false); selectAllLi.removeClass(this.options.selectedClass); } } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "hasSelectAll", "(", ")", ")", "{", "var", "allBoxes", "=", "$", "(", "\"li:not(.multiselect-item):not(.filter-hidden) input:enabled\"", ",", "this", ".", "$ul", ")", ";", "var", "allBoxesLength", "=", "allBoxes", ".", "length", ";", "var", "checkedBoxesLength", "=", "allBoxes", ".", "filter", "(", "\":checked\"", ")", ".", "length", ";", "var", "selectAllLi", "=", "$", "(", "\"li.multiselect-all\"", ",", "this", ".", "$ul", ")", ";", "var", "selectAllInput", "=", "selectAllLi", ".", "find", "(", "\"input\"", ")", ";", "if", "(", "checkedBoxesLength", ">", "0", "&&", "checkedBoxesLength", "===", "allBoxesLength", ")", "{", "selectAllInput", ".", "prop", "(", "\"checked\"", ",", "true", ")", ";", "selectAllLi", ".", "addClass", "(", "this", ".", "options", ".", "selectedClass", ")", ";", "this", ".", "options", ".", "onSelectAll", "(", ")", ";", "}", "else", "{", "selectAllInput", ".", "prop", "(", "\"checked\"", ",", "false", ")", ";", "selectAllLi", ".", "removeClass", "(", "this", ".", "options", ".", "selectedClass", ")", ";", "}", "}", "}" ]
Updates the select all checkbox based on the currently displayed and selected checkboxes.
[ "Updates", "the", "select", "all", "checkbox", "based", "on", "the", "currently", "displayed", "and", "selected", "checkboxes", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/bootstrap-multiselect/bootstrap-multiselect.js#L1283-L1301
train
hashchange/jquery.documentsize
demo/load-event/js/libs/detectizr/detectizr-2.2.0.js
extend
function extend(obj, extObj) { var a, b, i; if (arguments.length > 2) { for (a = 1, b = arguments.length; a < b; a += 1) { extend(obj, arguments[a]); } } else { for (i in extObj) { if (extObj.hasOwnProperty(i)) { obj[i] = extObj[i]; } } } return obj; }
javascript
function extend(obj, extObj) { var a, b, i; if (arguments.length > 2) { for (a = 1, b = arguments.length; a < b; a += 1) { extend(obj, arguments[a]); } } else { for (i in extObj) { if (extObj.hasOwnProperty(i)) { obj[i] = extObj[i]; } } } return obj; }
[ "function", "extend", "(", "obj", ",", "extObj", ")", "{", "var", "a", ",", "b", ",", "i", ";", "if", "(", "arguments", ".", "length", ">", "2", ")", "{", "for", "(", "a", "=", "1", ",", "b", "=", "arguments", ".", "length", ";", "a", "<", "b", ";", "a", "+=", "1", ")", "{", "extend", "(", "obj", ",", "arguments", "[", "a", "]", ")", ";", "}", "}", "else", "{", "for", "(", "i", "in", "extObj", ")", "{", "if", "(", "extObj", ".", "hasOwnProperty", "(", "i", ")", ")", "{", "obj", "[", "i", "]", "=", "extObj", "[", "i", "]", ";", "}", "}", "}", "return", "obj", ";", "}" ]
Create Global "extend" method, so Detectizr does not need jQuery.extend
[ "Create", "Global", "extend", "method", "so", "Detectizr", "does", "not", "need", "jQuery", ".", "extend" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/detectizr/detectizr-2.2.0.js#L59-L73
train
hashchange/jquery.documentsize
demo/load-event/js/libs/detectizr/detectizr-2.2.0.js
toCamel
function toCamel(string) { if (string === null || string === undefined) { return ""; } return String(string).replace(/((\s|\-|\.)+[a-z0-9])/g, function($1) { return $1.toUpperCase().replace(/(\s|\-|\.)/g, ""); }); }
javascript
function toCamel(string) { if (string === null || string === undefined) { return ""; } return String(string).replace(/((\s|\-|\.)+[a-z0-9])/g, function($1) { return $1.toUpperCase().replace(/(\s|\-|\.)/g, ""); }); }
[ "function", "toCamel", "(", "string", ")", "{", "if", "(", "string", "===", "null", "||", "string", "===", "undefined", ")", "{", "return", "\"\"", ";", "}", "return", "String", "(", "string", ")", ".", "replace", "(", "/", "((\\s|\\-|\\.)+[a-z0-9])", "/", "g", ",", "function", "(", "$1", ")", "{", "return", "$1", ".", "toUpperCase", "(", ")", ".", "replace", "(", "/", "(\\s|\\-|\\.)", "/", "g", ",", "\"\"", ")", ";", "}", ")", ";", "}" ]
convert string to camelcase
[ "convert", "string", "to", "camelcase" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/detectizr/detectizr-2.2.0.js#L96-L103
train
hashchange/jquery.documentsize
demo/load-event/js/libs/detectizr/detectizr-2.2.0.js
removeClass
function removeClass(element, value) { var class2remove = value || "", cur = element.nodeType === 1 && (element.className ? (" " + element.className + " ").replace(rclass, " ") : ""); if (cur) { while (cur.indexOf(" " + class2remove + " ") >= 0) { cur = cur.replace(" " + class2remove + " ", " "); } element.className = value ? trim(cur) : ""; } }
javascript
function removeClass(element, value) { var class2remove = value || "", cur = element.nodeType === 1 && (element.className ? (" " + element.className + " ").replace(rclass, " ") : ""); if (cur) { while (cur.indexOf(" " + class2remove + " ") >= 0) { cur = cur.replace(" " + class2remove + " ", " "); } element.className = value ? trim(cur) : ""; } }
[ "function", "removeClass", "(", "element", ",", "value", ")", "{", "var", "class2remove", "=", "value", "||", "\"\"", ",", "cur", "=", "element", ".", "nodeType", "===", "1", "&&", "(", "element", ".", "className", "?", "(", "\" \"", "+", "element", ".", "className", "+", "\" \"", ")", ".", "replace", "(", "rclass", ",", "\" \"", ")", ":", "\"\"", ")", ";", "if", "(", "cur", ")", "{", "while", "(", "cur", ".", "indexOf", "(", "\" \"", "+", "class2remove", "+", "\" \"", ")", ">=", "0", ")", "{", "cur", "=", "cur", ".", "replace", "(", "\" \"", "+", "class2remove", "+", "\" \"", ",", "\" \"", ")", ";", "}", "element", ".", "className", "=", "value", "?", "trim", "(", "cur", ")", ":", "\"\"", ";", "}", "}" ]
removeClass function inspired from jQuery.removeClass
[ "removeClass", "function", "inspired", "from", "jQuery", ".", "removeClass" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/detectizr/detectizr-2.2.0.js#L106-L115
train
hashchange/jquery.documentsize
demo/load-event/js/libs/detectizr/detectizr-2.2.0.js
setVersion
function setVersion(versionType, versionFull) { versionType.version = versionFull; var versionArray = versionFull.split("."); if (versionArray.length > 0) { versionArray = versionArray.reverse(); versionType.major = versionArray.pop(); if (versionArray.length > 0) { versionType.minor = versionArray.pop(); if (versionArray.length > 0) { versionArray = versionArray.reverse(); versionType.patch = versionArray.join("."); } else { versionType.patch = "0"; } } else { versionType.minor = "0"; } } else { versionType.major = "0"; } }
javascript
function setVersion(versionType, versionFull) { versionType.version = versionFull; var versionArray = versionFull.split("."); if (versionArray.length > 0) { versionArray = versionArray.reverse(); versionType.major = versionArray.pop(); if (versionArray.length > 0) { versionType.minor = versionArray.pop(); if (versionArray.length > 0) { versionArray = versionArray.reverse(); versionType.patch = versionArray.join("."); } else { versionType.patch = "0"; } } else { versionType.minor = "0"; } } else { versionType.major = "0"; } }
[ "function", "setVersion", "(", "versionType", ",", "versionFull", ")", "{", "versionType", ".", "version", "=", "versionFull", ";", "var", "versionArray", "=", "versionFull", ".", "split", "(", "\".\"", ")", ";", "if", "(", "versionArray", ".", "length", ">", "0", ")", "{", "versionArray", "=", "versionArray", ".", "reverse", "(", ")", ";", "versionType", ".", "major", "=", "versionArray", ".", "pop", "(", ")", ";", "if", "(", "versionArray", ".", "length", ">", "0", ")", "{", "versionType", ".", "minor", "=", "versionArray", ".", "pop", "(", ")", ";", "if", "(", "versionArray", ".", "length", ">", "0", ")", "{", "versionArray", "=", "versionArray", ".", "reverse", "(", ")", ";", "versionType", ".", "patch", "=", "versionArray", ".", "join", "(", "\".\"", ")", ";", "}", "else", "{", "versionType", ".", "patch", "=", "\"0\"", ";", "}", "}", "else", "{", "versionType", ".", "minor", "=", "\"0\"", ";", "}", "}", "else", "{", "versionType", ".", "major", "=", "\"0\"", ";", "}", "}" ]
set version based on versionFull
[ "set", "version", "based", "on", "versionFull" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/detectizr/detectizr-2.2.0.js#L149-L169
train
hashchange/jquery.documentsize
spec/helpers/measurement.js
getBoundingClientRectCompat
function getBoundingClientRectCompat ( elem ) { var elemRect = elem.getBoundingClientRect(); if ( elemRect.width === undefined || elemRect.height === undefined ) { // Fix for IE8 elemRect = { top: elemRect.top, left: elemRect.left, bottom: elemRect.bottom, right: elemRect.right, width: elemRect.right - elemRect.left, height: elemRect.bottom - elemRect.top }; } return elemRect; }
javascript
function getBoundingClientRectCompat ( elem ) { var elemRect = elem.getBoundingClientRect(); if ( elemRect.width === undefined || elemRect.height === undefined ) { // Fix for IE8 elemRect = { top: elemRect.top, left: elemRect.left, bottom: elemRect.bottom, right: elemRect.right, width: elemRect.right - elemRect.left, height: elemRect.bottom - elemRect.top }; } return elemRect; }
[ "function", "getBoundingClientRectCompat", "(", "elem", ")", "{", "var", "elemRect", "=", "elem", ".", "getBoundingClientRect", "(", ")", ";", "if", "(", "elemRect", ".", "width", "===", "undefined", "||", "elemRect", ".", "height", "===", "undefined", ")", "{", "elemRect", "=", "{", "top", ":", "elemRect", ".", "top", ",", "left", ":", "elemRect", ".", "left", ",", "bottom", ":", "elemRect", ".", "bottom", ",", "right", ":", "elemRect", ".", "right", ",", "width", ":", "elemRect", ".", "right", "-", "elemRect", ".", "left", ",", "height", ":", "elemRect", ".", "bottom", "-", "elemRect", ".", "top", "}", ";", "}", "return", "elemRect", ";", "}" ]
Returns the bounding client rect, including width and height properties. For compatibility with IE8, which supports getBoundingClientRect but doesn't calculate width and height. Use only when width and height are actually needed. Will be removed when IE8 support is dropped entirely. @param {HTMLElement} elem @returns {ClientRect}
[ "Returns", "the", "bounding", "client", "rect", "including", "width", "and", "height", "properties", ".", "For", "compatibility", "with", "IE8", "which", "supports", "getBoundingClientRect", "but", "doesn", "t", "calculate", "width", "and", "height", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/measurement.js#L152-L168
train
hashchange/jquery.documentsize
spec/helpers/measurement.js
getAppliedOverflows
function getAppliedOverflows ( props, createBooleans ) { var status = {}; // Establish the applied overflow (e.g. overflowX: "scroll") status.overflowX = props.overflowX || props.overflow || "visible"; status.overflowY = props.overflowY || props.overflow || "visible"; // Create the derived boolean status properties (e.g overflowScrollX: true) if ( createBooleans ) { $.each( [ "Visible", "Auto", "Scroll", "Hidden" ], function ( index, type ) { var lcType = type.toLowerCase(); status["overflow" + type + "X"] = status.overflowX === lcType; status["overflow" + type + "Y"] = status.overflowY === lcType; } ); } return status; }
javascript
function getAppliedOverflows ( props, createBooleans ) { var status = {}; // Establish the applied overflow (e.g. overflowX: "scroll") status.overflowX = props.overflowX || props.overflow || "visible"; status.overflowY = props.overflowY || props.overflow || "visible"; // Create the derived boolean status properties (e.g overflowScrollX: true) if ( createBooleans ) { $.each( [ "Visible", "Auto", "Scroll", "Hidden" ], function ( index, type ) { var lcType = type.toLowerCase(); status["overflow" + type + "X"] = status.overflowX === lcType; status["overflow" + type + "Y"] = status.overflowY === lcType; } ); } return status; }
[ "function", "getAppliedOverflows", "(", "props", ",", "createBooleans", ")", "{", "var", "status", "=", "{", "}", ";", "status", ".", "overflowX", "=", "props", ".", "overflowX", "||", "props", ".", "overflow", "||", "\"visible\"", ";", "status", ".", "overflowY", "=", "props", ".", "overflowY", "||", "props", ".", "overflow", "||", "\"visible\"", ";", "if", "(", "createBooleans", ")", "{", "$", ".", "each", "(", "[", "\"Visible\"", ",", "\"Auto\"", ",", "\"Scroll\"", ",", "\"Hidden\"", "]", ",", "function", "(", "index", ",", "type", ")", "{", "var", "lcType", "=", "type", ".", "toLowerCase", "(", ")", ";", "status", "[", "\"overflow\"", "+", "type", "+", "\"X\"", "]", "=", "status", ".", "overflowX", "===", "lcType", ";", "status", "[", "\"overflow\"", "+", "type", "+", "\"Y\"", "]", "=", "status", ".", "overflowY", "===", "lcType", ";", "}", ")", ";", "}", "return", "status", ";", "}" ]
Determines the effective overflow setting of an element, separately for each axis, based on the `overflow`, `overflowX` and `overflowY` properties of the element which must be passed in as a hash. Returns a hash of the computed results for overflowX, overflowY. Also adds boolean status properties to the hash if the createBooleans flag is set. These are properties for mere convenience. They signal if a particular overflow type applies (e.g. overflowHiddenX = true/false). ATTN The method does not take the special relation of body and documentElement into account. That is handled by the more specific getAppliedViewportOverflows() function. The effective overflow setting is established as follows: - If a computed value for `overflow(X/Y)` exists, it gets applied to the axis. - If not, the computed value of the general `overflow` setting gets applied to the axis. - If there is no computed value at all, the overflow default gets applied to the axis. The default is "visible" in seemingly every browser out there. Falling back to the default should never be necessary, though, because there always is a computed value. @param {Object} props hash of element properties (computed values) @param {string} props.overflow @param {string} props.overflowX @param {string} props.overflowY @param {boolean=false} createBooleans if true, create the full set of boolean status properties, e.g. overflowVisibleX (true/false), overflowHiddenY (true/false) etc @returns {AppliedOverflow} hash of the computed results: overflowX, overflowY, optional boolean status properties
[ "Determines", "the", "effective", "overflow", "setting", "of", "an", "element", "separately", "for", "each", "axis", "based", "on", "the", "overflow", "overflowX", "and", "overflowY", "properties", "of", "the", "element", "which", "must", "be", "passed", "in", "as", "a", "hash", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/measurement.js#L198-L215
train
hashchange/jquery.documentsize
spec/helpers/measurement.js
getAppliedViewportOverflows
function getAppliedViewportOverflows ( documentElementProps, bodyProps ) { var _window = getAppliedOverflows( documentElementProps, false ), body = getAppliedOverflows( bodyProps, false ), consolidated = { window: {}, body: {} }; // Handle the interdependent relation between body and window (documentElement) overflow if ( _window.overflowX === "visible" ) { // If the window overflow is set to "visible", body props get transferred to the window, body changes to // "visible". (Nothing really changes if both are set to "visible".) consolidated.body.overflowX = "visible"; consolidated.window.overflowX = body.overflowX; } else { // No transfer of properties. // - If body overflow is "visible", it remains that way, and the window stays as it is. // - If body and window are set to properties other than "visible", they keep their divergent settings. consolidated.body.overflowX = body.overflowX; consolidated.window.overflowX = _window.overflowX; } // Repeat for overflowY if ( _window.overflowY === "visible" ) { consolidated.body.overflowY = "visible"; consolidated.window.overflowY = body.overflowY; } else { consolidated.body.overflowY = body.overflowY; consolidated.window.overflowY = _window.overflowY; } // window.overflow(X/Y): "visible" actually means "auto" because scroll bars appear as needed; transform if ( consolidated.window.overflowX === "visible" ) consolidated.window.overflowX = "auto"; if ( consolidated.window.overflowY === "visible" ) consolidated.window.overflowY = "auto"; // In iOS, window.overflow(X/Y): "hidden" actually means "auto"; transform if ( isIOS() ) { if ( consolidated.window.overflowX === "hidden" ) consolidated.window.overflowX = "auto"; if ( consolidated.window.overflowY === "hidden" ) consolidated.window.overflowY = "auto"; } // Add the boolean status properties to the result consolidated.window = getAppliedOverflows( consolidated.window, true ); consolidated.body = getAppliedOverflows( consolidated.body, true ); return consolidated; }
javascript
function getAppliedViewportOverflows ( documentElementProps, bodyProps ) { var _window = getAppliedOverflows( documentElementProps, false ), body = getAppliedOverflows( bodyProps, false ), consolidated = { window: {}, body: {} }; // Handle the interdependent relation between body and window (documentElement) overflow if ( _window.overflowX === "visible" ) { // If the window overflow is set to "visible", body props get transferred to the window, body changes to // "visible". (Nothing really changes if both are set to "visible".) consolidated.body.overflowX = "visible"; consolidated.window.overflowX = body.overflowX; } else { // No transfer of properties. // - If body overflow is "visible", it remains that way, and the window stays as it is. // - If body and window are set to properties other than "visible", they keep their divergent settings. consolidated.body.overflowX = body.overflowX; consolidated.window.overflowX = _window.overflowX; } // Repeat for overflowY if ( _window.overflowY === "visible" ) { consolidated.body.overflowY = "visible"; consolidated.window.overflowY = body.overflowY; } else { consolidated.body.overflowY = body.overflowY; consolidated.window.overflowY = _window.overflowY; } // window.overflow(X/Y): "visible" actually means "auto" because scroll bars appear as needed; transform if ( consolidated.window.overflowX === "visible" ) consolidated.window.overflowX = "auto"; if ( consolidated.window.overflowY === "visible" ) consolidated.window.overflowY = "auto"; // In iOS, window.overflow(X/Y): "hidden" actually means "auto"; transform if ( isIOS() ) { if ( consolidated.window.overflowX === "hidden" ) consolidated.window.overflowX = "auto"; if ( consolidated.window.overflowY === "hidden" ) consolidated.window.overflowY = "auto"; } // Add the boolean status properties to the result consolidated.window = getAppliedOverflows( consolidated.window, true ); consolidated.body = getAppliedOverflows( consolidated.body, true ); return consolidated; }
[ "function", "getAppliedViewportOverflows", "(", "documentElementProps", ",", "bodyProps", ")", "{", "var", "_window", "=", "getAppliedOverflows", "(", "documentElementProps", ",", "false", ")", ",", "body", "=", "getAppliedOverflows", "(", "bodyProps", ",", "false", ")", ",", "consolidated", "=", "{", "window", ":", "{", "}", ",", "body", ":", "{", "}", "}", ";", "if", "(", "_window", ".", "overflowX", "===", "\"visible\"", ")", "{", "consolidated", ".", "body", ".", "overflowX", "=", "\"visible\"", ";", "consolidated", ".", "window", ".", "overflowX", "=", "body", ".", "overflowX", ";", "}", "else", "{", "consolidated", ".", "body", ".", "overflowX", "=", "body", ".", "overflowX", ";", "consolidated", ".", "window", ".", "overflowX", "=", "_window", ".", "overflowX", ";", "}", "if", "(", "_window", ".", "overflowY", "===", "\"visible\"", ")", "{", "consolidated", ".", "body", ".", "overflowY", "=", "\"visible\"", ";", "consolidated", ".", "window", ".", "overflowY", "=", "body", ".", "overflowY", ";", "}", "else", "{", "consolidated", ".", "body", ".", "overflowY", "=", "body", ".", "overflowY", ";", "consolidated", ".", "window", ".", "overflowY", "=", "_window", ".", "overflowY", ";", "}", "if", "(", "consolidated", ".", "window", ".", "overflowX", "===", "\"visible\"", ")", "consolidated", ".", "window", ".", "overflowX", "=", "\"auto\"", ";", "if", "(", "consolidated", ".", "window", ".", "overflowY", "===", "\"visible\"", ")", "consolidated", ".", "window", ".", "overflowY", "=", "\"auto\"", ";", "if", "(", "isIOS", "(", ")", ")", "{", "if", "(", "consolidated", ".", "window", ".", "overflowX", "===", "\"hidden\"", ")", "consolidated", ".", "window", ".", "overflowX", "=", "\"auto\"", ";", "if", "(", "consolidated", ".", "window", ".", "overflowY", "===", "\"hidden\"", ")", "consolidated", ".", "window", ".", "overflowY", "=", "\"auto\"", ";", "}", "consolidated", ".", "window", "=", "getAppliedOverflows", "(", "consolidated", ".", "window", ",", "true", ")", ";", "consolidated", ".", "body", "=", "getAppliedOverflows", "(", "consolidated", ".", "body", ",", "true", ")", ";", "return", "consolidated", ";", "}" ]
Determines the effective overflow setting of the viewport and body, separately for each axis, based on the `overflow`, `overflowX` and `overflowY` properties of the documentElement and body which must be passed in as a hash. Returns the results for viewport and body in an aggregated `{ window: ..., body: ...}` hash. For the basic resolution mechanism, see getAppliedOverflows(). When determining the effective overflow, the peculiarities of viewport and body are taken into account: - Viewport and body overflows are interdependent. If the nominal viewport overflow for a given axis is "visible", the viewport inherits the body overflow for that axis, and the body overflow is set to "visible". Curiously, that transfer is _not_ reflected in the computed values, it just manifests in behaviour. - Once that is done, if the viewport overflow is still "visible" for an axis, it is effectively turned into "auto". Scroll bars appear when the content overflows the viewport (ie, "auto" behaviour). Hence, this function will indeed report "auto". Again, the transformation is only manifest in behaviour, not in the computed values. - In iOS, if the effective overflow setting of the viewport is "hidden", it is ignored and treated as "auto". Content can still overflow the viewport, and scroll bars appear as needed. Now, the catch. This behaviour is impossible to feature-detect. The computed values are not at all affected by it, and the results reported eg. for clientHeight, offsetHeight, scrollHeight of body and documentElement do not differ between Safari on iOS and, say, Chrome. The numbers don't give the behaviour away. So we have to resort to browser sniffing here. It sucks, but there is literally no other option. NB Additional status properties (see getAppliedOverflows) are always generated here. @param {Object} documentElementProps hash of documentElement properties (computed values) @param {string} documentElementProps.overflow @param {string} documentElementProps.overflowX @param {string} documentElementProps.overflowY @param {Object} bodyProps hash of body properties (computed values) @param {string} bodyProps.overflow @param {string} bodyProps.overflowX @param {string} bodyProps.overflowY @returns {{window: AppliedOverflow, body: AppliedOverflow}}
[ "Determines", "the", "effective", "overflow", "setting", "of", "the", "viewport", "and", "body", "separately", "for", "each", "axis", "based", "on", "the", "overflow", "overflowX", "and", "overflowY", "properties", "of", "the", "documentElement", "and", "body", "which", "must", "be", "passed", "in", "as", "a", "hash", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/measurement.js#L258-L301
train
hashchange/jquery.documentsize
demo/amd/amd.js
scaleLog
function scaleLog () { var zoomFactor = $.pinchZoomFactor(), logProps = { top: ( initialLogProps.top / zoomFactor ) + "px", left: ( initialLogProps.left / zoomFactor ) + "px", paddingTop: ( initialLogProps.paddingTop / zoomFactor ) + "px", paddingLeft: ( initialLogProps.paddingLeft / zoomFactor ) + "px", paddingBottom: ( initialLogProps.paddingBottom / zoomFactor ) + "px", paddingRight: ( initialLogProps.paddingRight / zoomFactor ) + "px", minWidth: ( initialLogProps.minWidth / zoomFactor ) + "px", maxWidth: ( initialLogProps.maxWidth / zoomFactor ) + "px" }, dtProps = { fontSize: ( initialLogProps.dtFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.dtLineHeight / zoomFactor ) + "px", minWidth: ( initialLogProps.dtMinWidth / zoomFactor ) + "px" }, ddProps = { fontSize: ( initialLogProps.ddFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.ddLineHeight / zoomFactor ) + "px" }, dlProps = { fontSize: ( initialLogProps.dlFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.dlLineHeight / zoomFactor ) + "px", marginBottom: ( initialLogProps.dlMarginBottom / zoomFactor ) + "px" }, hrProps = { marginTop: ( initialLogProps.hrMarginTop / zoomFactor ) + "px", marginBottom: ( initialLogProps.hrMarginBottom / zoomFactor ) + "px" }; $logPane.css( logProps ); $( "dt", $logPane ).css( dtProps ); $( "dd", $logPane ).css( ddProps ); $( "dl", $logPane ).css( dlProps ); $( "hr", $logPane ).css( hrProps ); }
javascript
function scaleLog () { var zoomFactor = $.pinchZoomFactor(), logProps = { top: ( initialLogProps.top / zoomFactor ) + "px", left: ( initialLogProps.left / zoomFactor ) + "px", paddingTop: ( initialLogProps.paddingTop / zoomFactor ) + "px", paddingLeft: ( initialLogProps.paddingLeft / zoomFactor ) + "px", paddingBottom: ( initialLogProps.paddingBottom / zoomFactor ) + "px", paddingRight: ( initialLogProps.paddingRight / zoomFactor ) + "px", minWidth: ( initialLogProps.minWidth / zoomFactor ) + "px", maxWidth: ( initialLogProps.maxWidth / zoomFactor ) + "px" }, dtProps = { fontSize: ( initialLogProps.dtFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.dtLineHeight / zoomFactor ) + "px", minWidth: ( initialLogProps.dtMinWidth / zoomFactor ) + "px" }, ddProps = { fontSize: ( initialLogProps.ddFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.ddLineHeight / zoomFactor ) + "px" }, dlProps = { fontSize: ( initialLogProps.dlFontSize / zoomFactor ) + "px", lineHeight: ( initialLogProps.dlLineHeight / zoomFactor ) + "px", marginBottom: ( initialLogProps.dlMarginBottom / zoomFactor ) + "px" }, hrProps = { marginTop: ( initialLogProps.hrMarginTop / zoomFactor ) + "px", marginBottom: ( initialLogProps.hrMarginBottom / zoomFactor ) + "px" }; $logPane.css( logProps ); $( "dt", $logPane ).css( dtProps ); $( "dd", $logPane ).css( ddProps ); $( "dl", $logPane ).css( dlProps ); $( "hr", $logPane ).css( hrProps ); }
[ "function", "scaleLog", "(", ")", "{", "var", "zoomFactor", "=", "$", ".", "pinchZoomFactor", "(", ")", ",", "logProps", "=", "{", "top", ":", "(", "initialLogProps", ".", "top", "/", "zoomFactor", ")", "+", "\"px\"", ",", "left", ":", "(", "initialLogProps", ".", "left", "/", "zoomFactor", ")", "+", "\"px\"", ",", "paddingTop", ":", "(", "initialLogProps", ".", "paddingTop", "/", "zoomFactor", ")", "+", "\"px\"", ",", "paddingLeft", ":", "(", "initialLogProps", ".", "paddingLeft", "/", "zoomFactor", ")", "+", "\"px\"", ",", "paddingBottom", ":", "(", "initialLogProps", ".", "paddingBottom", "/", "zoomFactor", ")", "+", "\"px\"", ",", "paddingRight", ":", "(", "initialLogProps", ".", "paddingRight", "/", "zoomFactor", ")", "+", "\"px\"", ",", "minWidth", ":", "(", "initialLogProps", ".", "minWidth", "/", "zoomFactor", ")", "+", "\"px\"", ",", "maxWidth", ":", "(", "initialLogProps", ".", "maxWidth", "/", "zoomFactor", ")", "+", "\"px\"", "}", ",", "dtProps", "=", "{", "fontSize", ":", "(", "initialLogProps", ".", "dtFontSize", "/", "zoomFactor", ")", "+", "\"px\"", ",", "lineHeight", ":", "(", "initialLogProps", ".", "dtLineHeight", "/", "zoomFactor", ")", "+", "\"px\"", ",", "minWidth", ":", "(", "initialLogProps", ".", "dtMinWidth", "/", "zoomFactor", ")", "+", "\"px\"", "}", ",", "ddProps", "=", "{", "fontSize", ":", "(", "initialLogProps", ".", "ddFontSize", "/", "zoomFactor", ")", "+", "\"px\"", ",", "lineHeight", ":", "(", "initialLogProps", ".", "ddLineHeight", "/", "zoomFactor", ")", "+", "\"px\"", "}", ",", "dlProps", "=", "{", "fontSize", ":", "(", "initialLogProps", ".", "dlFontSize", "/", "zoomFactor", ")", "+", "\"px\"", ",", "lineHeight", ":", "(", "initialLogProps", ".", "dlLineHeight", "/", "zoomFactor", ")", "+", "\"px\"", ",", "marginBottom", ":", "(", "initialLogProps", ".", "dlMarginBottom", "/", "zoomFactor", ")", "+", "\"px\"", "}", ",", "hrProps", "=", "{", "marginTop", ":", "(", "initialLogProps", ".", "hrMarginTop", "/", "zoomFactor", ")", "+", "\"px\"", ",", "marginBottom", ":", "(", "initialLogProps", ".", "hrMarginBottom", "/", "zoomFactor", ")", "+", "\"px\"", "}", ";", "$logPane", ".", "css", "(", "logProps", ")", ";", "$", "(", "\"dt\"", ",", "$logPane", ")", ".", "css", "(", "dtProps", ")", ";", "$", "(", "\"dd\"", ",", "$logPane", ")", ".", "css", "(", "ddProps", ")", ";", "$", "(", "\"dl\"", ",", "$logPane", ")", ".", "css", "(", "dlProps", ")", ";", "$", "(", "\"hr\"", ",", "$logPane", ")", ".", "css", "(", "hrProps", ")", ";", "}" ]
Makes sure the log always keeps the same size, visually, as the user zooms in and out
[ "Makes", "sure", "the", "log", "always", "keeps", "the", "same", "size", "visually", "as", "the", "user", "zooms", "in", "and", "out" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/amd/amd.js#L106-L145
train
hashchange/jquery.documentsize
demo/load-event/js/libs/modernizr/modernizr-custom.js
injectElementWithStyles
function injectElementWithStyles(rule, callback, nodes, testnames) { var mod = 'modernizr'; var style; var ret; var node; var docOverflow; var div = createElement('div'); var body = getBody(); if (parseInt(nodes, 10)) { // In order not to give false positives we create a node for each test // This also allows the method to scale for unspecified uses while (nodes--) { node = createElement('div'); node.id = testnames ? testnames[nodes] : mod + (nodes + 1); div.appendChild(node); } } style = createElement('style'); style.type = 'text/css'; style.id = 's' + mod; // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody. // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270 (!body.fake ? div : body).appendChild(style); body.appendChild(div); if (style.styleSheet) { style.styleSheet.cssText = rule; } else { style.appendChild(document.createTextNode(rule)); } div.id = mod; if (body.fake) { //avoid crashing IE8, if background image is used body.style.background = ''; //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible body.style.overflow = 'hidden'; docOverflow = docElement.style.overflow; docElement.style.overflow = 'hidden'; docElement.appendChild(body); } ret = callback(div, rule); // If this is done after page load we don't want to remove the body so check if body exists if (body.fake) { body.parentNode.removeChild(body); docElement.style.overflow = docOverflow; // Trigger layout so kinetic scrolling isn't disabled in iOS6+ docElement.offsetHeight; } else { div.parentNode.removeChild(div); } return !!ret; }
javascript
function injectElementWithStyles(rule, callback, nodes, testnames) { var mod = 'modernizr'; var style; var ret; var node; var docOverflow; var div = createElement('div'); var body = getBody(); if (parseInt(nodes, 10)) { // In order not to give false positives we create a node for each test // This also allows the method to scale for unspecified uses while (nodes--) { node = createElement('div'); node.id = testnames ? testnames[nodes] : mod + (nodes + 1); div.appendChild(node); } } style = createElement('style'); style.type = 'text/css'; style.id = 's' + mod; // IE6 will false positive on some tests due to the style element inside the test div somehow interfering offsetHeight, so insert it into body or fakebody. // Opera will act all quirky when injecting elements in documentElement when page is served as xml, needs fakebody too. #270 (!body.fake ? div : body).appendChild(style); body.appendChild(div); if (style.styleSheet) { style.styleSheet.cssText = rule; } else { style.appendChild(document.createTextNode(rule)); } div.id = mod; if (body.fake) { //avoid crashing IE8, if background image is used body.style.background = ''; //Safari 5.13/5.1.4 OSX stops loading if ::-webkit-scrollbar is used and scrollbars are visible body.style.overflow = 'hidden'; docOverflow = docElement.style.overflow; docElement.style.overflow = 'hidden'; docElement.appendChild(body); } ret = callback(div, rule); // If this is done after page load we don't want to remove the body so check if body exists if (body.fake) { body.parentNode.removeChild(body); docElement.style.overflow = docOverflow; // Trigger layout so kinetic scrolling isn't disabled in iOS6+ docElement.offsetHeight; } else { div.parentNode.removeChild(div); } return !!ret; }
[ "function", "injectElementWithStyles", "(", "rule", ",", "callback", ",", "nodes", ",", "testnames", ")", "{", "var", "mod", "=", "'modernizr'", ";", "var", "style", ";", "var", "ret", ";", "var", "node", ";", "var", "docOverflow", ";", "var", "div", "=", "createElement", "(", "'div'", ")", ";", "var", "body", "=", "getBody", "(", ")", ";", "if", "(", "parseInt", "(", "nodes", ",", "10", ")", ")", "{", "while", "(", "nodes", "--", ")", "{", "node", "=", "createElement", "(", "'div'", ")", ";", "node", ".", "id", "=", "testnames", "?", "testnames", "[", "nodes", "]", ":", "mod", "+", "(", "nodes", "+", "1", ")", ";", "div", ".", "appendChild", "(", "node", ")", ";", "}", "}", "style", "=", "createElement", "(", "'style'", ")", ";", "style", ".", "type", "=", "'text/css'", ";", "style", ".", "id", "=", "'s'", "+", "mod", ";", "(", "!", "body", ".", "fake", "?", "div", ":", "body", ")", ".", "appendChild", "(", "style", ")", ";", "body", ".", "appendChild", "(", "div", ")", ";", "if", "(", "style", ".", "styleSheet", ")", "{", "style", ".", "styleSheet", ".", "cssText", "=", "rule", ";", "}", "else", "{", "style", ".", "appendChild", "(", "document", ".", "createTextNode", "(", "rule", ")", ")", ";", "}", "div", ".", "id", "=", "mod", ";", "if", "(", "body", ".", "fake", ")", "{", "body", ".", "style", ".", "background", "=", "''", ";", "body", ".", "style", ".", "overflow", "=", "'hidden'", ";", "docOverflow", "=", "docElement", ".", "style", ".", "overflow", ";", "docElement", ".", "style", ".", "overflow", "=", "'hidden'", ";", "docElement", ".", "appendChild", "(", "body", ")", ";", "}", "ret", "=", "callback", "(", "div", ",", "rule", ")", ";", "if", "(", "body", ".", "fake", ")", "{", "body", ".", "parentNode", ".", "removeChild", "(", "body", ")", ";", "docElement", ".", "style", ".", "overflow", "=", "docOverflow", ";", "docElement", ".", "offsetHeight", ";", "}", "else", "{", "div", ".", "parentNode", ".", "removeChild", "(", "div", ")", ";", "}", "return", "!", "!", "ret", ";", "}" ]
injectElementWithStyles injects an element with style element and some CSS rules @access private @function injectElementWithStyles @param {string} rule - String representing a css rule @param {function} callback - A function that is used to test the injected element @param {number} [nodes] - An integer representing the number of additional nodes you want injected @param {string[]} [testnames] - An array of strings that are used as ids for the additional nodes @returns {boolean}
[ "injectElementWithStyles", "injects", "an", "element", "with", "style", "element", "and", "some", "CSS", "rules" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/modernizr/modernizr-custom.js#L770-L828
train
hashchange/jquery.documentsize
demo/load-event/custom.js
htmlAsEntities
function htmlAsEntities(html){ html = html.replace(/&/g, '&amp;'); html = html.replace(/>/g, '&gt;'); html = html.replace(/</g, '&lt;'); html = html.replace(/"/g, '&quot;'); html = html.replace(/'/g, '&#039;'); return html; }
javascript
function htmlAsEntities(html){ html = html.replace(/&/g, '&amp;'); html = html.replace(/>/g, '&gt;'); html = html.replace(/</g, '&lt;'); html = html.replace(/"/g, '&quot;'); html = html.replace(/'/g, '&#039;'); return html; }
[ "function", "htmlAsEntities", "(", "html", ")", "{", "html", "=", "html", ".", "replace", "(", "/", "&", "/", "g", ",", "'&amp;'", ")", ";", "html", "=", "html", ".", "replace", "(", "/", ">", "/", "g", ",", "'&gt;'", ")", ";", "html", "=", "html", ".", "replace", "(", "/", "<", "/", "g", ",", "'&lt;'", ")", ";", "html", "=", "html", ".", "replace", "(", "/", "\"", "/", "g", ",", "'&quot;'", ")", ";", "html", "=", "html", ".", "replace", "(", "/", "'", "/", "g", ",", "'&#039;'", ")", ";", "return", "html", ";", "}" ]
Converts HTML markup to its equivalent representation @param string @return string
[ "Converts", "HTML", "markup", "to", "its", "equivalent", "representation" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/custom.js#L50-L57
train
hashchange/jquery.documentsize
demo/load-event/custom.js
map
function map(obj, callback){ var result = {}; Object.keys(obj).forEach(function(key){ result[key] = callback.call(obj, obj[key], key, obj); }); return result; }
javascript
function map(obj, callback){ var result = {}; Object.keys(obj).forEach(function(key){ result[key] = callback.call(obj, obj[key], key, obj); }); return result; }
[ "function", "map", "(", "obj", ",", "callback", ")", "{", "var", "result", "=", "{", "}", ";", "Object", ".", "keys", "(", "obj", ")", ".", "forEach", "(", "function", "(", "key", ")", "{", "result", "[", "key", "]", "=", "callback", ".", "call", "(", "obj", ",", "obj", "[", "key", "]", ",", "key", ",", "obj", ")", ";", "}", ")", ";", "return", "result", ";", "}" ]
Map for Objects @param Object @return Object
[ "Map", "for", "Objects" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/custom.js#L76-L82
train
hashchange/jquery.documentsize
demo/load-event/custom.js
sanitizeHtml
function sanitizeHtml(html){ var separator = '/'; if(html.constructor === Object){ return map(html, function(value){ var sanitizedHtml = value.split(separator) .map(sanitizeHtml) .join(separator); return sanitizedHtml; }); } else if(html.constructor === Array){ return html.map(sanitizeHtml); } var div = document.createElement('div'); div.appendChild(document.createTextNode(html)); var sanitizedHtml = div.innerHTML.replace(/&amp;/g, '&'); if(html != sanitizedHtml){ return ''; // Blank it } return sanitizedHtml; }
javascript
function sanitizeHtml(html){ var separator = '/'; if(html.constructor === Object){ return map(html, function(value){ var sanitizedHtml = value.split(separator) .map(sanitizeHtml) .join(separator); return sanitizedHtml; }); } else if(html.constructor === Array){ return html.map(sanitizeHtml); } var div = document.createElement('div'); div.appendChild(document.createTextNode(html)); var sanitizedHtml = div.innerHTML.replace(/&amp;/g, '&'); if(html != sanitizedHtml){ return ''; // Blank it } return sanitizedHtml; }
[ "function", "sanitizeHtml", "(", "html", ")", "{", "var", "separator", "=", "'/'", ";", "if", "(", "html", ".", "constructor", "===", "Object", ")", "{", "return", "map", "(", "html", ",", "function", "(", "value", ")", "{", "var", "sanitizedHtml", "=", "value", ".", "split", "(", "separator", ")", ".", "map", "(", "sanitizeHtml", ")", ".", "join", "(", "separator", ")", ";", "return", "sanitizedHtml", ";", "}", ")", ";", "}", "else", "if", "(", "html", ".", "constructor", "===", "Array", ")", "{", "return", "html", ".", "map", "(", "sanitizeHtml", ")", ";", "}", "var", "div", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "div", ".", "appendChild", "(", "document", ".", "createTextNode", "(", "html", ")", ")", ";", "var", "sanitizedHtml", "=", "div", ".", "innerHTML", ".", "replace", "(", "/", "&amp;", "/", "g", ",", "'&'", ")", ";", "if", "(", "html", "!=", "sanitizedHtml", ")", "{", "return", "''", ";", "}", "return", "sanitizedHtml", ";", "}" ]
Use the browser's built-in functionality to quickly and safely escape a string @param string|Array|Object @return string|Array|Object
[ "Use", "the", "browser", "s", "built", "-", "in", "functionality", "to", "quickly", "and", "safely", "escape", "a", "string" ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/custom.js#L91-L114
train
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
_isInView
function _isInView ( elem, config ) { var containerWidth, containerHeight, hTolerance, vTolerance, rect, container = config.container, $container = config.$container, cache = config.cache, elemInView = true; if ( elem === container ) throw new Error( "Invalid container: is the same as the element" ); // When hidden elements are ignored, we check if an element consumes space in the document. And we bail out // immediately if it doesn't. // // The test employed for this works in the vast majority of cases, but there is a limitation. We use offsetWidth // and offsetHeight, which considers the content (incl. borders) but ignores margins. Zero-size content with a // margin might actually consume space sometimes, but it won't be detected (see http://jsbin.com/tiwabo/3). // // That said, the definition of visibility and the actual test are the same as in jQuery :visible. if ( config.excludeHidden && !( elem.offsetWidth > 0 && elem.offsetHeight > 0 ) ) return false; if ( config.useHorizontal ) containerWidth = getNetContainerWidth( $container, config.containerIsWindow, cache ); if ( config.useVertical ) containerHeight = getNetContainerHeight( $container, config.containerIsWindow, cache ); // Convert tolerance to a px value (if given as a percentage) hTolerance = cache.hTolerance !== undefined ? cache.hTolerance : ( cache.hTolerance = config.toleranceType === "add" ? config.tolerance : containerWidth * config.tolerance ); vTolerance = cache.vTolerance !== undefined ? cache.vTolerance : ( cache.vTolerance = config.toleranceType === "add" ? config.tolerance : containerHeight * config.tolerance ); // We can safely use getBoundingClientRect without a fallback. Its core properties (top, left, bottom, right) // are supported on the desktop for ages (IE5+). On mobile, too: supported from Blackberry 6+ (2010), iOS 4 // (2010, iPhone 3GS+), according to the jQuery source comment in $.fn.offset. // // In oldIE (up to IE8), the coordinates were 2px off in each dimension because the "viewport" began at (2,2) of // the window. Can be feature-tested by creating an absolutely positioned div at (0,0) and reading the rect // coordinates. Won't be fixed here because the quirk is too minor to justify the overhead, just for oldIE. // // (See http://stackoverflow.com/a/10231202/508355 and Zakas, Professional Javascript (2012), p. 406) rect = config.borderBox ? elem.getBoundingClientRect() : getContentRect( elem ); if ( ! config.containerIsWindow ) rect = getRelativeRect( rect, $container, cache ); if ( config.partially ) { if ( config.useVertical ) elemInView = rect.top < containerHeight + vTolerance && rect.bottom > -vTolerance; if ( config.useHorizontal ) elemInView = elemInView && rect.left < containerWidth + hTolerance && rect.right > -hTolerance; } else { if ( config.useVertical ) elemInView = rect.top >= -vTolerance && rect.top < containerHeight + vTolerance && rect.bottom > -vTolerance && rect.bottom <= containerHeight + vTolerance; if ( config.useHorizontal ) elemInView = elemInView && rect.left >= -hTolerance && rect.left < containerWidth + hTolerance && rect.right > -hTolerance && rect.right <= containerWidth + hTolerance; } return elemInView; }
javascript
function _isInView ( elem, config ) { var containerWidth, containerHeight, hTolerance, vTolerance, rect, container = config.container, $container = config.$container, cache = config.cache, elemInView = true; if ( elem === container ) throw new Error( "Invalid container: is the same as the element" ); // When hidden elements are ignored, we check if an element consumes space in the document. And we bail out // immediately if it doesn't. // // The test employed for this works in the vast majority of cases, but there is a limitation. We use offsetWidth // and offsetHeight, which considers the content (incl. borders) but ignores margins. Zero-size content with a // margin might actually consume space sometimes, but it won't be detected (see http://jsbin.com/tiwabo/3). // // That said, the definition of visibility and the actual test are the same as in jQuery :visible. if ( config.excludeHidden && !( elem.offsetWidth > 0 && elem.offsetHeight > 0 ) ) return false; if ( config.useHorizontal ) containerWidth = getNetContainerWidth( $container, config.containerIsWindow, cache ); if ( config.useVertical ) containerHeight = getNetContainerHeight( $container, config.containerIsWindow, cache ); // Convert tolerance to a px value (if given as a percentage) hTolerance = cache.hTolerance !== undefined ? cache.hTolerance : ( cache.hTolerance = config.toleranceType === "add" ? config.tolerance : containerWidth * config.tolerance ); vTolerance = cache.vTolerance !== undefined ? cache.vTolerance : ( cache.vTolerance = config.toleranceType === "add" ? config.tolerance : containerHeight * config.tolerance ); // We can safely use getBoundingClientRect without a fallback. Its core properties (top, left, bottom, right) // are supported on the desktop for ages (IE5+). On mobile, too: supported from Blackberry 6+ (2010), iOS 4 // (2010, iPhone 3GS+), according to the jQuery source comment in $.fn.offset. // // In oldIE (up to IE8), the coordinates were 2px off in each dimension because the "viewport" began at (2,2) of // the window. Can be feature-tested by creating an absolutely positioned div at (0,0) and reading the rect // coordinates. Won't be fixed here because the quirk is too minor to justify the overhead, just for oldIE. // // (See http://stackoverflow.com/a/10231202/508355 and Zakas, Professional Javascript (2012), p. 406) rect = config.borderBox ? elem.getBoundingClientRect() : getContentRect( elem ); if ( ! config.containerIsWindow ) rect = getRelativeRect( rect, $container, cache ); if ( config.partially ) { if ( config.useVertical ) elemInView = rect.top < containerHeight + vTolerance && rect.bottom > -vTolerance; if ( config.useHorizontal ) elemInView = elemInView && rect.left < containerWidth + hTolerance && rect.right > -hTolerance; } else { if ( config.useVertical ) elemInView = rect.top >= -vTolerance && rect.top < containerHeight + vTolerance && rect.bottom > -vTolerance && rect.bottom <= containerHeight + vTolerance; if ( config.useHorizontal ) elemInView = elemInView && rect.left >= -hTolerance && rect.left < containerWidth + hTolerance && rect.right > -hTolerance && rect.right <= containerWidth + hTolerance; } return elemInView; }
[ "function", "_isInView", "(", "elem", ",", "config", ")", "{", "var", "containerWidth", ",", "containerHeight", ",", "hTolerance", ",", "vTolerance", ",", "rect", ",", "container", "=", "config", ".", "container", ",", "$container", "=", "config", ".", "$container", ",", "cache", "=", "config", ".", "cache", ",", "elemInView", "=", "true", ";", "if", "(", "elem", "===", "container", ")", "throw", "new", "Error", "(", "\"Invalid container: is the same as the element\"", ")", ";", "if", "(", "config", ".", "excludeHidden", "&&", "!", "(", "elem", ".", "offsetWidth", ">", "0", "&&", "elem", ".", "offsetHeight", ">", "0", ")", ")", "return", "false", ";", "if", "(", "config", ".", "useHorizontal", ")", "containerWidth", "=", "getNetContainerWidth", "(", "$container", ",", "config", ".", "containerIsWindow", ",", "cache", ")", ";", "if", "(", "config", ".", "useVertical", ")", "containerHeight", "=", "getNetContainerHeight", "(", "$container", ",", "config", ".", "containerIsWindow", ",", "cache", ")", ";", "hTolerance", "=", "cache", ".", "hTolerance", "!==", "undefined", "?", "cache", ".", "hTolerance", ":", "(", "cache", ".", "hTolerance", "=", "config", ".", "toleranceType", "===", "\"add\"", "?", "config", ".", "tolerance", ":", "containerWidth", "*", "config", ".", "tolerance", ")", ";", "vTolerance", "=", "cache", ".", "vTolerance", "!==", "undefined", "?", "cache", ".", "vTolerance", ":", "(", "cache", ".", "vTolerance", "=", "config", ".", "toleranceType", "===", "\"add\"", "?", "config", ".", "tolerance", ":", "containerHeight", "*", "config", ".", "tolerance", ")", ";", "rect", "=", "config", ".", "borderBox", "?", "elem", ".", "getBoundingClientRect", "(", ")", ":", "getContentRect", "(", "elem", ")", ";", "if", "(", "!", "config", ".", "containerIsWindow", ")", "rect", "=", "getRelativeRect", "(", "rect", ",", "$container", ",", "cache", ")", ";", "if", "(", "config", ".", "partially", ")", "{", "if", "(", "config", ".", "useVertical", ")", "elemInView", "=", "rect", ".", "top", "<", "containerHeight", "+", "vTolerance", "&&", "rect", ".", "bottom", ">", "-", "vTolerance", ";", "if", "(", "config", ".", "useHorizontal", ")", "elemInView", "=", "elemInView", "&&", "rect", ".", "left", "<", "containerWidth", "+", "hTolerance", "&&", "rect", ".", "right", ">", "-", "hTolerance", ";", "}", "else", "{", "if", "(", "config", ".", "useVertical", ")", "elemInView", "=", "rect", ".", "top", ">=", "-", "vTolerance", "&&", "rect", ".", "top", "<", "containerHeight", "+", "vTolerance", "&&", "rect", ".", "bottom", ">", "-", "vTolerance", "&&", "rect", ".", "bottom", "<=", "containerHeight", "+", "vTolerance", ";", "if", "(", "config", ".", "useHorizontal", ")", "elemInView", "=", "elemInView", "&&", "rect", ".", "left", ">=", "-", "hTolerance", "&&", "rect", ".", "left", "<", "containerWidth", "+", "hTolerance", "&&", "rect", ".", "right", ">", "-", "hTolerance", "&&", "rect", ".", "right", "<=", "containerWidth", "+", "hTolerance", ";", "}", "return", "elemInView", ";", "}" ]
Returns if an element is in view, with regard to a given configuration. The configuration is built with _prepareConfig(). @param {HTMLElement} elem @param {Object} config @param {HTMLElement|Window} config.container @param {jQuery} config.$container @param {boolean} config.containerIsWindow @param {Object} config.cache @param {boolean} config.useHorizontal @param {boolean} config.useVertical @param {boolean} config.partially @param {boolean} config.excludeHidden @param {boolean} config.borderBox @param {number} config.tolerance @param {string} config.toleranceType @returns {boolean}
[ "Returns", "if", "an", "element", "is", "in", "view", "with", "regard", "to", "a", "given", "configuration", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L412-L462
train
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
getRelativeRect
function getRelativeRect ( rect, $container, cache ) { var containerPaddingRectRoot; if ( cache && cache.containerPaddingRectRoot ) { containerPaddingRectRoot = cache.containerPaddingRectRoot; } else { // gBCR coordinates enclose padding, and leave out margin. That is perfect for scrolling because // // - padding scrolls (ie,o it is part of the scrollable area, and gBCR puts it inside) // - margin doesn't scroll (ie, it pushes the scrollable area to another position, and gBCR records that) // // Borders, however, don't scroll, so they are not part of the scrollable area, but gBCR puts them inside. // // (See http://jsbin.com/pivata/10 for an extensive test of gBCR behaviour.) containerPaddingRectRoot = getPaddingRectRoot( $container[0] ); // Cache the calculations if ( cache ) cache.containerPaddingRectRoot = containerPaddingRectRoot; } return { top: rect.top - containerPaddingRectRoot.top, bottom: rect.bottom - containerPaddingRectRoot.top, left: rect.left - containerPaddingRectRoot.left, right: rect.right - containerPaddingRectRoot.left }; }
javascript
function getRelativeRect ( rect, $container, cache ) { var containerPaddingRectRoot; if ( cache && cache.containerPaddingRectRoot ) { containerPaddingRectRoot = cache.containerPaddingRectRoot; } else { // gBCR coordinates enclose padding, and leave out margin. That is perfect for scrolling because // // - padding scrolls (ie,o it is part of the scrollable area, and gBCR puts it inside) // - margin doesn't scroll (ie, it pushes the scrollable area to another position, and gBCR records that) // // Borders, however, don't scroll, so they are not part of the scrollable area, but gBCR puts them inside. // // (See http://jsbin.com/pivata/10 for an extensive test of gBCR behaviour.) containerPaddingRectRoot = getPaddingRectRoot( $container[0] ); // Cache the calculations if ( cache ) cache.containerPaddingRectRoot = containerPaddingRectRoot; } return { top: rect.top - containerPaddingRectRoot.top, bottom: rect.bottom - containerPaddingRectRoot.top, left: rect.left - containerPaddingRectRoot.left, right: rect.right - containerPaddingRectRoot.left }; }
[ "function", "getRelativeRect", "(", "rect", ",", "$container", ",", "cache", ")", "{", "var", "containerPaddingRectRoot", ";", "if", "(", "cache", "&&", "cache", ".", "containerPaddingRectRoot", ")", "{", "containerPaddingRectRoot", "=", "cache", ".", "containerPaddingRectRoot", ";", "}", "else", "{", "containerPaddingRectRoot", "=", "getPaddingRectRoot", "(", "$container", "[", "0", "]", ")", ";", "if", "(", "cache", ")", "cache", ".", "containerPaddingRectRoot", "=", "containerPaddingRectRoot", ";", "}", "return", "{", "top", ":", "rect", ".", "top", "-", "containerPaddingRectRoot", ".", "top", ",", "bottom", ":", "rect", ".", "bottom", "-", "containerPaddingRectRoot", ".", "top", ",", "left", ":", "rect", ".", "left", "-", "containerPaddingRectRoot", ".", "left", ",", "right", ":", "rect", ".", "right", "-", "containerPaddingRectRoot", ".", "left", "}", ";", "}" ]
Gets the TextRectangle coordinates relative to a container element. Do not call if the container is a window (redundant) or a document. Both calls would fail.
[ "Gets", "the", "TextRectangle", "coordinates", "relative", "to", "a", "container", "element", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L469-L498
train
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
getContentRect
function getContentRect( elem ) { var rect = elem.getBoundingClientRect(), props = getCss( elem, [ "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft" ], { toFloat: true } ); return { top: rect.top + props.paddingTop + props.borderTopWidth, right: rect.right - ( props.paddingRight + props.borderRightWidth ), bottom: rect.bottom - ( props.paddingBottom + props.borderBottomWidth ), left: rect.left + props.paddingLeft + props.borderLeftWidth }; }
javascript
function getContentRect( elem ) { var rect = elem.getBoundingClientRect(), props = getCss( elem, [ "borderTopWidth", "borderRightWidth", "borderBottomWidth", "borderLeftWidth", "paddingTop", "paddingRight", "paddingBottom", "paddingLeft" ], { toFloat: true } ); return { top: rect.top + props.paddingTop + props.borderTopWidth, right: rect.right - ( props.paddingRight + props.borderRightWidth ), bottom: rect.bottom - ( props.paddingBottom + props.borderBottomWidth ), left: rect.left + props.paddingLeft + props.borderLeftWidth }; }
[ "function", "getContentRect", "(", "elem", ")", "{", "var", "rect", "=", "elem", ".", "getBoundingClientRect", "(", ")", ",", "props", "=", "getCss", "(", "elem", ",", "[", "\"borderTopWidth\"", ",", "\"borderRightWidth\"", ",", "\"borderBottomWidth\"", ",", "\"borderLeftWidth\"", ",", "\"paddingTop\"", ",", "\"paddingRight\"", ",", "\"paddingBottom\"", ",", "\"paddingLeft\"", "]", ",", "{", "toFloat", ":", "true", "}", ")", ";", "return", "{", "top", ":", "rect", ".", "top", "+", "props", ".", "paddingTop", "+", "props", ".", "borderTopWidth", ",", "right", ":", "rect", ".", "right", "-", "(", "props", ".", "paddingRight", "+", "props", ".", "borderRightWidth", ")", ",", "bottom", ":", "rect", ".", "bottom", "-", "(", "props", ".", "paddingBottom", "+", "props", ".", "borderBottomWidth", ")", ",", "left", ":", "rect", ".", "left", "+", "props", ".", "paddingLeft", "+", "props", ".", "borderLeftWidth", "}", ";", "}" ]
Calculates the rect of the content-box. Similar to getBoundingClientRect, but excludes padding and borders - and is much slower. @param {HTMLElement} elem @returns {ClientRect}
[ "Calculates", "the", "rect", "of", "the", "content", "-", "box", ".", "Similar", "to", "getBoundingClientRect", "but", "excludes", "padding", "and", "borders", "-", "and", "is", "much", "slower", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L507-L521
train
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
wrapContainer
function wrapContainer ( container ) { var $container, isJquery = container instanceof $; if ( ! isJquery && ! $.isWindow( container ) && ! container.nodeType && ! isString( container ) ) throw new Error( 'Invalid container: not a window, node, jQuery object or selector string' ); $container = isJquery ? container : container === root ? $root : $( container ); if ( !$container.length ) throw new Error( 'Invalid container: empty jQuery object' ); container = $container[0]; if ( container.nodeType === 9 ) { // Document is passed in, transform to window $container = wrapContainer( container.defaultView || container.parentWindow ); } else if ( container.nodeType === 1 && container.tagName.toLowerCase() === "iframe" ) { // IFrame element is passed in, transform to IFrame content window $container = wrapContainer( container.contentWindow ); } // Check if the container matches the requirements if ( !$.isWindow( $container[0] ) && $container.css( "overflow" ) === "visible" ) throw new Error( 'Invalid container: is set to overflow:visible. Containers must have the ability to obscure some of their content, otherwise the in-view test is pointless. Containers must be set to overflow:scroll/auto/hide, or be a window (or document, or iframe, as proxies for a window)' ); return $container; }
javascript
function wrapContainer ( container ) { var $container, isJquery = container instanceof $; if ( ! isJquery && ! $.isWindow( container ) && ! container.nodeType && ! isString( container ) ) throw new Error( 'Invalid container: not a window, node, jQuery object or selector string' ); $container = isJquery ? container : container === root ? $root : $( container ); if ( !$container.length ) throw new Error( 'Invalid container: empty jQuery object' ); container = $container[0]; if ( container.nodeType === 9 ) { // Document is passed in, transform to window $container = wrapContainer( container.defaultView || container.parentWindow ); } else if ( container.nodeType === 1 && container.tagName.toLowerCase() === "iframe" ) { // IFrame element is passed in, transform to IFrame content window $container = wrapContainer( container.contentWindow ); } // Check if the container matches the requirements if ( !$.isWindow( $container[0] ) && $container.css( "overflow" ) === "visible" ) throw new Error( 'Invalid container: is set to overflow:visible. Containers must have the ability to obscure some of their content, otherwise the in-view test is pointless. Containers must be set to overflow:scroll/auto/hide, or be a window (or document, or iframe, as proxies for a window)' ); return $container; }
[ "function", "wrapContainer", "(", "container", ")", "{", "var", "$container", ",", "isJquery", "=", "container", "instanceof", "$", ";", "if", "(", "!", "isJquery", "&&", "!", "$", ".", "isWindow", "(", "container", ")", "&&", "!", "container", ".", "nodeType", "&&", "!", "isString", "(", "container", ")", ")", "throw", "new", "Error", "(", "'Invalid container: not a window, node, jQuery object or selector string'", ")", ";", "$container", "=", "isJquery", "?", "container", ":", "container", "===", "root", "?", "$root", ":", "$", "(", "container", ")", ";", "if", "(", "!", "$container", ".", "length", ")", "throw", "new", "Error", "(", "'Invalid container: empty jQuery object'", ")", ";", "container", "=", "$container", "[", "0", "]", ";", "if", "(", "container", ".", "nodeType", "===", "9", ")", "{", "$container", "=", "wrapContainer", "(", "container", ".", "defaultView", "||", "container", ".", "parentWindow", ")", ";", "}", "else", "if", "(", "container", ".", "nodeType", "===", "1", "&&", "container", ".", "tagName", ".", "toLowerCase", "(", ")", "===", "\"iframe\"", ")", "{", "$container", "=", "wrapContainer", "(", "container", ".", "contentWindow", ")", ";", "}", "if", "(", "!", "$", ".", "isWindow", "(", "$container", "[", "0", "]", ")", "&&", "$container", ".", "css", "(", "\"overflow\"", ")", "===", "\"visible\"", ")", "throw", "new", "Error", "(", "'Invalid container: is set to overflow:visible. Containers must have the ability to obscure some of their content, otherwise the in-view test is pointless. Containers must be set to overflow:scroll/auto/hide, or be a window (or document, or iframe, as proxies for a window)'", ")", ";", "return", "$container", ";", "}" ]
Establishes the container and returns it in a jQuery wrapper. Resolves and normalizes the input, which may be a document, HTMLElement, window, or selector string. Corrects likely mistakes, such as passing in a document or an iframe, rather than the corresponding window. @param {Window|Document|HTMLElement|HTMLIFrameElement|jQuery|string} container @returns {jQuery}
[ "Establishes", "the", "container", "and", "returns", "it", "in", "a", "jQuery", "wrapper", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L795-L819
train
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
checkOptions
function checkOptions ( opts ) { var isNum, isNumWithUnit; if ( opts.direction && !( opts.direction === 'vertical' || opts.direction === 'horizontal' || opts.direction === 'both' ) ) { throw new Error( 'Invalid option value: direction = "' + opts.direction + '"' ); } if ( opts.box && !( opts.box === 'border-box' || opts.box === 'content-box' ) ) { throw new Error( 'Invalid option value: box = "' + opts.box + '"' ); } if ( opts.tolerance !== undefined ) { isNum = isNumber( opts.tolerance ); isNumWithUnit = isString( opts.tolerance ) && ( /^[+-]?\d*\.?\d+(px|%)?$/.test( opts.tolerance ) ); if ( ! ( isNum || isNumWithUnit ) ) throw new Error( 'Invalid option value: tolerance = "' + opts.tolerance + '"' ); } }
javascript
function checkOptions ( opts ) { var isNum, isNumWithUnit; if ( opts.direction && !( opts.direction === 'vertical' || opts.direction === 'horizontal' || opts.direction === 'both' ) ) { throw new Error( 'Invalid option value: direction = "' + opts.direction + '"' ); } if ( opts.box && !( opts.box === 'border-box' || opts.box === 'content-box' ) ) { throw new Error( 'Invalid option value: box = "' + opts.box + '"' ); } if ( opts.tolerance !== undefined ) { isNum = isNumber( opts.tolerance ); isNumWithUnit = isString( opts.tolerance ) && ( /^[+-]?\d*\.?\d+(px|%)?$/.test( opts.tolerance ) ); if ( ! ( isNum || isNumWithUnit ) ) throw new Error( 'Invalid option value: tolerance = "' + opts.tolerance + '"' ); } }
[ "function", "checkOptions", "(", "opts", ")", "{", "var", "isNum", ",", "isNumWithUnit", ";", "if", "(", "opts", ".", "direction", "&&", "!", "(", "opts", ".", "direction", "===", "'vertical'", "||", "opts", ".", "direction", "===", "'horizontal'", "||", "opts", ".", "direction", "===", "'both'", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid option value: direction = \"'", "+", "opts", ".", "direction", "+", "'\"'", ")", ";", "}", "if", "(", "opts", ".", "box", "&&", "!", "(", "opts", ".", "box", "===", "'border-box'", "||", "opts", ".", "box", "===", "'content-box'", ")", ")", "{", "throw", "new", "Error", "(", "'Invalid option value: box = \"'", "+", "opts", ".", "box", "+", "'\"'", ")", ";", "}", "if", "(", "opts", ".", "tolerance", "!==", "undefined", ")", "{", "isNum", "=", "isNumber", "(", "opts", ".", "tolerance", ")", ";", "isNumWithUnit", "=", "isString", "(", "opts", ".", "tolerance", ")", "&&", "(", "/", "^[+-]?\\d*\\.?\\d+(px|%)?$", "/", ".", "test", "(", "opts", ".", "tolerance", ")", ")", ";", "if", "(", "!", "(", "isNum", "||", "isNumWithUnit", ")", ")", "throw", "new", "Error", "(", "'Invalid option value: tolerance = \"'", "+", "opts", ".", "tolerance", "+", "'\"'", ")", ";", "}", "}" ]
Spots likely option mistakes and throws appropriate errors. @param {Object} opts
[ "Spots", "likely", "option", "mistakes", "and", "throws", "appropriate", "errors", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L854-L871
train
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
getContainerScrollbarWidths
function getContainerScrollbarWidths ( $container, cache ) { var containerScrollbarWidths; if ( cache && cache.containerScrollbarWidths ) { containerScrollbarWidths = cache.containerScrollbarWidths; } else { containerScrollbarWidths = effectiveScrollbarWith( $container ); if ( cache ) cache.containerScrollbarWidths = containerScrollbarWidths; } return containerScrollbarWidths; }
javascript
function getContainerScrollbarWidths ( $container, cache ) { var containerScrollbarWidths; if ( cache && cache.containerScrollbarWidths ) { containerScrollbarWidths = cache.containerScrollbarWidths; } else { containerScrollbarWidths = effectiveScrollbarWith( $container ); if ( cache ) cache.containerScrollbarWidths = containerScrollbarWidths; } return containerScrollbarWidths; }
[ "function", "getContainerScrollbarWidths", "(", "$container", ",", "cache", ")", "{", "var", "containerScrollbarWidths", ";", "if", "(", "cache", "&&", "cache", ".", "containerScrollbarWidths", ")", "{", "containerScrollbarWidths", "=", "cache", ".", "containerScrollbarWidths", ";", "}", "else", "{", "containerScrollbarWidths", "=", "effectiveScrollbarWith", "(", "$container", ")", ";", "if", "(", "cache", ")", "cache", ".", "containerScrollbarWidths", "=", "containerScrollbarWidths", ";", "}", "return", "containerScrollbarWidths", ";", "}" ]
Gets the effective scroll bar widths of a given container. Makes use of caching if a cache object is provided. @param {jQuery} $container @param {Object} [cache] @returns {Object}
[ "Gets", "the", "effective", "scroll", "bar", "widths", "of", "a", "given", "container", ".", "Makes", "use", "of", "caching", "if", "a", "cache", "object", "is", "provided", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L930-L941
train
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
getCss
function getCss ( elem, properties, opts ) { var i, length, name, props = {}, _window = ( elem.ownerDocument.defaultView || elem.ownerDocument.parentWindow ), computedStyles = _useGetComputedStyle ? _window.getComputedStyle( elem, null ) : elem.currentStyle; opts || ( opts = {} ); if ( ! $.isArray( properties ) ) properties = [ properties ]; length = properties.length; for ( i = 0; i < length; i++ ) { name = properties[i]; props[name] = $.css( elem, name, false, computedStyles ); if ( opts.toLowerCase && props[name] && props[name].toLowerCase ) props[name] = props[name].toLowerCase(); if ( opts.toFloat ) props[name] = parseFloat( props[name] ); } return props; }
javascript
function getCss ( elem, properties, opts ) { var i, length, name, props = {}, _window = ( elem.ownerDocument.defaultView || elem.ownerDocument.parentWindow ), computedStyles = _useGetComputedStyle ? _window.getComputedStyle( elem, null ) : elem.currentStyle; opts || ( opts = {} ); if ( ! $.isArray( properties ) ) properties = [ properties ]; length = properties.length; for ( i = 0; i < length; i++ ) { name = properties[i]; props[name] = $.css( elem, name, false, computedStyles ); if ( opts.toLowerCase && props[name] && props[name].toLowerCase ) props[name] = props[name].toLowerCase(); if ( opts.toFloat ) props[name] = parseFloat( props[name] ); } return props; }
[ "function", "getCss", "(", "elem", ",", "properties", ",", "opts", ")", "{", "var", "i", ",", "length", ",", "name", ",", "props", "=", "{", "}", ",", "_window", "=", "(", "elem", ".", "ownerDocument", ".", "defaultView", "||", "elem", ".", "ownerDocument", ".", "parentWindow", ")", ",", "computedStyles", "=", "_useGetComputedStyle", "?", "_window", ".", "getComputedStyle", "(", "elem", ",", "null", ")", ":", "elem", ".", "currentStyle", ";", "opts", "||", "(", "opts", "=", "{", "}", ")", ";", "if", "(", "!", "$", ".", "isArray", "(", "properties", ")", ")", "properties", "=", "[", "properties", "]", ";", "length", "=", "properties", ".", "length", ";", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "name", "=", "properties", "[", "i", "]", ";", "props", "[", "name", "]", "=", "$", ".", "css", "(", "elem", ",", "name", ",", "false", ",", "computedStyles", ")", ";", "if", "(", "opts", ".", "toLowerCase", "&&", "props", "[", "name", "]", "&&", "props", "[", "name", "]", ".", "toLowerCase", ")", "props", "[", "name", "]", "=", "props", "[", "name", "]", ".", "toLowerCase", "(", ")", ";", "if", "(", "opts", ".", "toFloat", ")", "props", "[", "name", "]", "=", "parseFloat", "(", "props", "[", "name", "]", ")", ";", "}", "return", "props", ";", "}" ]
Returns the computed style for a property, or an array of properties, as a hash. Building a CSS properties hash this way can be significantly faster than the more convenient, conventional jQuery approach, $( elem ).css( propertiesArray ). ATTN ==== We are using an internal jQuery API here: $.css(). The current signature was introduced in jQuery 1.9.0. It may break without warning with any change of the minor version. For that reason, the $.css API is monitored by the tests in api.jquery.css.spec.js which verify that it works as expected. @param {HTMLElement} elem @param {string|string[]} properties @param {Object} [opts] @param {boolean} [opts.toLowerCase=false] ensures return values in lower case @param {boolean} [opts.toFloat=false] converts return values to numbers, using parseFloat @returns {Object} property names and their values
[ "Returns", "the", "computed", "style", "for", "a", "property", "or", "an", "array", "of", "properties", "as", "a", "hash", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L984-L1003
train
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
isIOS
function isIOS () { if ( _isIOS === undefined ) _isIOS = (/iPad|iPhone|iPod/g).test( navigator.userAgent ); return _isIOS; }
javascript
function isIOS () { if ( _isIOS === undefined ) _isIOS = (/iPad|iPhone|iPod/g).test( navigator.userAgent ); return _isIOS; }
[ "function", "isIOS", "(", ")", "{", "if", "(", "_isIOS", "===", "undefined", ")", "_isIOS", "=", "(", "/", "iPad|iPhone|iPod", "/", "g", ")", ".", "test", "(", "navigator", ".", "userAgent", ")", ";", "return", "_isIOS", ";", "}" ]
Detects if the browser is on iOS. Works for Safari as well as other browsers, say, Chrome on iOS. Required for some iOS behaviour which can't be feature-detected in any way. @returns {boolean}
[ "Detects", "if", "the", "browser", "is", "on", "iOS", ".", "Works", "for", "Safari", "as", "well", "as", "other", "browsers", "say", "Chrome", "on", "iOS", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L1041-L1044
train
hashchange/jquery.documentsize
demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js
toFloat
function toFloat ( object ) { var transformed = {}; $.map( object, function ( value, key ) { transformed[key] = parseFloat( value ); } ); return transformed; }
javascript
function toFloat ( object ) { var transformed = {}; $.map( object, function ( value, key ) { transformed[key] = parseFloat( value ); } ); return transformed; }
[ "function", "toFloat", "(", "object", ")", "{", "var", "transformed", "=", "{", "}", ";", "$", ".", "map", "(", "object", ",", "function", "(", "value", ",", "key", ")", "{", "transformed", "[", "key", "]", "=", "parseFloat", "(", "value", ")", ";", "}", ")", ";", "return", "transformed", ";", "}" ]
Calls parseFloat on each value. Useful for removing units from numeric values. @param {Object} object @returns {Object}
[ "Calls", "parseFloat", "on", "each", "value", ".", "Useful", "for", "removing", "units", "from", "numeric", "values", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/demo/load-event/js/libs/jquery.isinview/jquery.isinview-1.0.3.js#L1052-L1060
train
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
createChildWindow
function createChildWindow ( readyDfd, size ) { var childWindow, width, height, sizedDefaultProps = ",top=0,left=0,location=no,menubar=no,status=no,toolbar=no,resizeable=yes,scrollbars=yes"; if ( size ) { width = size === "parent" ? window.document.documentElement.clientWidth : size.width; height = size === "parent" ? window.document.documentElement.clientHeight : size.height; childWindow = window.open( "", "", "width=" + width + ",height=" + height + sizedDefaultProps ); } else { childWindow = window.open(); } if ( childWindow ) { // Setting the document content (using plain JS - jQuery can't write an entire HTML document, including the // doctype and <head> tags). childWindow.document.open(); childWindow.document.write( '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<title></title>\n</head>\n<body>\n</body>\n</html>' ); childWindow.document.close(); } if ( readyDfd ) { if ( ! varExists( $ ) ) throw new Error( "`$` variable is not available. For using a readyDfd, jQuery (or a compatible library) must be loaded" ); if ( childWindow && childWindow.document ) { $( childWindow.document ).ready ( function () { windowSizeReady( childWindow, readyDfd ); } ); } else { readyDfd.reject(); } } return childWindow; }
javascript
function createChildWindow ( readyDfd, size ) { var childWindow, width, height, sizedDefaultProps = ",top=0,left=0,location=no,menubar=no,status=no,toolbar=no,resizeable=yes,scrollbars=yes"; if ( size ) { width = size === "parent" ? window.document.documentElement.clientWidth : size.width; height = size === "parent" ? window.document.documentElement.clientHeight : size.height; childWindow = window.open( "", "", "width=" + width + ",height=" + height + sizedDefaultProps ); } else { childWindow = window.open(); } if ( childWindow ) { // Setting the document content (using plain JS - jQuery can't write an entire HTML document, including the // doctype and <head> tags). childWindow.document.open(); childWindow.document.write( '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<title></title>\n</head>\n<body>\n</body>\n</html>' ); childWindow.document.close(); } if ( readyDfd ) { if ( ! varExists( $ ) ) throw new Error( "`$` variable is not available. For using a readyDfd, jQuery (or a compatible library) must be loaded" ); if ( childWindow && childWindow.document ) { $( childWindow.document ).ready ( function () { windowSizeReady( childWindow, readyDfd ); } ); } else { readyDfd.reject(); } } return childWindow; }
[ "function", "createChildWindow", "(", "readyDfd", ",", "size", ")", "{", "var", "childWindow", ",", "width", ",", "height", ",", "sizedDefaultProps", "=", "\",top=0,left=0,location=no,menubar=no,status=no,toolbar=no,resizeable=yes,scrollbars=yes\"", ";", "if", "(", "size", ")", "{", "width", "=", "size", "===", "\"parent\"", "?", "window", ".", "document", ".", "documentElement", ".", "clientWidth", ":", "size", ".", "width", ";", "height", "=", "size", "===", "\"parent\"", "?", "window", ".", "document", ".", "documentElement", ".", "clientHeight", ":", "size", ".", "height", ";", "childWindow", "=", "window", ".", "open", "(", "\"\"", ",", "\"\"", ",", "\"width=\"", "+", "width", "+", "\",height=\"", "+", "height", "+", "sizedDefaultProps", ")", ";", "}", "else", "{", "childWindow", "=", "window", ".", "open", "(", ")", ";", "}", "if", "(", "childWindow", ")", "{", "childWindow", ".", "document", ".", "open", "(", ")", ";", "childWindow", ".", "document", ".", "write", "(", "'<!DOCTYPE html>\\n<html>\\n<head>\\n<meta charset=\"UTF-8\">\\n<title></title>\\n</head>\\n<body>\\n</body>\\n</html>'", ")", ";", "\\n", "}", "\\n", "\\n", "}" ]
Creates a child window, including a document with an HTML 5 doctype, UFT-8 charset, head, title, and body tags. Returns the handle, or undefined if window creation fails. Optionally accepts a jQuery Deferred. The deferred is resolved when the document in the child window is ready and the window has expanded to its intended size. If the child window can't be created, the deferred is rejected. (For this, jQuery needs to be loaded, obviously.) The size can also be specified. If so, the new window is opened with minimal browser chrome (no menu, location, and status bars) and is positioned at the top left of the viewport. By default, the window is opened with the default settings of the browser (usually with browser chrome, and not exactly in the top left corner). If the child window can't be created, a pop-up blocker usually prevents it. Pop-up blockers are active by default in most browsers - Chrome, for instance. @param {jQuery.Deferred} [readyDfd] @param {Object|string} [size] "parent" (same size as parent window), or size object @param {number} [size.width] @param {number} [size.height] @returns {Window|undefined} the window handle
[ "Creates", "a", "child", "window", "including", "a", "document", "with", "an", "HTML", "5", "doctype", "UFT", "-", "8", "charset", "head", "title", "and", "body", "tags", ".", "Returns", "the", "handle", "or", "undefined", "if", "window", "creation", "fails", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L29-L69
train
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
createIframe
function createIframe ( opts ) { var parent = ( opts && opts.parent ) ? ( varExists( $ ) && opts.parent instanceof $ ) ? opts.parent[0] : opts.parent : document.body, _document = parent.ownerDocument, iframe = _document.createElement( "iframe" ); opts || ( opts = {} ); if ( opts.elementStyles ) iframe.style.cssText = ensureTrailingSemicolon( opts.elementStyles ); iframe.frameborder = "0"; if ( opts.prepend ) { parent.insertBefore( iframe, parent.firstChild ); } else { parent.appendChild( iframe ); } iframe.src = 'about:blank'; createIframeDocument( iframe, opts.documentStyles ); return iframe; }
javascript
function createIframe ( opts ) { var parent = ( opts && opts.parent ) ? ( varExists( $ ) && opts.parent instanceof $ ) ? opts.parent[0] : opts.parent : document.body, _document = parent.ownerDocument, iframe = _document.createElement( "iframe" ); opts || ( opts = {} ); if ( opts.elementStyles ) iframe.style.cssText = ensureTrailingSemicolon( opts.elementStyles ); iframe.frameborder = "0"; if ( opts.prepend ) { parent.insertBefore( iframe, parent.firstChild ); } else { parent.appendChild( iframe ); } iframe.src = 'about:blank'; createIframeDocument( iframe, opts.documentStyles ); return iframe; }
[ "function", "createIframe", "(", "opts", ")", "{", "var", "parent", "=", "(", "opts", "&&", "opts", ".", "parent", ")", "?", "(", "varExists", "(", "$", ")", "&&", "opts", ".", "parent", "instanceof", "$", ")", "?", "opts", ".", "parent", "[", "0", "]", ":", "opts", ".", "parent", ":", "document", ".", "body", ",", "_document", "=", "parent", ".", "ownerDocument", ",", "iframe", "=", "_document", ".", "createElement", "(", "\"iframe\"", ")", ";", "opts", "||", "(", "opts", "=", "{", "}", ")", ";", "if", "(", "opts", ".", "elementStyles", ")", "iframe", ".", "style", ".", "cssText", "=", "ensureTrailingSemicolon", "(", "opts", ".", "elementStyles", ")", ";", "iframe", ".", "frameborder", "=", "\"0\"", ";", "if", "(", "opts", ".", "prepend", ")", "{", "parent", ".", "insertBefore", "(", "iframe", ",", "parent", ".", "firstChild", ")", ";", "}", "else", "{", "parent", ".", "appendChild", "(", "iframe", ")", ";", "}", "iframe", ".", "src", "=", "'about:blank'", ";", "createIframeDocument", "(", "iframe", ",", "opts", ".", "documentStyles", ")", ";", "return", "iframe", ";", "}" ]
Creates an iframe with an HTML5 doctype and UTF-8 encoding. Appends it to the body, or to another specified parent element. Alternatively, the iframe can be prepended to the parent. The iframe element can be styled as it is created, before it is added to the DOM, e.g. to keep it out of view. Likewise, styles can be written into the iframe document as it is created, providing it with defaults from the get-go. @param {Object} [opts] @param {HTMLElement|jQuery} [opts.parent=document.body] the parent element to which the iframe is appended @param {boolean} [opts.prepend=false] if true, the iframe gets prepended to the parent, rather than appended @param {string} [opts.elementStyles] cssText string, styles the iframe _element_ @param {string} [opts.documentStyles] cssText string of entire rules, styles the iframe document, e.g. "html, body { overflow: hidden; } div.foo { margin: 2em; }" @returns {HTMLIFrameElement}
[ "Creates", "an", "iframe", "with", "an", "HTML5", "doctype", "and", "UTF", "-", "8", "encoding", ".", "Appends", "it", "to", "the", "body", "or", "to", "another", "specified", "parent", "element", ".", "Alternatively", "the", "iframe", "can", "be", "prepended", "to", "the", "parent", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L87-L107
train
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
createIframeDocument
function createIframeDocument ( iframe, documentStyles ) { if ( varExists( $ ) && iframe instanceof $ ) iframe = iframe[0]; if ( ! iframe.ownerDocument.body.contains( iframe ) ) throw new Error( "The iframe has not been appended to the DOM, or is not a descendant of the body element. Can't create an iframe content document." ); if ( ! iframe.contentDocument ) throw new Error( "Cannot access the iframe content document. Check for cross-domain policy restrictions." ); documentStyles = documentStyles ? '<style type="text/css">\n' + documentStyles + '\n</style>\n' : ""; iframe.contentDocument.write( '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<title></title>\n' + documentStyles + '</head>\n<body>\n</body>\n</html>' ); return iframe.contentDocument; }
javascript
function createIframeDocument ( iframe, documentStyles ) { if ( varExists( $ ) && iframe instanceof $ ) iframe = iframe[0]; if ( ! iframe.ownerDocument.body.contains( iframe ) ) throw new Error( "The iframe has not been appended to the DOM, or is not a descendant of the body element. Can't create an iframe content document." ); if ( ! iframe.contentDocument ) throw new Error( "Cannot access the iframe content document. Check for cross-domain policy restrictions." ); documentStyles = documentStyles ? '<style type="text/css">\n' + documentStyles + '\n</style>\n' : ""; iframe.contentDocument.write( '<!DOCTYPE html>\n<html>\n<head>\n<meta charset="UTF-8">\n<title></title>\n' + documentStyles + '</head>\n<body>\n</body>\n</html>' ); return iframe.contentDocument; }
[ "function", "createIframeDocument", "(", "iframe", ",", "documentStyles", ")", "{", "if", "(", "varExists", "(", "$", ")", "&&", "iframe", "instanceof", "$", ")", "iframe", "=", "iframe", "[", "0", "]", ";", "if", "(", "!", "iframe", ".", "ownerDocument", ".", "body", ".", "contains", "(", "iframe", ")", ")", "throw", "new", "Error", "(", "\"The iframe has not been appended to the DOM, or is not a descendant of the body element. Can't create an iframe content document.\"", ")", ";", "if", "(", "!", "iframe", ".", "contentDocument", ")", "throw", "new", "Error", "(", "\"Cannot access the iframe content document. Check for cross-domain policy restrictions.\"", ")", ";", "documentStyles", "=", "documentStyles", "?", "'<style type=\"text/css\">\\n'", "+", "\\n", "+", "documentStyles", ":", "'\\n</style>\\n'", ";", "\\n", "\\n", "}" ]
Creates an iframe document with an HTML5 doctype and UTF-8 encoding. The iframe element MUST have been appended to the DOM by the time this function is called, and it must be a descendant of the body element. A document inside an iframe can only be created when these conditions are met. @param {HTMLIFrameElement|jQuery} iframe @param {string} [documentStyles] cssText string of CSS rules, styles the iframe document, e.g. "html, body { overflow: hidden; } div.foo { margin: 2em; }" @returns {Document}
[ "Creates", "an", "iframe", "document", "with", "an", "HTML5", "doctype", "and", "UTF", "-", "8", "encoding", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L120-L130
train
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
windowSizeReady
function windowSizeReady ( queriedWindow, readyDfd, interval ) { if ( !varExists( $ ) ) throw new Error( "This method uses jQuery deferreds, but the $ variable is not available" ); if ( queriedWindow instanceof $ ) queriedWindow = queriedWindow[0]; readyDfd || ( readyDfd = $.Deferred() ); $( queriedWindow.document ).ready( function () { var documentElement = queriedWindow.document.documentElement, lastSize = { width: documentElement.clientWidth, height: documentElement.clientHeight }, repeater = setInterval( function () { var width = documentElement.clientWidth, height = documentElement.clientHeight, isStable = width > 0 && height > 0 && width === lastSize.width && height === lastSize.height; if ( isStable ) { clearInterval( repeater ); readyDfd.resolve(); } else { lastSize = { width: width, height: height }; } }, interval || 100 ); } ); return readyDfd; }
javascript
function windowSizeReady ( queriedWindow, readyDfd, interval ) { if ( !varExists( $ ) ) throw new Error( "This method uses jQuery deferreds, but the $ variable is not available" ); if ( queriedWindow instanceof $ ) queriedWindow = queriedWindow[0]; readyDfd || ( readyDfd = $.Deferred() ); $( queriedWindow.document ).ready( function () { var documentElement = queriedWindow.document.documentElement, lastSize = { width: documentElement.clientWidth, height: documentElement.clientHeight }, repeater = setInterval( function () { var width = documentElement.clientWidth, height = documentElement.clientHeight, isStable = width > 0 && height > 0 && width === lastSize.width && height === lastSize.height; if ( isStable ) { clearInterval( repeater ); readyDfd.resolve(); } else { lastSize = { width: width, height: height }; } }, interval || 100 ); } ); return readyDfd; }
[ "function", "windowSizeReady", "(", "queriedWindow", ",", "readyDfd", ",", "interval", ")", "{", "if", "(", "!", "varExists", "(", "$", ")", ")", "throw", "new", "Error", "(", "\"This method uses jQuery deferreds, but the $ variable is not available\"", ")", ";", "if", "(", "queriedWindow", "instanceof", "$", ")", "queriedWindow", "=", "queriedWindow", "[", "0", "]", ";", "readyDfd", "||", "(", "readyDfd", "=", "$", ".", "Deferred", "(", ")", ")", ";", "$", "(", "queriedWindow", ".", "document", ")", ".", "ready", "(", "function", "(", ")", "{", "var", "documentElement", "=", "queriedWindow", ".", "document", ".", "documentElement", ",", "lastSize", "=", "{", "width", ":", "documentElement", ".", "clientWidth", ",", "height", ":", "documentElement", ".", "clientHeight", "}", ",", "repeater", "=", "setInterval", "(", "function", "(", ")", "{", "var", "width", "=", "documentElement", ".", "clientWidth", ",", "height", "=", "documentElement", ".", "clientHeight", ",", "isStable", "=", "width", ">", "0", "&&", "height", ">", "0", "&&", "width", "===", "lastSize", ".", "width", "&&", "height", "===", "lastSize", ".", "height", ";", "if", "(", "isStable", ")", "{", "clearInterval", "(", "repeater", ")", ";", "readyDfd", ".", "resolve", "(", ")", ";", "}", "else", "{", "lastSize", "=", "{", "width", ":", "width", ",", "height", ":", "height", "}", ";", "}", "}", ",", "interval", "||", "100", ")", ";", "}", ")", ";", "return", "readyDfd", ";", "}" ]
Waits for the size of a window to become stable, in case it is undergoing a change. Returns a deferred which resolves when the window size is stable. Optionally accepts an external jQuery deferred to act on, which is then returned instead. This check can be used to determine when the process of resizing a window has ended. It should also be used when a new window is created. Technique --------- In most cases, it would be enough to set a timeout of 0 and then resolve the deferred. The timeout frees the UI and allows the window to assume its eventual size before the deferred is resolved. Unfortunately, the success rate of this approach is close to, but not quite, 100%. So instead, we check the reported window size in regular intervals, so we know for sure when it is stable. @param {Window|jQuery} queriedWindow the window to observe, also accepted inside a jQuery `$( window )` wrapper @param {jQuery.Deferred} [readyDfd] @param {number} [interval=100] the interval for checking the window size, in ms @returns {jQuery.Deferred}
[ "Waits", "for", "the", "size", "of", "a", "window", "to", "become", "stable", "in", "case", "it", "is", "undergoing", "a", "change", ".", "Returns", "a", "deferred", "which", "resolves", "when", "the", "window", "size", "is", "stable", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L156-L188
train
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
validateWindowSize
function validateWindowSize ( expected, opts ) { var msg = "", documentElement = ( opts && opts.window || window ).document.documentElement, width = documentElement.clientWidth, height = documentElement.clientHeight; if ( opts && opts.exactly ) { if ( width !== expected.width ) msg = " Window width is " + width + "px (expected: " + expected.width + "px)."; if ( height !== expected.height ) msg += " Window height is " + height + "px (expected: " + expected.height + "px)."; } else { if ( width < expected.width ) msg = " Window width is " + width + "px (expected minimum: " + expected.width + "px)."; if ( height < expected.height ) msg += " Window height is " + height + "px (expected minimum: " + expected.height + "px)."; } if ( msg !== "" ) throw new Error( "The browser window does not match the expected size." + msg ); }
javascript
function validateWindowSize ( expected, opts ) { var msg = "", documentElement = ( opts && opts.window || window ).document.documentElement, width = documentElement.clientWidth, height = documentElement.clientHeight; if ( opts && opts.exactly ) { if ( width !== expected.width ) msg = " Window width is " + width + "px (expected: " + expected.width + "px)."; if ( height !== expected.height ) msg += " Window height is " + height + "px (expected: " + expected.height + "px)."; } else { if ( width < expected.width ) msg = " Window width is " + width + "px (expected minimum: " + expected.width + "px)."; if ( height < expected.height ) msg += " Window height is " + height + "px (expected minimum: " + expected.height + "px)."; } if ( msg !== "" ) throw new Error( "The browser window does not match the expected size." + msg ); }
[ "function", "validateWindowSize", "(", "expected", ",", "opts", ")", "{", "var", "msg", "=", "\"\"", ",", "documentElement", "=", "(", "opts", "&&", "opts", ".", "window", "||", "window", ")", ".", "document", ".", "documentElement", ",", "width", "=", "documentElement", ".", "clientWidth", ",", "height", "=", "documentElement", ".", "clientHeight", ";", "if", "(", "opts", "&&", "opts", ".", "exactly", ")", "{", "if", "(", "width", "!==", "expected", ".", "width", ")", "msg", "=", "\" Window width is \"", "+", "width", "+", "\"px (expected: \"", "+", "expected", ".", "width", "+", "\"px).\"", ";", "if", "(", "height", "!==", "expected", ".", "height", ")", "msg", "+=", "\" Window height is \"", "+", "height", "+", "\"px (expected: \"", "+", "expected", ".", "height", "+", "\"px).\"", ";", "}", "else", "{", "if", "(", "width", "<", "expected", ".", "width", ")", "msg", "=", "\" Window width is \"", "+", "width", "+", "\"px (expected minimum: \"", "+", "expected", ".", "width", "+", "\"px).\"", ";", "if", "(", "height", "<", "expected", ".", "height", ")", "msg", "+=", "\" Window height is \"", "+", "height", "+", "\"px (expected minimum: \"", "+", "expected", ".", "height", "+", "\"px).\"", ";", "}", "if", "(", "msg", "!==", "\"\"", ")", "throw", "new", "Error", "(", "\"The browser window does not match the expected size.\"", "+", "msg", ")", ";", "}" ]
Makes sure a window is as at least as large as the specified minimum. If the window is too small, an error is thrown. Optionally, it can be validated that the window matches the expected size exactly. @param {Object} expected @param {number} expected.width @param {number} expected.height @param {Object} [opts] @param {Object} [opts.window=window] a window handle, defaults to the global `window` @param {boolean} [opts.exactly=false]
[ "Makes", "sure", "a", "window", "is", "as", "at", "least", "as", "large", "as", "the", "specified", "minimum", ".", "If", "the", "window", "is", "too", "small", "an", "error", "is", "thrown", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L203-L218
train
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
forceReflow
function forceReflow ( element ) { if ( !varExists( $ ) ) throw new Error( "This method uses jQuery, but the $ variable is not available" ); var $element = element instanceof $ ? element : $( element ); $element.css( { display: "none" } ).height(); $element.css( { display: "block" } ); }
javascript
function forceReflow ( element ) { if ( !varExists( $ ) ) throw new Error( "This method uses jQuery, but the $ variable is not available" ); var $element = element instanceof $ ? element : $( element ); $element.css( { display: "none" } ).height(); $element.css( { display: "block" } ); }
[ "function", "forceReflow", "(", "element", ")", "{", "if", "(", "!", "varExists", "(", "$", ")", ")", "throw", "new", "Error", "(", "\"This method uses jQuery, but the $ variable is not available\"", ")", ";", "var", "$element", "=", "element", "instanceof", "$", "?", "element", ":", "$", "(", "element", ")", ";", "$element", ".", "css", "(", "{", "display", ":", "\"none\"", "}", ")", ".", "height", "(", ")", ";", "$element", ".", "css", "(", "{", "display", ":", "\"block\"", "}", ")", ";", "}" ]
Forces a reflow for a given element, in case it doesn't happen automatically. For the technique, see http://stackoverflow.com/a/14382251/508355 For some background, see e.g. http://apmblog.dynatrace.com/2009/12/12/understanding-internet-explorer-rendering-behaviour/ @param {HTMLElement|jQuery} element
[ "Forces", "a", "reflow", "for", "a", "given", "element", "in", "case", "it", "doesn", "t", "happen", "automatically", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L256-L263
train
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
isIE
function isIE ( opts ) { var ver = getIEVersion(), isMatch = ver !== 0; opts || ( opts = {} ); if ( isMatch && opts.eq ) isMatch = ver === opts.eq; if ( isMatch && opts.lt ) isMatch = ver < opts.lt; if ( isMatch && opts.lte ) isMatch = ver <= opts.lte; if ( isMatch && opts.gt ) isMatch = ver > opts.gt; if ( isMatch && opts.gte ) isMatch = ver >= opts.gte; return isMatch; }
javascript
function isIE ( opts ) { var ver = getIEVersion(), isMatch = ver !== 0; opts || ( opts = {} ); if ( isMatch && opts.eq ) isMatch = ver === opts.eq; if ( isMatch && opts.lt ) isMatch = ver < opts.lt; if ( isMatch && opts.lte ) isMatch = ver <= opts.lte; if ( isMatch && opts.gt ) isMatch = ver > opts.gt; if ( isMatch && opts.gte ) isMatch = ver >= opts.gte; return isMatch; }
[ "function", "isIE", "(", "opts", ")", "{", "var", "ver", "=", "getIEVersion", "(", ")", ",", "isMatch", "=", "ver", "!==", "0", ";", "opts", "||", "(", "opts", "=", "{", "}", ")", ";", "if", "(", "isMatch", "&&", "opts", ".", "eq", ")", "isMatch", "=", "ver", "===", "opts", ".", "eq", ";", "if", "(", "isMatch", "&&", "opts", ".", "lt", ")", "isMatch", "=", "ver", "<", "opts", ".", "lt", ";", "if", "(", "isMatch", "&&", "opts", ".", "lte", ")", "isMatch", "=", "ver", "<=", "opts", ".", "lte", ";", "if", "(", "isMatch", "&&", "opts", ".", "gt", ")", "isMatch", "=", "ver", ">", "opts", ".", "gt", ";", "if", "(", "isMatch", "&&", "opts", ".", "gte", ")", "isMatch", "=", "ver", ">=", "opts", ".", "gte", ";", "return", "isMatch", ";", "}" ]
Detects IE. Can use a version requirement. A range can also be specified, e.g. with an option like { gte: 8, lt: 11 }. @param {Object} [opts] @param {number} [opts.eq] the IE version must be as specified @param {number} [opts.lt] the IE version must be less than the one specified @param {number} [opts.lte] the IE version must be less than or equal to the one specified @param {number} [opts.gt] the IE version must be greater than the one specified @param {number} [opts.gte] the IE version must be greater than or equal to the one specified
[ "Detects", "IE", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L416-L429
train
hashchange/jquery.documentsize
spec/helpers/dom-utils.js
getIEVersion
function getIEVersion () { var ieMatch = /MSIE (\d+)/.exec( navigator.userAgent ) || /Trident\/.+? rv:(\d+)/.exec( navigator.userAgent ); return ( ieMatch && ieMatch.length ) ? parseFloat( ieMatch[1] ) : 0; }
javascript
function getIEVersion () { var ieMatch = /MSIE (\d+)/.exec( navigator.userAgent ) || /Trident\/.+? rv:(\d+)/.exec( navigator.userAgent ); return ( ieMatch && ieMatch.length ) ? parseFloat( ieMatch[1] ) : 0; }
[ "function", "getIEVersion", "(", ")", "{", "var", "ieMatch", "=", "/", "MSIE (\\d+)", "/", ".", "exec", "(", "navigator", ".", "userAgent", ")", "||", "/", "Trident\\/.+? rv:(\\d+)", "/", ".", "exec", "(", "navigator", ".", "userAgent", ")", ";", "return", "(", "ieMatch", "&&", "ieMatch", ".", "length", ")", "?", "parseFloat", "(", "ieMatch", "[", "1", "]", ")", ":", "0", ";", "}" ]
Detects the IE version. Returns the major version number, or 0 if the browser is not IE. Simple solution, solely based on UA sniffing. In a better implementation, conditional comments would be used to detect IE6 to IE9 - see https://gist.github.com/cowboy/542301 for an example. UA sniffing would only serve as a fallback to detect IE > 9. There are also other solutions to infer the version of IE > 9. For inspiration, see http://stackoverflow.com/q/17907445/508355.
[ "Detects", "the", "IE", "version", ".", "Returns", "the", "major", "version", "number", "or", "0", "if", "the", "browser", "is", "not", "IE", "." ]
4f9c24f054f604b165082bbe5b3b424ad042a729
https://github.com/hashchange/jquery.documentsize/blob/4f9c24f054f604b165082bbe5b3b424ad042a729/spec/helpers/dom-utils.js#L439-L442
train
klei/grunt-injector
tasks/injector.js
removeEmptySources
function removeEmptySources (sources) { return _.reject(sources, function (obj) { return _.isEmpty(obj.transformed); }); }
javascript
function removeEmptySources (sources) { return _.reject(sources, function (obj) { return _.isEmpty(obj.transformed); }); }
[ "function", "removeEmptySources", "(", "sources", ")", "{", "return", "_", ".", "reject", "(", "sources", ",", "function", "(", "obj", ")", "{", "return", "_", ".", "isEmpty", "(", "obj", ".", "transformed", ")", ";", "}", ")", ";", "}" ]
Remove the entry whose transformed string is empty since we don't want to inject empty string.
[ "Remove", "the", "entry", "whose", "transformed", "string", "is", "empty", "since", "we", "don", "t", "want", "to", "inject", "empty", "string", "." ]
6387c056f74f35a65a462a6e07f2247a11da5a46
https://github.com/klei/grunt-injector/blob/6387c056f74f35a65a462a6e07f2247a11da5a46/tasks/injector.js#L292-L296
train
oscarmarinmiro/aframe-video-controls
index.js
function(){ var self = this; var camera = self.el.sceneEl.camera; if(camera) { var camera_rotation = camera.el.getAttribute("rotation"); var camera_yaw = camera_rotation.y; // Set position of menu based on camera yaw and data.pitch // Have to add 1.6m to camera.position.y (????) self.y_position = camera.position.y + 1.6; self.x_position = -self.data.distance * Math.sin(camera_yaw * Math.PI / 180.0); self.z_position = -self.data.distance * Math.cos(camera_yaw * Math.PI / 180.0); self.el.setAttribute("position", [self.x_position, self.y_position, self.z_position].join(" ")); // and now, make our controls rotate towards origin this.el.object3D.lookAt(new THREE.Vector3(camera.position.x, camera.position.y + 1.6, camera.position.z)); } }
javascript
function(){ var self = this; var camera = self.el.sceneEl.camera; if(camera) { var camera_rotation = camera.el.getAttribute("rotation"); var camera_yaw = camera_rotation.y; // Set position of menu based on camera yaw and data.pitch // Have to add 1.6m to camera.position.y (????) self.y_position = camera.position.y + 1.6; self.x_position = -self.data.distance * Math.sin(camera_yaw * Math.PI / 180.0); self.z_position = -self.data.distance * Math.cos(camera_yaw * Math.PI / 180.0); self.el.setAttribute("position", [self.x_position, self.y_position, self.z_position].join(" ")); // and now, make our controls rotate towards origin this.el.object3D.lookAt(new THREE.Vector3(camera.position.x, camera.position.y + 1.6, camera.position.z)); } }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "var", "camera", "=", "self", ".", "el", ".", "sceneEl", ".", "camera", ";", "if", "(", "camera", ")", "{", "var", "camera_rotation", "=", "camera", ".", "el", ".", "getAttribute", "(", "\"rotation\"", ")", ";", "var", "camera_yaw", "=", "camera_rotation", ".", "y", ";", "self", ".", "y_position", "=", "camera", ".", "position", ".", "y", "+", "1.6", ";", "self", ".", "x_position", "=", "-", "self", ".", "data", ".", "distance", "*", "Math", ".", "sin", "(", "camera_yaw", "*", "Math", ".", "PI", "/", "180.0", ")", ";", "self", ".", "z_position", "=", "-", "self", ".", "data", ".", "distance", "*", "Math", ".", "cos", "(", "camera_yaw", "*", "Math", ".", "PI", "/", "180.0", ")", ";", "self", ".", "el", ".", "setAttribute", "(", "\"position\"", ",", "[", "self", ".", "x_position", ",", "self", ".", "y_position", ",", "self", ".", "z_position", "]", ".", "join", "(", "\" \"", ")", ")", ";", "this", ".", "el", ".", "object3D", ".", "lookAt", "(", "new", "THREE", ".", "Vector3", "(", "camera", ".", "position", ".", "x", ",", "camera", ".", "position", ".", "y", "+", "1.6", ",", "camera", ".", "position", ".", "z", ")", ")", ";", "}", "}" ]
Puts the control in from of the camera, at this.data.distance, facing it...
[ "Puts", "the", "control", "in", "from", "of", "the", "camera", "at", "this", ".", "data", ".", "distance", "facing", "it", "..." ]
c4a8b8ae05498e7b2e43a65746e9ef5511504032
https://github.com/oscarmarinmiro/aframe-video-controls/blob/c4a8b8ae05498e7b2e43a65746e9ef5511504032/index.js#L41-L69
train
triestpa/koa-joi-validate
index.js
validateObject
function validateObject (object = {}, label, schema, options) { // Skip validation if no schema is provided if (schema) { // Validate the object against the provided schema const { error, value } = joi.validate(object, schema, options) if (error) { // Throw error with custom message if validation failed throw new Error(`Invalid ${label} - ${error.message}`) } } }
javascript
function validateObject (object = {}, label, schema, options) { // Skip validation if no schema is provided if (schema) { // Validate the object against the provided schema const { error, value } = joi.validate(object, schema, options) if (error) { // Throw error with custom message if validation failed throw new Error(`Invalid ${label} - ${error.message}`) } } }
[ "function", "validateObject", "(", "object", "=", "{", "}", ",", "label", ",", "schema", ",", "options", ")", "{", "if", "(", "schema", ")", "{", "const", "{", "error", ",", "value", "}", "=", "joi", ".", "validate", "(", "object", ",", "schema", ",", "options", ")", "if", "(", "error", ")", "{", "throw", "new", "Error", "(", "`", "${", "label", "}", "${", "error", ".", "message", "}", "`", ")", "}", "}", "}" ]
Helper function to validate an object against the provided schema, and to throw a custom error if object is not valid. @param {Object} object The object to be validated. @param {String} label The label to use in the error message. @param {JoiSchema} schema The Joi schema to validate the object against.
[ "Helper", "function", "to", "validate", "an", "object", "against", "the", "provided", "schema", "and", "to", "throw", "a", "custom", "error", "if", "object", "is", "not", "valid", "." ]
edc6bfe5b4889eddc78fe8c59ca75bb7209ae5d4
https://github.com/triestpa/koa-joi-validate/blob/edc6bfe5b4889eddc78fe8c59ca75bb7209ae5d4/index.js#L11-L21
train
triestpa/koa-joi-validate
index.js
validate
function validate (validationObj) { // Return a Koa middleware function return (ctx, next) => { try { // Validate each request data object in the Koa context object validateObject(ctx.headers, 'Headers', validationObj.headers, { allowUnknown: true }) validateObject(ctx.params, 'URL Parameters', validationObj.params) validateObject(ctx.query, 'URL Query', validationObj.query) if (ctx.request.body) { validateObject(ctx.request.body, 'Request Body', validationObj.body) } return next() } catch (err) { // If any of the objects fails validation, send an HTTP 400 response. ctx.throw(400, err.message) } } }
javascript
function validate (validationObj) { // Return a Koa middleware function return (ctx, next) => { try { // Validate each request data object in the Koa context object validateObject(ctx.headers, 'Headers', validationObj.headers, { allowUnknown: true }) validateObject(ctx.params, 'URL Parameters', validationObj.params) validateObject(ctx.query, 'URL Query', validationObj.query) if (ctx.request.body) { validateObject(ctx.request.body, 'Request Body', validationObj.body) } return next() } catch (err) { // If any of the objects fails validation, send an HTTP 400 response. ctx.throw(400, err.message) } } }
[ "function", "validate", "(", "validationObj", ")", "{", "return", "(", "ctx", ",", "next", ")", "=>", "{", "try", "{", "validateObject", "(", "ctx", ".", "headers", ",", "'Headers'", ",", "validationObj", ".", "headers", ",", "{", "allowUnknown", ":", "true", "}", ")", "validateObject", "(", "ctx", ".", "params", ",", "'URL Parameters'", ",", "validationObj", ".", "params", ")", "validateObject", "(", "ctx", ".", "query", ",", "'URL Query'", ",", "validationObj", ".", "query", ")", "if", "(", "ctx", ".", "request", ".", "body", ")", "{", "validateObject", "(", "ctx", ".", "request", ".", "body", ",", "'Request Body'", ",", "validationObj", ".", "body", ")", "}", "return", "next", "(", ")", "}", "catch", "(", "err", ")", "{", "ctx", ".", "throw", "(", "400", ",", "err", ".", "message", ")", "}", "}", "}" ]
Generate a Koa middleware function to validate a request using the provided validation objects. @param {Object} validationObj @param {Object} validationObj.headers The request headers schema @param {Object} validationObj.params The request params schema @param {Object} validationObj.query The request query schema @param {Object} validationObj.body The request body schema @returns A validation middleware function.
[ "Generate", "a", "Koa", "middleware", "function", "to", "validate", "a", "request", "using", "the", "provided", "validation", "objects", "." ]
edc6bfe5b4889eddc78fe8c59ca75bb7209ae5d4
https://github.com/triestpa/koa-joi-validate/blob/edc6bfe5b4889eddc78fe8c59ca75bb7209ae5d4/index.js#L34-L53
train
qeesung/rocketchat-node
lib/rocket-chat.js
function (protocol, host, port, username, password, onConnected) { this.rocketChatClient = new RocketChatClient(protocol, host, port, username, password, onConnected); this.token = null; /** * login the rocket chat * @param callback after login the rocket chat , will invoke the callback function */ this.login = function (username, password, callback) { var self = this; this.rocketChatClient.authentication.login(username, password, function (err, body) { self.token = body.data; callback(null, body); }); }; }
javascript
function (protocol, host, port, username, password, onConnected) { this.rocketChatClient = new RocketChatClient(protocol, host, port, username, password, onConnected); this.token = null; /** * login the rocket chat * @param callback after login the rocket chat , will invoke the callback function */ this.login = function (username, password, callback) { var self = this; this.rocketChatClient.authentication.login(username, password, function (err, body) { self.token = body.data; callback(null, body); }); }; }
[ "function", "(", "protocol", ",", "host", ",", "port", ",", "username", ",", "password", ",", "onConnected", ")", "{", "this", ".", "rocketChatClient", "=", "new", "RocketChatClient", "(", "protocol", ",", "host", ",", "port", ",", "username", ",", "password", ",", "onConnected", ")", ";", "this", ".", "token", "=", "null", ";", "this", ".", "login", "=", "function", "(", "username", ",", "password", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "this", ".", "rocketChatClient", ".", "authentication", ".", "login", "(", "username", ",", "password", ",", "function", "(", "err", ",", "body", ")", "{", "self", ".", "token", "=", "body", ".", "data", ";", "callback", "(", "null", ",", "body", ")", ";", "}", ")", ";", "}", ";", "}" ]
Rocket Chat Api constructor @param protocol rocket chat protocol @param host rocket chat host , default is https://demo.rocket.chat @param port rocket chat port , default is 80 @param username rocket chat username @param password rocket chat password @param onConnected callback that is invoked when connection is open @constructor
[ "Rocket", "Chat", "Api", "constructor" ]
3fb76139968e8d95fc6db19411955e11b31fa7cc
https://github.com/qeesung/rocketchat-node/blob/3fb76139968e8d95fc6db19411955e11b31fa7cc/lib/rocket-chat.js#L27-L43
train
weihanchen/angular-d3-word-cloud
docs/js/controllers/app.js
resizeWordsCloud
function resizeWordsCloud() { $timeout(function() { var element = document.getElementById('wordsCloud'); var height = $window.innerHeight * 0.75; element.style.height = height + 'px'; var width = element.getBoundingClientRect().width; var maxCount = originWords[0].count; var minCount = originWords[originWords.length - 1].count; var maxWordSize = width * 0.15; var minWordSize = maxWordSize / 5; var spread = maxCount - minCount; if (spread <= 0) spread = 1; var step = (maxWordSize - minWordSize) / spread; self.words = originWords.map(function(word) { return { text: word.text, size: Math.round(maxWordSize - ((maxCount - word.count) * step)), color: self.customColor, tooltipText: word.text + ' tooltip' }; }); self.width = width; self.height = height; self.padding = self.editPadding; self.rotate = self.editRotate; }); }
javascript
function resizeWordsCloud() { $timeout(function() { var element = document.getElementById('wordsCloud'); var height = $window.innerHeight * 0.75; element.style.height = height + 'px'; var width = element.getBoundingClientRect().width; var maxCount = originWords[0].count; var minCount = originWords[originWords.length - 1].count; var maxWordSize = width * 0.15; var minWordSize = maxWordSize / 5; var spread = maxCount - minCount; if (spread <= 0) spread = 1; var step = (maxWordSize - minWordSize) / spread; self.words = originWords.map(function(word) { return { text: word.text, size: Math.round(maxWordSize - ((maxCount - word.count) * step)), color: self.customColor, tooltipText: word.text + ' tooltip' }; }); self.width = width; self.height = height; self.padding = self.editPadding; self.rotate = self.editRotate; }); }
[ "function", "resizeWordsCloud", "(", ")", "{", "$timeout", "(", "function", "(", ")", "{", "var", "element", "=", "document", ".", "getElementById", "(", "'wordsCloud'", ")", ";", "var", "height", "=", "$window", ".", "innerHeight", "*", "0.75", ";", "element", ".", "style", ".", "height", "=", "height", "+", "'px'", ";", "var", "width", "=", "element", ".", "getBoundingClientRect", "(", ")", ".", "width", ";", "var", "maxCount", "=", "originWords", "[", "0", "]", ".", "count", ";", "var", "minCount", "=", "originWords", "[", "originWords", ".", "length", "-", "1", "]", ".", "count", ";", "var", "maxWordSize", "=", "width", "*", "0.15", ";", "var", "minWordSize", "=", "maxWordSize", "/", "5", ";", "var", "spread", "=", "maxCount", "-", "minCount", ";", "if", "(", "spread", "<=", "0", ")", "spread", "=", "1", ";", "var", "step", "=", "(", "maxWordSize", "-", "minWordSize", ")", "/", "spread", ";", "self", ".", "words", "=", "originWords", ".", "map", "(", "function", "(", "word", ")", "{", "return", "{", "text", ":", "word", ".", "text", ",", "size", ":", "Math", ".", "round", "(", "maxWordSize", "-", "(", "(", "maxCount", "-", "word", ".", "count", ")", "*", "step", ")", ")", ",", "color", ":", "self", ".", "customColor", ",", "tooltipText", ":", "word", ".", "text", "+", "' tooltip'", "}", ";", "}", ")", ";", "self", ".", "width", "=", "width", ";", "self", ".", "height", "=", "height", ";", "self", ".", "padding", "=", "self", ".", "editPadding", ";", "self", ".", "rotate", "=", "self", ".", "editRotate", ";", "}", ")", ";", "}" ]
adjust words size base on width
[ "adjust", "words", "size", "base", "on", "width" ]
66464ea8e33ff6b03cca608c55a552e76922bf67
https://github.com/weihanchen/angular-d3-word-cloud/blob/66464ea8e33ff6b03cca608c55a552e76922bf67/docs/js/controllers/app.js#L39-L65
train
wmira/react-datatable
src/js/datasource.js
function(records,config) { //the hell is this doing here this.id = new Date(); if ( records instanceof Array ) { this.records = records; } else { var dataField = records.data; var data = records.datasource; this.records = data[dataField]; } this.config = config; if ( this.config ) { this.propertyConfigMap = {}; this.config.cols.forEach( col => { this.propertyConfigMap[col.property] = col; }); } //indexRecords.call(this); }
javascript
function(records,config) { //the hell is this doing here this.id = new Date(); if ( records instanceof Array ) { this.records = records; } else { var dataField = records.data; var data = records.datasource; this.records = data[dataField]; } this.config = config; if ( this.config ) { this.propertyConfigMap = {}; this.config.cols.forEach( col => { this.propertyConfigMap[col.property] = col; }); } //indexRecords.call(this); }
[ "function", "(", "records", ",", "config", ")", "{", "this", ".", "id", "=", "new", "Date", "(", ")", ";", "if", "(", "records", "instanceof", "Array", ")", "{", "this", ".", "records", "=", "records", ";", "}", "else", "{", "var", "dataField", "=", "records", ".", "data", ";", "var", "data", "=", "records", ".", "datasource", ";", "this", ".", "records", "=", "data", "[", "dataField", "]", ";", "}", "this", ".", "config", "=", "config", ";", "if", "(", "this", ".", "config", ")", "{", "this", ".", "propertyConfigMap", "=", "{", "}", ";", "this", ".", "config", ".", "cols", ".", "forEach", "(", "col", "=>", "{", "this", ".", "propertyConfigMap", "[", "col", ".", "property", "]", "=", "col", ";", "}", ")", ";", "}", "}" ]
Create a new datasource using records array as a backing dataset @param records @constructor
[ "Create", "a", "new", "datasource", "using", "records", "array", "as", "a", "backing", "dataset" ]
81647701093a14d9f58a1cd016169a2534f012be
https://github.com/wmira/react-datatable/blob/81647701093a14d9f58a1cd016169a2534f012be/src/js/datasource.js#L48-L69
train
michaelkrone/generator-material-app
generators/app/templates/server/api/user(auth)/user.controller.js
function (req, res) { // check for a user id if (!req[this.paramName]._id) { return res.badRequest(); } req[this.paramName].password = req.body.password; delete req.body.password; req[this.paramName].save(function (err) { if (err) { return res.handleError(err); } return res.noContent(); }); }
javascript
function (req, res) { // check for a user id if (!req[this.paramName]._id) { return res.badRequest(); } req[this.paramName].password = req.body.password; delete req.body.password; req[this.paramName].save(function (err) { if (err) { return res.handleError(err); } return res.noContent(); }); }
[ "function", "(", "req", ",", "res", ")", "{", "if", "(", "!", "req", "[", "this", ".", "paramName", "]", ".", "_id", ")", "{", "return", "res", ".", "badRequest", "(", ")", ";", "}", "req", "[", "this", ".", "paramName", "]", ".", "password", "=", "req", ".", "body", ".", "password", ";", "delete", "req", ".", "body", ".", "password", ";", "req", "[", "this", ".", "paramName", "]", ".", "save", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "res", ".", "handleError", "(", "err", ")", ";", "}", "return", "res", ".", "noContent", "(", ")", ";", "}", ")", ";", "}" ]
README Replaces an existing user password in the DB using the request body property named 'password'. Should be an admin only route. @param {IncomingMessage} req - The request message object @param {ServerResponse} res - The outgoing response object @returns {ServerResponse} The updated document or NOT FOUND if no document has been found
[ "README", "Replaces", "an", "existing", "user", "password", "in", "the", "DB", "using", "the", "request", "body", "property", "named", "password", ".", "Should", "be", "an", "admin", "only", "route", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.controller.js#L54-L69
train
michaelkrone/generator-material-app
generators/app/templates/server/api/user(auth)/user.controller.js
function (req, res, next) { var userId = req[this.paramName]._id; var oldPass = String(req.body.oldPassword); var newPass = String(req.body.newPassword); this.model.findOne({'_id': userId}, function (err, user) { if (user.authenticate(oldPass)) { user.password = newPass; user.save(function (err) { if (err) { return res.handleError(err); } return res.noContent(); }); } else { res.forbidden(); } }); }
javascript
function (req, res, next) { var userId = req[this.paramName]._id; var oldPass = String(req.body.oldPassword); var newPass = String(req.body.newPassword); this.model.findOne({'_id': userId}, function (err, user) { if (user.authenticate(oldPass)) { user.password = newPass; user.save(function (err) { if (err) { return res.handleError(err); } return res.noContent(); }); } else { res.forbidden(); } }); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "var", "userId", "=", "req", "[", "this", ".", "paramName", "]", ".", "_id", ";", "var", "oldPass", "=", "String", "(", "req", ".", "body", ".", "oldPassword", ")", ";", "var", "newPass", "=", "String", "(", "req", ".", "body", ".", "newPassword", ")", ";", "this", ".", "model", ".", "findOne", "(", "{", "'_id'", ":", "userId", "}", ",", "function", "(", "err", ",", "user", ")", "{", "if", "(", "user", ".", "authenticate", "(", "oldPass", ")", ")", "{", "user", ".", "password", "=", "newPass", ";", "user", ".", "save", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "res", ".", "handleError", "(", "err", ")", ";", "}", "return", "res", ".", "noContent", "(", ")", ";", "}", ")", ";", "}", "else", "{", "res", ".", "forbidden", "(", ")", ";", "}", "}", ")", ";", "}" ]
Change the password of a user in the DB. The 'oldPassword' and 'newPassword' property of the request body are used. @param {IncomingMessage} req - The request message object containing the 'oldPassword' and 'newPassword' property @param {ServerResponse} res - The outgoing response object @param {function} next - The next handler function @returns {ServerResponse} The response status OK or FORBIDDEN if an error occurs
[ "Change", "the", "password", "of", "a", "user", "in", "the", "DB", ".", "The", "oldPassword", "and", "newPassword", "property", "of", "the", "request", "body", "are", "used", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.controller.js#L79-L98
train
michaelkrone/generator-material-app
generators/app/templates/server/api/user(auth)/user.controller.js
function (req, res, next) { if (!req.userInfo) { return res.unauthorized(); } return res.ok(req.userInfo.profile); }
javascript
function (req, res, next) { if (!req.userInfo) { return res.unauthorized(); } return res.ok(req.userInfo.profile); }
[ "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "!", "req", ".", "userInfo", ")", "{", "return", "res", ".", "unauthorized", "(", ")", ";", "}", "return", "res", ".", "ok", "(", "req", ".", "userInfo", ".", "profile", ")", ";", "}" ]
Get the authenticated user for the current request. The requested user id is read from the userInfo parameter of the request object. @param {IncomingMessage} req - The request message object the user object is read from @param {ServerResponse} res - The outgoing response object @param {function} next - The next handler function @returns {ServerResponse} The virtual 'profile' of this user or UNAUTHORIZED if no document has been found
[ "Get", "the", "authenticated", "user", "for", "the", "current", "request", ".", "The", "requested", "user", "id", "is", "read", "from", "the", "userInfo", "parameter", "of", "the", "request", "object", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.controller.js#L108-L114
train
michaelkrone/generator-material-app
generators/app/templates/server/lib/responses/errors.js
handleError
function handleError(err, options) { // jshint validthis: true // Get access to response object var res = this.res; var statusCode; console.log('handleError', err, options); if (err.name && err.name === 'ValidationError') { return res.badRequest(err); } try { statusCode = err.status || 500; // set the status as a default res.status(statusCode); if (statusCode !== 500 && typeof res[statusCode] === 'function') { return res[statusCode](err); } } catch (e) { console.log('Exception while handling error: %s', e); } return res.serverError(err); }
javascript
function handleError(err, options) { // jshint validthis: true // Get access to response object var res = this.res; var statusCode; console.log('handleError', err, options); if (err.name && err.name === 'ValidationError') { return res.badRequest(err); } try { statusCode = err.status || 500; // set the status as a default res.status(statusCode); if (statusCode !== 500 && typeof res[statusCode] === 'function') { return res[statusCode](err); } } catch (e) { console.log('Exception while handling error: %s', e); } return res.serverError(err); }
[ "function", "handleError", "(", "err", ",", "options", ")", "{", "var", "res", "=", "this", ".", "res", ";", "var", "statusCode", ";", "console", ".", "log", "(", "'handleError'", ",", "err", ",", "options", ")", ";", "if", "(", "err", ".", "name", "&&", "err", ".", "name", "===", "'ValidationError'", ")", "{", "return", "res", ".", "badRequest", "(", "err", ")", ";", "}", "try", "{", "statusCode", "=", "err", ".", "status", "||", "500", ";", "res", ".", "status", "(", "statusCode", ")", ";", "if", "(", "statusCode", "!==", "500", "&&", "typeof", "res", "[", "statusCode", "]", "===", "'function'", ")", "{", "return", "res", "[", "statusCode", "]", "(", "err", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "console", ".", "log", "(", "'Exception while handling error: %s'", ",", "e", ")", ";", "}", "return", "res", ".", "serverError", "(", "err", ")", ";", "}" ]
Handle generic errors on requests. Set status 'Internal Server Error' @param {http.ServerResponse} res - The outgoing response object @param {Error} [err] - The error that occurred during the request @return The given Response with a error status code set (defaults to 500) and the error object set as response body.
[ "Handle", "generic", "errors", "on", "requests", ".", "Set", "status", "Internal", "Server", "Error" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/responses/errors.js#L251-L276
train
michaelkrone/generator-material-app
generators/app/templates/server/api/user(auth)/user.model.js
validateUniqueName
function validateUniqueName(value, respond) { // jshint validthis: true var self = this; // check for uniqueness of user name this.constructor.findOne({name: value}, function (err, user) { if (err) { throw err; } if (user) { // the searched name is my name or a duplicate return respond(self.id === user.id); } respond(true); }); }
javascript
function validateUniqueName(value, respond) { // jshint validthis: true var self = this; // check for uniqueness of user name this.constructor.findOne({name: value}, function (err, user) { if (err) { throw err; } if (user) { // the searched name is my name or a duplicate return respond(self.id === user.id); } respond(true); }); }
[ "function", "validateUniqueName", "(", "value", ",", "respond", ")", "{", "var", "self", "=", "this", ";", "this", ".", "constructor", ".", "findOne", "(", "{", "name", ":", "value", "}", ",", "function", "(", "err", ",", "user", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "if", "(", "user", ")", "{", "return", "respond", "(", "self", ".", "id", "===", "user", ".", "id", ")", ";", "}", "respond", "(", "true", ")", ";", "}", ")", ";", "}" ]
Validate the uniqueness of the given username @api private @param {String} value - The username to check for uniqueness @param {Function} respond - The callback function
[ "Validate", "the", "uniqueness", "of", "the", "given", "username" ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.model.js#L259-L276
train
michaelkrone/generator-material-app
generators/app/templates/server/api/user(auth)/user.model.js
preSave
function preSave(next) { // jshint validthis: true var self = this; if (this.isNew && !validatePresenceOf(this.hashedPassword)) { return next(new MongooseError.ValidationError('Missing password')); } // check if the root user should be updated // return an error if some not root tries to touch the root document self.constructor.getRoot(function (err, rootUser) { if (err) { throw err; } // will we update the root user? if (rootUser && self.id === rootUser.id) { // delete the role to prevent loosing the root status delete self.role; // get the user role to check if a root user will perform the update var userRole = contextService.getContext('request:acl.user.role'); if (!userRole) { // no user role - no root user check return next(); } if (!auth.roles.isRoot(userRole)) { // return error, only root can update root return next(new MongooseError.ValidationError('Forbidden root update request')); } } // normal user update return next(); }); }
javascript
function preSave(next) { // jshint validthis: true var self = this; if (this.isNew && !validatePresenceOf(this.hashedPassword)) { return next(new MongooseError.ValidationError('Missing password')); } // check if the root user should be updated // return an error if some not root tries to touch the root document self.constructor.getRoot(function (err, rootUser) { if (err) { throw err; } // will we update the root user? if (rootUser && self.id === rootUser.id) { // delete the role to prevent loosing the root status delete self.role; // get the user role to check if a root user will perform the update var userRole = contextService.getContext('request:acl.user.role'); if (!userRole) { // no user role - no root user check return next(); } if (!auth.roles.isRoot(userRole)) { // return error, only root can update root return next(new MongooseError.ValidationError('Forbidden root update request')); } } // normal user update return next(); }); }
[ "function", "preSave", "(", "next", ")", "{", "var", "self", "=", "this", ";", "if", "(", "this", ".", "isNew", "&&", "!", "validatePresenceOf", "(", "this", ".", "hashedPassword", ")", ")", "{", "return", "next", "(", "new", "MongooseError", ".", "ValidationError", "(", "'Missing password'", ")", ")", ";", "}", "self", ".", "constructor", ".", "getRoot", "(", "function", "(", "err", ",", "rootUser", ")", "{", "if", "(", "err", ")", "{", "throw", "err", ";", "}", "if", "(", "rootUser", "&&", "self", ".", "id", "===", "rootUser", ".", "id", ")", "{", "delete", "self", ".", "role", ";", "var", "userRole", "=", "contextService", ".", "getContext", "(", "'request:acl.user.role'", ")", ";", "if", "(", "!", "userRole", ")", "{", "return", "next", "(", ")", ";", "}", "if", "(", "!", "auth", ".", "roles", ".", "isRoot", "(", "userRole", ")", ")", "{", "return", "next", "(", "new", "MongooseError", ".", "ValidationError", "(", "'Forbidden root update request'", ")", ")", ";", "}", "}", "return", "next", "(", ")", ";", "}", ")", ";", "}" ]
Pre save hook for the User model. Validates the existence of the hashedPassword property if the document is saved for the first time. Ensure that only the root user can update itself. @api private @param {Function} next - The mongoose middleware callback @returns {*} If an error occurs the passed callback with an Error as its argument is called
[ "Pre", "save", "hook", "for", "the", "User", "model", ".", "Validates", "the", "existence", "of", "the", "hashedPassword", "property", "if", "the", "document", "is", "saved", "for", "the", "first", "time", ".", "Ensure", "that", "only", "the", "root", "user", "can", "update", "itself", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.model.js#L321-L357
train
michaelkrone/generator-material-app
generators/app/templates/server/api/user(auth)/user.model.js
preRemove
function preRemove(next) { // jshint validthis: true if (auth.roles.isRoot(this.role)) { return next(new MongooseError.ValidationError(auth.roles.getMaxRole() + ' role cannot be deleted')); } return next(); }
javascript
function preRemove(next) { // jshint validthis: true if (auth.roles.isRoot(this.role)) { return next(new MongooseError.ValidationError(auth.roles.getMaxRole() + ' role cannot be deleted')); } return next(); }
[ "function", "preRemove", "(", "next", ")", "{", "if", "(", "auth", ".", "roles", ".", "isRoot", "(", "this", ".", "role", ")", ")", "{", "return", "next", "(", "new", "MongooseError", ".", "ValidationError", "(", "auth", ".", "roles", ".", "getMaxRole", "(", ")", "+", "' role cannot be deleted'", ")", ")", ";", "}", "return", "next", "(", ")", ";", "}" ]
Pre remove hook for the User model. Validates that the root user cannot be deleted. @api private @param {Function} next - The mongoose middleware callback @returns {*} If an error occurs the passed callback with an Error as its argument is called
[ "Pre", "remove", "hook", "for", "the", "User", "model", ".", "Validates", "that", "the", "root", "user", "cannot", "be", "deleted", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/api/user(auth)/user.model.js#L367-L374
train
michaelkrone/generator-material-app
generators/app/templates/server/lib/auth(auth)/local/passport.js
getAuthentication
function getAuthentication(authModel, config) { /** * @name authenticate * @function * @memberOf getAuthentication * Authenticate the user. * @param {String} name - The name used to authenticate the user * @param {String} password - The hashed password * @param {function} done - The callback function called with an error or the valid user object */ function authenticate(name, password, done) { authModel.findOne({name: name, active: true}, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false, {message: 'Unknown user'}); } if (!user.authenticate(password)) { return done(null, false, {message: 'Wrong password'}); } return done(null, user); }); } return authenticate; }
javascript
function getAuthentication(authModel, config) { /** * @name authenticate * @function * @memberOf getAuthentication * Authenticate the user. * @param {String} name - The name used to authenticate the user * @param {String} password - The hashed password * @param {function} done - The callback function called with an error or the valid user object */ function authenticate(name, password, done) { authModel.findOne({name: name, active: true}, function (err, user) { if (err) { return done(err); } if (!user) { return done(null, false, {message: 'Unknown user'}); } if (!user.authenticate(password)) { return done(null, false, {message: 'Wrong password'}); } return done(null, user); }); } return authenticate; }
[ "function", "getAuthentication", "(", "authModel", ",", "config", ")", "{", "function", "authenticate", "(", "name", ",", "password", ",", "done", ")", "{", "authModel", ".", "findOne", "(", "{", "name", ":", "name", ",", "active", ":", "true", "}", ",", "function", "(", "err", ",", "user", ")", "{", "if", "(", "err", ")", "{", "return", "done", "(", "err", ")", ";", "}", "if", "(", "!", "user", ")", "{", "return", "done", "(", "null", ",", "false", ",", "{", "message", ":", "'Unknown user'", "}", ")", ";", "}", "if", "(", "!", "user", ".", "authenticate", "(", "password", ")", ")", "{", "return", "done", "(", "null", ",", "false", ",", "{", "message", ":", "'Wrong password'", "}", ")", ";", "}", "return", "done", "(", "null", ",", "user", ")", ";", "}", ")", ";", "}", "return", "authenticate", ";", "}" ]
Return a function that authenticates the user. The user is identified by email. The hashed password is passed to the User model for authentication. @param {Model} authModel - The mongoose model used to authenticate the user @param {Object} [config] - The application configuration, may be passed to the service some day @returns {function} - The authentication function to use with the given authModel
[ "Return", "a", "function", "that", "authenticates", "the", "user", ".", "The", "user", "is", "identified", "by", "email", ".", "The", "hashed", "password", "is", "passed", "to", "the", "User", "model", "for", "authentication", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/auth(auth)/local/passport.js#L42-L72
train
michaelkrone/generator-material-app
generators/app/templates/server/lib/auth(auth)/local/index.js
authenticate
function authenticate(req, res, next) { var callback = _.bind(authCallback, {req: req, res: res}); passport.authenticate('local', callback)(req, res, next) }
javascript
function authenticate(req, res, next) { var callback = _.bind(authCallback, {req: req, res: res}); passport.authenticate('local', callback)(req, res, next) }
[ "function", "authenticate", "(", "req", ",", "res", ",", "next", ")", "{", "var", "callback", "=", "_", ".", "bind", "(", "authCallback", ",", "{", "req", ":", "req", ",", "res", ":", "res", "}", ")", ";", "passport", ".", "authenticate", "(", "'local'", ",", "callback", ")", "(", "req", ",", "res", ",", "next", ")", "}" ]
Authenticate a request and sign a token. @param {http.IncomingMessage} req - The request message object @param {http.ServerResponse} res - The outgoing response object @param {function} next - The next handler callback @return {http.ServerResponse} The result of calling the [callback function]{@link auth:local~authCallback}
[ "Authenticate", "a", "request", "and", "sign", "a", "token", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/auth(auth)/local/index.js#L29-L32
train
michaelkrone/generator-material-app
generators/app/templates/server/lib/controllers/crud.controller.js
CrudController
function CrudController(model, idName) { // call super constructor BaseController.call(this); // set the model instance to work on this.model = model; // set id name if defined, defaults to 'id' if (idName) { this.idName = String(idName); } }
javascript
function CrudController(model, idName) { // call super constructor BaseController.call(this); // set the model instance to work on this.model = model; // set id name if defined, defaults to 'id' if (idName) { this.idName = String(idName); } }
[ "function", "CrudController", "(", "model", ",", "idName", ")", "{", "BaseController", ".", "call", "(", "this", ")", ";", "this", ".", "model", "=", "model", ";", "if", "(", "idName", ")", "{", "this", ".", "idName", "=", "String", "(", "idName", ")", ";", "}", "}" ]
Constructor function for CrudController. @classdesc Controller for basic CRUD operations on mongoose models. Uses the passed id name as the request parameter id to identify models. @constructor @inherits BaseController @param {Model} model - The mongoose model to operate on @param {String} [idName] - The name of the id request parameter to use
[ "Constructor", "function", "for", "CrudController", "." ]
764465d953282f6d86349527e3d62ec97f12a4d1
https://github.com/michaelkrone/generator-material-app/blob/764465d953282f6d86349527e3d62ec97f12a4d1/generators/app/templates/server/lib/controllers/crud.controller.js#L21-L32
train