repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
toajs/toa
lib/application.js
onResError
function onResError (ctx, err) { // nothing we can do here other // than delegate to the app-level // handler and log. if (ctx.headerSent || ctx._finished != null) { err.headerSent = ctx.headerSent err.context = ctx.toJSON() return err } // unset headers if (isFn(ctx.res.getHeaderNames)) { for (let name of ctx.res.getHeaderNames()) { if (!ON_ERROR_HEADER_REG.test(name)) ctx.res.removeHeader(name) } } else { // Node < 7.7 let _headers = ctx.res._headers if (_headers) { // retain headers on error for (let name of Object.keys(_headers)) { if (!ON_ERROR_HEADER_REG.test(name)) delete _headers[name] } } } // support ENOENT to 404, default to 500 if (err.code === 'ENOENT') ctx.status = 404 else if (typeof err.status !== 'number' || !statuses[err.status]) ctx.status = 500 else ctx.status = err.status ctx.set('x-content-type-options', 'nosniff') // support JSON error object: { error: 'BadRequest', message: 'Some bad request' } ctx.body = !isError(err) ? err : { error: err.error || err.name, message: err.expose ? err.message : statuses[ctx.status] } respond.call(ctx) return err }
javascript
function onResError (ctx, err) { // nothing we can do here other // than delegate to the app-level // handler and log. if (ctx.headerSent || ctx._finished != null) { err.headerSent = ctx.headerSent err.context = ctx.toJSON() return err } // unset headers if (isFn(ctx.res.getHeaderNames)) { for (let name of ctx.res.getHeaderNames()) { if (!ON_ERROR_HEADER_REG.test(name)) ctx.res.removeHeader(name) } } else { // Node < 7.7 let _headers = ctx.res._headers if (_headers) { // retain headers on error for (let name of Object.keys(_headers)) { if (!ON_ERROR_HEADER_REG.test(name)) delete _headers[name] } } } // support ENOENT to 404, default to 500 if (err.code === 'ENOENT') ctx.status = 404 else if (typeof err.status !== 'number' || !statuses[err.status]) ctx.status = 500 else ctx.status = err.status ctx.set('x-content-type-options', 'nosniff') // support JSON error object: { error: 'BadRequest', message: 'Some bad request' } ctx.body = !isError(err) ? err : { error: err.error || err.name, message: err.expose ? err.message : statuses[ctx.status] } respond.call(ctx) return err }
[ "function", "onResError", "(", "ctx", ",", "err", ")", "{", "if", "(", "ctx", ".", "headerSent", "||", "ctx", ".", "_finished", "!=", "null", ")", "{", "err", ".", "headerSent", "=", "ctx", ".", "headerSent", "err", ".", "context", "=", "ctx", ".", "toJSON", "(", ")", "return", "err", "}", "if", "(", "isFn", "(", "ctx", ".", "res", ".", "getHeaderNames", ")", ")", "{", "for", "(", "let", "name", "of", "ctx", ".", "res", ".", "getHeaderNames", "(", ")", ")", "{", "if", "(", "!", "ON_ERROR_HEADER_REG", ".", "test", "(", "name", ")", ")", "ctx", ".", "res", ".", "removeHeader", "(", "name", ")", "}", "}", "else", "{", "let", "_headers", "=", "ctx", ".", "res", ".", "_headers", "if", "(", "_headers", ")", "{", "for", "(", "let", "name", "of", "Object", ".", "keys", "(", "_headers", ")", ")", "{", "if", "(", "!", "ON_ERROR_HEADER_REG", ".", "test", "(", "name", ")", ")", "delete", "_headers", "[", "name", "]", "}", "}", "}", "if", "(", "err", ".", "code", "===", "'ENOENT'", ")", "ctx", ".", "status", "=", "404", "else", "if", "(", "typeof", "err", ".", "status", "!==", "'number'", "||", "!", "statuses", "[", "err", ".", "status", "]", ")", "ctx", ".", "status", "=", "500", "else", "ctx", ".", "status", "=", "err", ".", "status", "ctx", ".", "set", "(", "'x-content-type-options'", ",", "'nosniff'", ")", "ctx", ".", "body", "=", "!", "isError", "(", "err", ")", "?", "err", ":", "{", "error", ":", "err", ".", "error", "||", "err", ".", "name", ",", "message", ":", "err", ".", "expose", "?", "err", ".", "message", ":", "statuses", "[", "ctx", ".", "status", "]", "}", "respond", ".", "call", "(", "ctx", ")", "return", "err", "}" ]
Default response error handler. @param {Error} err @api private
[ "Default", "response", "error", "handler", "." ]
21814e5cf29125dffc92ba84c7364e0d5335855b
https://github.com/toajs/toa/blob/21814e5cf29125dffc92ba84c7364e0d5335855b/lib/application.js#L300-L337
train
doowb/npm-api
index.js
NpmApi
function NpmApi(options) { if (!(this instanceof NpmApi)) { return new NpmApi(options); } Base.call(this, null, options); this.is('npmapi'); this.use(utils.plugin()); this.use(utils.option()); this.define('List', List); this.define('View', View); this.define('Repo', Repo); this.define('Maintainer', Maintainer); var store = typeof this.options.store === 'undefined' ? new Memory() : this.options.store; this.define('store', store); }
javascript
function NpmApi(options) { if (!(this instanceof NpmApi)) { return new NpmApi(options); } Base.call(this, null, options); this.is('npmapi'); this.use(utils.plugin()); this.use(utils.option()); this.define('List', List); this.define('View', View); this.define('Repo', Repo); this.define('Maintainer', Maintainer); var store = typeof this.options.store === 'undefined' ? new Memory() : this.options.store; this.define('store', store); }
[ "function", "NpmApi", "(", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "NpmApi", ")", ")", "{", "return", "new", "NpmApi", "(", "options", ")", ";", "}", "Base", ".", "call", "(", "this", ",", "null", ",", "options", ")", ";", "this", ".", "is", "(", "'npmapi'", ")", ";", "this", ".", "use", "(", "utils", ".", "plugin", "(", ")", ")", ";", "this", ".", "use", "(", "utils", ".", "option", "(", ")", ")", ";", "this", ".", "define", "(", "'List'", ",", "List", ")", ";", "this", ".", "define", "(", "'View'", ",", "View", ")", ";", "this", ".", "define", "(", "'Repo'", ",", "Repo", ")", ";", "this", ".", "define", "(", "'Maintainer'", ",", "Maintainer", ")", ";", "var", "store", "=", "typeof", "this", ".", "options", ".", "store", "===", "'undefined'", "?", "new", "Memory", "(", ")", ":", "this", ".", "options", ".", "store", ";", "this", ".", "define", "(", "'store'", ",", "store", ")", ";", "}" ]
NpmApi constructor. Create an instance to work with maintainer and repository information. ```js var npm = new NpmApi(); ``` @api public
[ "NpmApi", "constructor", ".", "Create", "an", "instance", "to", "work", "with", "maintainer", "and", "repository", "information", "." ]
2204395a7da8815465c12ba147cd7622b9d5bae2
https://github.com/doowb/npm-api/blob/2204395a7da8815465c12ba147cd7622b9d5bae2/index.js#L27-L44
train
evanshortiss/yr.no-forecast
index.js
function () { return this.json.weatherdata.product.time[this.json.weatherdata.product.time.length - 1].from; }
javascript
function () { return this.json.weatherdata.product.time[this.json.weatherdata.product.time.length - 1].from; }
[ "function", "(", ")", "{", "return", "this", ".", "json", ".", "weatherdata", ".", "product", ".", "time", "[", "this", ".", "json", ".", "weatherdata", ".", "product", ".", "time", ".", "length", "-", "1", "]", ".", "from", ";", "}" ]
Returns the latest ISO timestring available in the weather data @return {String}
[ "Returns", "the", "latest", "ISO", "timestring", "available", "in", "the", "weather", "data" ]
065320a3540d4b7890ba5ff94784023c904ecfca
https://github.com/evanshortiss/yr.no-forecast/blob/065320a3540d4b7890ba5ff94784023c904ecfca/index.js#L188-L190
train
evanshortiss/yr.no-forecast
index.js
function() { const startDate = moment.utc(this.getFirstDateInPayload()); const baseDate = startDate.clone().set('hour', 12).startOf('hour'); let firstDate = baseDate.clone(); log(`five day summary is using ${baseDate.toString()} as a starting point`); /* istanbul ignore else */ if (firstDate.isBefore(startDate)) { // first date is unique since we may not have data back to midday so instead we // go with the earliest available firstDate = startDate.clone(); } log(`getting five day summary starting with ${firstDate.toISOString()}`); return Promise.all([ this.getForecastForTime(firstDate), this.getForecastForTime(baseDate.clone().add(1, 'days')), this.getForecastForTime(baseDate.clone().add(2, 'days')), this.getForecastForTime(baseDate.clone().add(3, 'days')), this.getForecastForTime(baseDate.clone().add(4, 'days')) ]) .then(function (results) { // Return a single array of objects return Array.prototype.concat.apply([], results); }); }
javascript
function() { const startDate = moment.utc(this.getFirstDateInPayload()); const baseDate = startDate.clone().set('hour', 12).startOf('hour'); let firstDate = baseDate.clone(); log(`five day summary is using ${baseDate.toString()} as a starting point`); /* istanbul ignore else */ if (firstDate.isBefore(startDate)) { // first date is unique since we may not have data back to midday so instead we // go with the earliest available firstDate = startDate.clone(); } log(`getting five day summary starting with ${firstDate.toISOString()}`); return Promise.all([ this.getForecastForTime(firstDate), this.getForecastForTime(baseDate.clone().add(1, 'days')), this.getForecastForTime(baseDate.clone().add(2, 'days')), this.getForecastForTime(baseDate.clone().add(3, 'days')), this.getForecastForTime(baseDate.clone().add(4, 'days')) ]) .then(function (results) { // Return a single array of objects return Array.prototype.concat.apply([], results); }); }
[ "function", "(", ")", "{", "const", "startDate", "=", "moment", ".", "utc", "(", "this", ".", "getFirstDateInPayload", "(", ")", ")", ";", "const", "baseDate", "=", "startDate", ".", "clone", "(", ")", ".", "set", "(", "'hour'", ",", "12", ")", ".", "startOf", "(", "'hour'", ")", ";", "let", "firstDate", "=", "baseDate", ".", "clone", "(", ")", ";", "log", "(", "`", "${", "baseDate", ".", "toString", "(", ")", "}", "`", ")", ";", "if", "(", "firstDate", ".", "isBefore", "(", "startDate", ")", ")", "{", "firstDate", "=", "startDate", ".", "clone", "(", ")", ";", "}", "log", "(", "`", "${", "firstDate", ".", "toISOString", "(", ")", "}", "`", ")", ";", "return", "Promise", ".", "all", "(", "[", "this", ".", "getForecastForTime", "(", "firstDate", ")", ",", "this", ".", "getForecastForTime", "(", "baseDate", ".", "clone", "(", ")", ".", "add", "(", "1", ",", "'days'", ")", ")", ",", "this", ".", "getForecastForTime", "(", "baseDate", ".", "clone", "(", ")", ".", "add", "(", "2", ",", "'days'", ")", ")", ",", "this", ".", "getForecastForTime", "(", "baseDate", ".", "clone", "(", ")", ".", "add", "(", "3", ",", "'days'", ")", ")", ",", "this", ".", "getForecastForTime", "(", "baseDate", ".", "clone", "(", ")", ".", "add", "(", "4", ",", "'days'", ")", ")", "]", ")", ".", "then", "(", "function", "(", "results", ")", "{", "return", "Array", ".", "prototype", ".", "concat", ".", "apply", "(", "[", "]", ",", "results", ")", ";", "}", ")", ";", "}" ]
Get five day weather. @param {Function} callback
[ "Get", "five", "day", "weather", "." ]
065320a3540d4b7890ba5ff94784023c904ecfca
https://github.com/evanshortiss/yr.no-forecast/blob/065320a3540d4b7890ba5ff94784023c904ecfca/index.js#L206-L233
train
evanshortiss/yr.no-forecast
index.js
function (time) { time = moment.utc(time); if (time.isValid() === false) { return Promise.reject( new Error('Invalid date provided for weather lookup') ); } if (time.minute() > 30) { time.add('hours', 1).startOf('hour'); } else { time.startOf('hour'); } log('getForecastForTime', dateToForecastISO(time)); let data = this.times[dateToForecastISO(time)] || null; /* istanbul ignore else */ if (!data && this.isInRange(time)) { data = this.fallbackSelector(time); } /* istanbul ignore else */ if (data) { data = Object.assign({}, data, data.location); delete data.location; } return Promise.resolve(data); }
javascript
function (time) { time = moment.utc(time); if (time.isValid() === false) { return Promise.reject( new Error('Invalid date provided for weather lookup') ); } if (time.minute() > 30) { time.add('hours', 1).startOf('hour'); } else { time.startOf('hour'); } log('getForecastForTime', dateToForecastISO(time)); let data = this.times[dateToForecastISO(time)] || null; /* istanbul ignore else */ if (!data && this.isInRange(time)) { data = this.fallbackSelector(time); } /* istanbul ignore else */ if (data) { data = Object.assign({}, data, data.location); delete data.location; } return Promise.resolve(data); }
[ "function", "(", "time", ")", "{", "time", "=", "moment", ".", "utc", "(", "time", ")", ";", "if", "(", "time", ".", "isValid", "(", ")", "===", "false", ")", "{", "return", "Promise", ".", "reject", "(", "new", "Error", "(", "'Invalid date provided for weather lookup'", ")", ")", ";", "}", "if", "(", "time", ".", "minute", "(", ")", ">", "30", ")", "{", "time", ".", "add", "(", "'hours'", ",", "1", ")", ".", "startOf", "(", "'hour'", ")", ";", "}", "else", "{", "time", ".", "startOf", "(", "'hour'", ")", ";", "}", "log", "(", "'getForecastForTime'", ",", "dateToForecastISO", "(", "time", ")", ")", ";", "let", "data", "=", "this", ".", "times", "[", "dateToForecastISO", "(", "time", ")", "]", "||", "null", ";", "if", "(", "!", "data", "&&", "this", ".", "isInRange", "(", "time", ")", ")", "{", "data", "=", "this", ".", "fallbackSelector", "(", "time", ")", ";", "}", "if", "(", "data", ")", "{", "data", "=", "Object", ".", "assign", "(", "{", "}", ",", "data", ",", "data", ".", "location", ")", ";", "delete", "data", ".", "location", ";", "}", "return", "Promise", ".", "resolve", "(", "data", ")", ";", "}" ]
Returns a forecast for a given time. @param {String|Date} time @param {Function} callback
[ "Returns", "a", "forecast", "for", "a", "given", "time", "." ]
065320a3540d4b7890ba5ff94784023c904ecfca
https://github.com/evanshortiss/yr.no-forecast/blob/065320a3540d4b7890ba5ff94784023c904ecfca/index.js#L255-L286
train
doowb/npm-api
lib/list.js
List
function List (name, view) { if (!(this instanceof List)) { return new List(name, view); } this.name = name; this.view = view; this.config = utils.clone(config); this.config.pathname += '/_list/' + this.view.name + '/' + this.name; }
javascript
function List (name, view) { if (!(this instanceof List)) { return new List(name, view); } this.name = name; this.view = view; this.config = utils.clone(config); this.config.pathname += '/_list/' + this.view.name + '/' + this.name; }
[ "function", "List", "(", "name", ",", "view", ")", "{", "if", "(", "!", "(", "this", "instanceof", "List", ")", ")", "{", "return", "new", "List", "(", "name", ",", "view", ")", ";", "}", "this", ".", "name", "=", "name", ";", "this", ".", "view", "=", "view", ";", "this", ".", "config", "=", "utils", ".", "clone", "(", "config", ")", ";", "this", ".", "config", ".", "pathname", "+=", "'/_list/'", "+", "this", ".", "view", ".", "name", "+", "'/'", "+", "this", ".", "name", ";", "}" ]
List constructor. Create an instance of a list associated with a couchdb list in the npm registry. ```js var list = new List('dependedUpon', view); ``` @param {String} `name` Name of couchdb list to use. @param {Object} `view` Instance of a View to use with the list. @returns {Object} instance of `List` @api public
[ "List", "constructor", ".", "Create", "an", "instance", "of", "a", "list", "associated", "with", "a", "couchdb", "list", "in", "the", "npm", "registry", "." ]
2204395a7da8815465c12ba147cd7622b9d5bae2
https://github.com/doowb/npm-api/blob/2204395a7da8815465c12ba147cd7622b9d5bae2/lib/list.js#L27-L35
train
doowb/npm-api
lib/models/repo.js
Repo
function Repo (name, store) { if (!(this instanceof Repo)) { return new Repo(name); } Base.call(this, store); this.is('repo'); this.name = name; this.use(downloads()); }
javascript
function Repo (name, store) { if (!(this instanceof Repo)) { return new Repo(name); } Base.call(this, store); this.is('repo'); this.name = name; this.use(downloads()); }
[ "function", "Repo", "(", "name", ",", "store", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Repo", ")", ")", "{", "return", "new", "Repo", "(", "name", ")", ";", "}", "Base", ".", "call", "(", "this", ",", "store", ")", ";", "this", ".", "is", "(", "'repo'", ")", ";", "this", ".", "name", "=", "name", ";", "this", ".", "use", "(", "downloads", "(", ")", ")", ";", "}" ]
Repo constructor. Create an instance of an npm repo by repo name. ```js var repo = new Repo('micromatch'); ``` @param {String} `name` Name of the npm repo to get information about. @param {Object} `store` Optional cache store instance for caching results. Defaults to a memory store. @api public
[ "Repo", "constructor", ".", "Create", "an", "instance", "of", "an", "npm", "repo", "by", "repo", "name", "." ]
2204395a7da8815465c12ba147cd7622b9d5bae2
https://github.com/doowb/npm-api/blob/2204395a7da8815465c12ba147cd7622b9d5bae2/lib/models/repo.js#L26-L34
train
ozum/sequelize-pg-generator
template/sequelize4/index.js
defineModel
function defineModel(file) { var object = require(file), options = object.options || {}, modelName = object.modelName; if (debug) { fs.writeSync(debugFD, 'var ' + modelName + ' = Sequelize.define("' + modelName + '",\n' + util.inspect(object.attributes) + ',\n' + util.inspect(options, {depth: null}) + ');\n\n\n'); } models[modelName] = sequelize.define(modelName, object.attributes, options); if (object.relations !== undefined) { relationships[modelName] = object.relations; } }
javascript
function defineModel(file) { var object = require(file), options = object.options || {}, modelName = object.modelName; if (debug) { fs.writeSync(debugFD, 'var ' + modelName + ' = Sequelize.define("' + modelName + '",\n' + util.inspect(object.attributes) + ',\n' + util.inspect(options, {depth: null}) + ');\n\n\n'); } models[modelName] = sequelize.define(modelName, object.attributes, options); if (object.relations !== undefined) { relationships[modelName] = object.relations; } }
[ "function", "defineModel", "(", "file", ")", "{", "var", "object", "=", "require", "(", "file", ")", ",", "options", "=", "object", ".", "options", "||", "{", "}", ",", "modelName", "=", "object", ".", "modelName", ";", "if", "(", "debug", ")", "{", "fs", ".", "writeSync", "(", "debugFD", ",", "'var '", "+", "modelName", "+", "' = Sequelize.define(\"'", "+", "modelName", "+", "'\",\\n'", "+", "\\n", "+", "util", ".", "inspect", "(", "object", ".", "attributes", ")", "+", "',\\n'", "+", "\\n", ")", ";", "}", "util", ".", "inspect", "(", "options", ",", "{", "depth", ":", "null", "}", ")", "');\\n\\n\\n'", "}" ]
Requires given npm module file and defines sequelize module according to exported object from that module. @private @param {string} file - Location of the npm module file which contains model definition.
[ "Requires", "given", "npm", "module", "file", "and", "defines", "sequelize", "module", "according", "to", "exported", "object", "from", "that", "module", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/template/sequelize4/index.js#L28-L41
train
ozum/sequelize-pg-generator
template/sequelize4/index.js
defineRelation
function defineRelation(modelName, relationType, targetModelName, options) { if (debug) { fs.writeSync(debugFD, modelName + '.' + relationType + '(' + targetModelName + ', ' + util.inspect(options, {depth: null}) + ');\n\n'); } models[modelName][relationType](models[targetModelName], options); // account.hasMany(contact, {...}) }
javascript
function defineRelation(modelName, relationType, targetModelName, options) { if (debug) { fs.writeSync(debugFD, modelName + '.' + relationType + '(' + targetModelName + ', ' + util.inspect(options, {depth: null}) + ');\n\n'); } models[modelName][relationType](models[targetModelName], options); // account.hasMany(contact, {...}) }
[ "function", "defineRelation", "(", "modelName", ",", "relationType", ",", "targetModelName", ",", "options", ")", "{", "if", "(", "debug", ")", "{", "fs", ".", "writeSync", "(", "debugFD", ",", "modelName", "+", "'.'", "+", "relationType", "+", "'('", "+", "targetModelName", "+", "', '", "+", "util", ".", "inspect", "(", "options", ",", "{", "depth", ":", "null", "}", ")", "+", "');\\n\\n'", ")", ";", "}", "\\n", "}" ]
Define 'hasMany' and 'belongsTo' relations. @private @param {string} modelName - Name of the model @param {string} relationType - Type of the relation 'hasMany' or 'belongsTo' @param {string} targetModelName - Name of the target model which this relation related to. @param {Object} options - Sequelize options of relation.
[ "Define", "hasMany", "and", "belongsTo", "relations", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/template/sequelize4/index.js#L52-L58
train
ozum/sequelize-pg-generator
template/sequelize4/index.js
getFileList
function getFileList() { var i, file, isOverridden = {}, files = [], customFiles, baseFiles; baseFiles = fs.readdirSync(path.join(modelsPath, definitionDir)); customFiles = fs.readdirSync(path.join(modelsPath, definitionDirCustom)); for (i = 0; i < customFiles.length; i = i + 1) { file = customFiles[i]; if (file.match(/\.js$/)) { isOverridden[file] = true; files.push('./' + path.join(definitionDirCustom, file)); } } for (i = 0; i < baseFiles.length; i = i + 1) { file = baseFiles[i]; if (!isOverridden[file] && file.match(/\.js$/)) { files.push('./' + path.join(definitionDir, file)); } } return files; }
javascript
function getFileList() { var i, file, isOverridden = {}, files = [], customFiles, baseFiles; baseFiles = fs.readdirSync(path.join(modelsPath, definitionDir)); customFiles = fs.readdirSync(path.join(modelsPath, definitionDirCustom)); for (i = 0; i < customFiles.length; i = i + 1) { file = customFiles[i]; if (file.match(/\.js$/)) { isOverridden[file] = true; files.push('./' + path.join(definitionDirCustom, file)); } } for (i = 0; i < baseFiles.length; i = i + 1) { file = baseFiles[i]; if (!isOverridden[file] && file.match(/\.js$/)) { files.push('./' + path.join(definitionDir, file)); } } return files; }
[ "function", "getFileList", "(", ")", "{", "var", "i", ",", "file", ",", "isOverridden", "=", "{", "}", ",", "files", "=", "[", "]", ",", "customFiles", ",", "baseFiles", ";", "baseFiles", "=", "fs", ".", "readdirSync", "(", "path", ".", "join", "(", "modelsPath", ",", "definitionDir", ")", ")", ";", "customFiles", "=", "fs", ".", "readdirSync", "(", "path", ".", "join", "(", "modelsPath", ",", "definitionDirCustom", ")", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "customFiles", ".", "length", ";", "i", "=", "i", "+", "1", ")", "{", "file", "=", "customFiles", "[", "i", "]", ";", "if", "(", "file", ".", "match", "(", "/", "\\.js$", "/", ")", ")", "{", "isOverridden", "[", "file", "]", "=", "true", ";", "files", ".", "push", "(", "'./'", "+", "path", ".", "join", "(", "definitionDirCustom", ",", "file", ")", ")", ";", "}", "}", "for", "(", "i", "=", "0", ";", "i", "<", "baseFiles", ".", "length", ";", "i", "=", "i", "+", "1", ")", "{", "file", "=", "baseFiles", "[", "i", "]", ";", "if", "(", "!", "isOverridden", "[", "file", "]", "&&", "file", ".", "match", "(", "/", "\\.js$", "/", ")", ")", "{", "files", ".", "push", "(", "'./'", "+", "path", ".", "join", "(", "definitionDir", ",", "file", ")", ")", ";", "}", "}", "return", "files", ";", "}" ]
Generates list of definition files by looking given modelsPath directory. It traverses 'definition-files' and 'definition-files-custom' directories to generate the list. Files in 'definition-files' will be skipped if a file with same name is found in 'definition-files-custom' directory. @private @returns {Array} @example var list = getFileList('../model'); // ['./definition-files-custom/public_cart.js', './definition-files/public_account.js]
[ "Generates", "list", "of", "definition", "files", "by", "looking", "given", "modelsPath", "directory", ".", "It", "traverses", "definition", "-", "files", "and", "definition", "-", "files", "-", "custom", "directories", "to", "generate", "the", "list", ".", "Files", "in", "definition", "-", "files", "will", "be", "skipped", "if", "a", "file", "with", "same", "name", "is", "found", "in", "definition", "-", "files", "-", "custom", "directory", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/template/sequelize4/index.js#L70-L90
train
ozum/sequelize-pg-generator
template/sequelize4/index.js
init
function init() { var debugFile = path.join(__dirname, 'debug.js'); if (debug) { if (fs.existsSync(debugFile)) { fs.unlinkSync(debugFile); } debugFD = fs.openSync(debugFile, 'a'); } getFileList(modelsPath).forEach(defineModel); processAllRelations(defineRelation); if (debug) { fs.closeSync(debugFD); } }
javascript
function init() { var debugFile = path.join(__dirname, 'debug.js'); if (debug) { if (fs.existsSync(debugFile)) { fs.unlinkSync(debugFile); } debugFD = fs.openSync(debugFile, 'a'); } getFileList(modelsPath).forEach(defineModel); processAllRelations(defineRelation); if (debug) { fs.closeSync(debugFD); } }
[ "function", "init", "(", ")", "{", "var", "debugFile", "=", "path", ".", "join", "(", "__dirname", ",", "'debug.js'", ")", ";", "if", "(", "debug", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "debugFile", ")", ")", "{", "fs", ".", "unlinkSync", "(", "debugFile", ")", ";", "}", "debugFD", "=", "fs", ".", "openSync", "(", "debugFile", ",", "'a'", ")", ";", "}", "getFileList", "(", "modelsPath", ")", ".", "forEach", "(", "defineModel", ")", ";", "processAllRelations", "(", "defineRelation", ")", ";", "if", "(", "debug", ")", "{", "fs", ".", "closeSync", "(", "debugFD", ")", ";", "}", "}" ]
Initializes models. @private
[ "Initializes", "models", "." ]
c38491b4d560981713a96a1923ad48d70e4aaff8
https://github.com/ozum/sequelize-pg-generator/blob/c38491b4d560981713a96a1923ad48d70e4aaff8/template/sequelize4/index.js#L119-L133
train
xBytez/slackbotapi
lib/index.js
slackAPI
function slackAPI(args, err_cb) { err_cb = err_cb || function () {}; var self = this; var authtoken = args.token; this.slackData = {}; this.token = ''; this.logging = true; this.autoReconnect = true; this.i = 0; if (typeof args !== 'object') { this.logging = true; this.out('error', errors.object_arg_required); throw new Error(errors.object_arg_required); } if (typeof args.logging !== 'boolean') { this.logging = true; this.out('error', errors.boolean_arg_required); } else { this.logging = args.logging; } if (!authtoken || typeof authtoken !== 'string' || !authtoken.match(/^([a-z]*)\-([0-9]*)\-([0-9a-zA-Z]*)/)) { this.logging = true; this.out('error', errors.invalid_token); throw new Error(errors.invalid_token); } if (typeof args.autoReconnect !== 'boolean') { this.autoReconnect = false; } else { this.autoReconnect = args.autoReconnect; } this.token = authtoken; self.reqAPI('rtm.start', {}, function (data) { if (!data.ok) return err_cb(data.error); self.slackData.self = data.self; self.slackData.team = data.team; self.slackData.channels = data.channels; self.slackData.groups = data.groups; self.slackData.users = data.users; self.slackData.ims = data.ims; self.connectSlack(data.url, function (err, data) { if (!err) { self.emit(events[data.type], data); } else { self.emit('error', data); } }); }); eventEmitter.call(this); }
javascript
function slackAPI(args, err_cb) { err_cb = err_cb || function () {}; var self = this; var authtoken = args.token; this.slackData = {}; this.token = ''; this.logging = true; this.autoReconnect = true; this.i = 0; if (typeof args !== 'object') { this.logging = true; this.out('error', errors.object_arg_required); throw new Error(errors.object_arg_required); } if (typeof args.logging !== 'boolean') { this.logging = true; this.out('error', errors.boolean_arg_required); } else { this.logging = args.logging; } if (!authtoken || typeof authtoken !== 'string' || !authtoken.match(/^([a-z]*)\-([0-9]*)\-([0-9a-zA-Z]*)/)) { this.logging = true; this.out('error', errors.invalid_token); throw new Error(errors.invalid_token); } if (typeof args.autoReconnect !== 'boolean') { this.autoReconnect = false; } else { this.autoReconnect = args.autoReconnect; } this.token = authtoken; self.reqAPI('rtm.start', {}, function (data) { if (!data.ok) return err_cb(data.error); self.slackData.self = data.self; self.slackData.team = data.team; self.slackData.channels = data.channels; self.slackData.groups = data.groups; self.slackData.users = data.users; self.slackData.ims = data.ims; self.connectSlack(data.url, function (err, data) { if (!err) { self.emit(events[data.type], data); } else { self.emit('error', data); } }); }); eventEmitter.call(this); }
[ "function", "slackAPI", "(", "args", ",", "err_cb", ")", "{", "err_cb", "=", "err_cb", "||", "function", "(", ")", "{", "}", ";", "var", "self", "=", "this", ";", "var", "authtoken", "=", "args", ".", "token", ";", "this", ".", "slackData", "=", "{", "}", ";", "this", ".", "token", "=", "''", ";", "this", ".", "logging", "=", "true", ";", "this", ".", "autoReconnect", "=", "true", ";", "this", ".", "i", "=", "0", ";", "if", "(", "typeof", "args", "!==", "'object'", ")", "{", "this", ".", "logging", "=", "true", ";", "this", ".", "out", "(", "'error'", ",", "errors", ".", "object_arg_required", ")", ";", "throw", "new", "Error", "(", "errors", ".", "object_arg_required", ")", ";", "}", "if", "(", "typeof", "args", ".", "logging", "!==", "'boolean'", ")", "{", "this", ".", "logging", "=", "true", ";", "this", ".", "out", "(", "'error'", ",", "errors", ".", "boolean_arg_required", ")", ";", "}", "else", "{", "this", ".", "logging", "=", "args", ".", "logging", ";", "}", "if", "(", "!", "authtoken", "||", "typeof", "authtoken", "!==", "'string'", "||", "!", "authtoken", ".", "match", "(", "/", "^([a-z]*)\\-([0-9]*)\\-([0-9a-zA-Z]*)", "/", ")", ")", "{", "this", ".", "logging", "=", "true", ";", "this", ".", "out", "(", "'error'", ",", "errors", ".", "invalid_token", ")", ";", "throw", "new", "Error", "(", "errors", ".", "invalid_token", ")", ";", "}", "if", "(", "typeof", "args", ".", "autoReconnect", "!==", "'boolean'", ")", "{", "this", ".", "autoReconnect", "=", "false", ";", "}", "else", "{", "this", ".", "autoReconnect", "=", "args", ".", "autoReconnect", ";", "}", "this", ".", "token", "=", "authtoken", ";", "self", ".", "reqAPI", "(", "'rtm.start'", ",", "{", "}", ",", "function", "(", "data", ")", "{", "if", "(", "!", "data", ".", "ok", ")", "return", "err_cb", "(", "data", ".", "error", ")", ";", "self", ".", "slackData", ".", "self", "=", "data", ".", "self", ";", "self", ".", "slackData", ".", "team", "=", "data", ".", "team", ";", "self", ".", "slackData", ".", "channels", "=", "data", ".", "channels", ";", "self", ".", "slackData", ".", "groups", "=", "data", ".", "groups", ";", "self", ".", "slackData", ".", "users", "=", "data", ".", "users", ";", "self", ".", "slackData", ".", "ims", "=", "data", ".", "ims", ";", "self", ".", "connectSlack", "(", "data", ".", "url", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "!", "err", ")", "{", "self", ".", "emit", "(", "events", "[", "data", ".", "type", "]", ",", "data", ")", ";", "}", "else", "{", "self", ".", "emit", "(", "'error'", ",", "data", ")", ";", "}", "}", ")", ";", "}", ")", ";", "eventEmitter", ".", "call", "(", "this", ")", ";", "}" ]
Spawn the API @param object args Arguments to start the bot with for example the auth token. @param function err_cb Callback if boot failed @example new slackAPI({'token': 'xo-abcdeftokenhere', 'logging': true, autoReconnect: true})
[ "Spawn", "the", "API" ]
3f79050f75a2282dcf92f4fecbb83beec32e8baa
https://github.com/xBytez/slackbotapi/blob/3f79050f75a2282dcf92f4fecbb83beec32e8baa/lib/index.js#L28-L88
train
apollographql/optics-agent-js
src/separateOperations.js
collectTransitiveDependencies
function collectTransitiveDependencies( collected, depGraph, fromName ) { const immediateDeps = depGraph[fromName]; if (immediateDeps) { Object.keys(immediateDeps).forEach(toName => { if (!collected[toName]) { collected[toName] = true; collectTransitiveDependencies(collected, depGraph, toName); } }); } }
javascript
function collectTransitiveDependencies( collected, depGraph, fromName ) { const immediateDeps = depGraph[fromName]; if (immediateDeps) { Object.keys(immediateDeps).forEach(toName => { if (!collected[toName]) { collected[toName] = true; collectTransitiveDependencies(collected, depGraph, toName); } }); } }
[ "function", "collectTransitiveDependencies", "(", "collected", ",", "depGraph", ",", "fromName", ")", "{", "const", "immediateDeps", "=", "depGraph", "[", "fromName", "]", ";", "if", "(", "immediateDeps", ")", "{", "Object", ".", "keys", "(", "immediateDeps", ")", ".", "forEach", "(", "toName", "=>", "{", "if", "(", "!", "collected", "[", "toName", "]", ")", "{", "collected", "[", "toName", "]", "=", "true", ";", "collectTransitiveDependencies", "(", "collected", ",", "depGraph", ",", "toName", ")", ";", "}", "}", ")", ";", "}", "}" ]
From a dependency graph, collects a list of transitive dependencies by recursing through a dependency graph.
[ "From", "a", "dependency", "graph", "collects", "a", "list", "of", "transitive", "dependencies", "by", "recursing", "through", "a", "dependency", "graph", "." ]
79040897a0faf96aa09ce9805f8d649f879a45ea
https://github.com/apollographql/optics-agent-js/blob/79040897a0faf96aa09ce9805f8d649f879a45ea/src/separateOperations.js#L87-L101
train
IBM-Cloud/gp-js-client
util/gen-html.js
convertMarkdown
function convertMarkdown(opts) { return new Promise((resolve, reject) => { marked(opts.data, {}, (err, content) => { if(err) return reject(err); return resolve(content); }); }); }
javascript
function convertMarkdown(opts) { return new Promise((resolve, reject) => { marked(opts.data, {}, (err, content) => { if(err) return reject(err); return resolve(content); }); }); }
[ "function", "convertMarkdown", "(", "opts", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "marked", "(", "opts", ".", "data", ",", "{", "}", ",", "(", "err", ",", "content", ")", "=>", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", ";", "return", "resolve", "(", "content", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Convert input to markdown, return data @param {Object} opts @param {String} opts.data
[ "Convert", "input", "to", "markdown", "return", "data" ]
4dc60e9ceedf0366ec084f6aaa9d73639941495f
https://github.com/IBM-Cloud/gp-js-client/blob/4dc60e9ceedf0366ec084f6aaa9d73639941495f/util/gen-html.js#L38-L45
train
jonschlinkert/handlebars-delimiters
index.js
replaceDelimiters
function replaceDelimiters(str, source, escape) { var regex = cache[source] || (cache[source] = new RegExp(source, 'g')); var match; while ((match = regex.exec(str))) { var prefix = str.slice(0, match.index); var inner = (escape ? '\\' : '') + '{{' + match[1] + '}}'; var suffix = str.slice(match.index + match[0].length); str = prefix + inner + suffix; } return str; }
javascript
function replaceDelimiters(str, source, escape) { var regex = cache[source] || (cache[source] = new RegExp(source, 'g')); var match; while ((match = regex.exec(str))) { var prefix = str.slice(0, match.index); var inner = (escape ? '\\' : '') + '{{' + match[1] + '}}'; var suffix = str.slice(match.index + match[0].length); str = prefix + inner + suffix; } return str; }
[ "function", "replaceDelimiters", "(", "str", ",", "source", ",", "escape", ")", "{", "var", "regex", "=", "cache", "[", "source", "]", "||", "(", "cache", "[", "source", "]", "=", "new", "RegExp", "(", "source", ",", "'g'", ")", ")", ";", "var", "match", ";", "while", "(", "(", "match", "=", "regex", ".", "exec", "(", "str", ")", ")", ")", "{", "var", "prefix", "=", "str", ".", "slice", "(", "0", ",", "match", ".", "index", ")", ";", "var", "inner", "=", "(", "escape", "?", "'\\\\'", ":", "\\\\", ")", "+", "''", "+", "'{{'", "+", "match", "[", "1", "]", ";", "'}}'", "var", "suffix", "=", "str", ".", "slice", "(", "match", ".", "index", "+", "match", "[", "0", "]", ".", "length", ")", ";", "}", "str", "=", "prefix", "+", "inner", "+", "suffix", ";", "}" ]
Replace or delimiters in the given string. ```js var replaced = delimiters.replace(str, ['<%=', '%>']); ``` @name .replace @param {String} `str` String with handlebars to replace or escape. @param {String} `source` The delimiters regex source string to conver to a regular expression. @param {Boolean} `escape` If true, replacements are escaped with a double-slash. @return {String} @api public
[ "Replace", "or", "delimiters", "in", "the", "given", "string", "." ]
2a4e3ae2ddca26f950ddd5ecf6824a897d5bcf2c
https://github.com/jonschlinkert/handlebars-delimiters/blob/2a4e3ae2ddca26f950ddd5ecf6824a897d5bcf2c/index.js#L71-L82
train
MiSchroe/klf-200-api
dist/utils/BitArray.js
bitArrayToArray
function bitArrayToArray(bitArray) { let resultArray = []; for (let index = 0; index < bitArray.byteLength; index++) { let arrayByte = bitArray.readUInt8(index); // Skip bit operations if zero -> no bit is set if (arrayByte !== 0) { for (let bitIndex = 0; bitIndex < 8; bitIndex++) { if ((arrayByte & 0x01) === 0x01) { resultArray.push(index * 8 + bitIndex); } arrayByte = arrayByte >>> 1; } } } return resultArray; }
javascript
function bitArrayToArray(bitArray) { let resultArray = []; for (let index = 0; index < bitArray.byteLength; index++) { let arrayByte = bitArray.readUInt8(index); // Skip bit operations if zero -> no bit is set if (arrayByte !== 0) { for (let bitIndex = 0; bitIndex < 8; bitIndex++) { if ((arrayByte & 0x01) === 0x01) { resultArray.push(index * 8 + bitIndex); } arrayByte = arrayByte >>> 1; } } } return resultArray; }
[ "function", "bitArrayToArray", "(", "bitArray", ")", "{", "let", "resultArray", "=", "[", "]", ";", "for", "(", "let", "index", "=", "0", ";", "index", "<", "bitArray", ".", "byteLength", ";", "index", "++", ")", "{", "let", "arrayByte", "=", "bitArray", ".", "readUInt8", "(", "index", ")", ";", "if", "(", "arrayByte", "!==", "0", ")", "{", "for", "(", "let", "bitIndex", "=", "0", ";", "bitIndex", "<", "8", ";", "bitIndex", "++", ")", "{", "if", "(", "(", "arrayByte", "&", "0x01", ")", "===", "0x01", ")", "{", "resultArray", ".", "push", "(", "index", "*", "8", "+", "bitIndex", ")", ";", "}", "arrayByte", "=", "arrayByte", ">>>", "1", ";", "}", "}", "}", "return", "resultArray", ";", "}" ]
Converts a binary bit array to an array of numbers. @export @param {Buffer} bitArray Bytes where each bit is set for the corresponding number, e.g. the node ID. @returns {number[]} Returns an array of numbers with an entry for each set bit.
[ "Converts", "a", "binary", "bit", "array", "to", "an", "array", "of", "numbers", "." ]
f82356dcd9e43b47cf492817717268db181a06c4
https://github.com/MiSchroe/klf-200-api/blob/f82356dcd9e43b47cf492817717268db181a06c4/dist/utils/BitArray.js#L10-L25
train
MiSchroe/klf-200-api
dist/utils/BitArray.js
arrayToBitArray
function arrayToBitArray(numberArray, bufferLength, destinationBuffer) { const returnBuffer = destinationBuffer ? destinationBuffer : Buffer.alloc(bufferLength); if (destinationBuffer) { // Get the bufferLength from the destination buffer, if one is provided bufferLength = destinationBuffer.byteLength; } const maxAllowedNumber = bufferLength * 8 - 1; // Max. allowed number is defined by the buffer size // Fill buffer with zeros first returnBuffer.fill(0); // Write bits for (let index = 0; index < numberArray.length; index++) { // Check for valid number const numberToWrite = numberArray[index]; if (numberToWrite < 0 || numberToWrite > maxAllowedNumber) throw new Error("Number out of range."); // Set bit returnBuffer[Math.floor(numberToWrite / 8)] |= 1 << (numberToWrite % 8); // numberToWrite / 8 = byte position (0-bufferLength), numberToWrite % 8 = bit position (0-7) } return returnBuffer; }
javascript
function arrayToBitArray(numberArray, bufferLength, destinationBuffer) { const returnBuffer = destinationBuffer ? destinationBuffer : Buffer.alloc(bufferLength); if (destinationBuffer) { // Get the bufferLength from the destination buffer, if one is provided bufferLength = destinationBuffer.byteLength; } const maxAllowedNumber = bufferLength * 8 - 1; // Max. allowed number is defined by the buffer size // Fill buffer with zeros first returnBuffer.fill(0); // Write bits for (let index = 0; index < numberArray.length; index++) { // Check for valid number const numberToWrite = numberArray[index]; if (numberToWrite < 0 || numberToWrite > maxAllowedNumber) throw new Error("Number out of range."); // Set bit returnBuffer[Math.floor(numberToWrite / 8)] |= 1 << (numberToWrite % 8); // numberToWrite / 8 = byte position (0-bufferLength), numberToWrite % 8 = bit position (0-7) } return returnBuffer; }
[ "function", "arrayToBitArray", "(", "numberArray", ",", "bufferLength", ",", "destinationBuffer", ")", "{", "const", "returnBuffer", "=", "destinationBuffer", "?", "destinationBuffer", ":", "Buffer", ".", "alloc", "(", "bufferLength", ")", ";", "if", "(", "destinationBuffer", ")", "{", "bufferLength", "=", "destinationBuffer", ".", "byteLength", ";", "}", "const", "maxAllowedNumber", "=", "bufferLength", "*", "8", "-", "1", ";", "returnBuffer", ".", "fill", "(", "0", ")", ";", "for", "(", "let", "index", "=", "0", ";", "index", "<", "numberArray", ".", "length", ";", "index", "++", ")", "{", "const", "numberToWrite", "=", "numberArray", "[", "index", "]", ";", "if", "(", "numberToWrite", "<", "0", "||", "numberToWrite", ">", "maxAllowedNumber", ")", "throw", "new", "Error", "(", "\"Number out of range.\"", ")", ";", "returnBuffer", "[", "Math", ".", "floor", "(", "numberToWrite", "/", "8", ")", "]", "|=", "1", "<<", "(", "numberToWrite", "%", "8", ")", ";", "}", "return", "returnBuffer", ";", "}" ]
Converts an array of numbers to a binary bit array. @export @param {number[]} numberArray Each number in the array corresponds to the bit that has to be set in the buffer. @param {number} bufferLength Length of the resulting buffer. This value will be ignored, if a destination buffer is provided. @param {Buffer} [destinationBuffer] Instead of creating a new buffer, the result can be written directly to an existing buffer. @returns {Buffer} Returns a new buffer with the bit array or the destination buffer, if a value for the destination buffer is provided.
[ "Converts", "an", "array", "of", "numbers", "to", "a", "binary", "bit", "array", "." ]
f82356dcd9e43b47cf492817717268db181a06c4
https://github.com/MiSchroe/klf-200-api/blob/f82356dcd9e43b47cf492817717268db181a06c4/dist/utils/BitArray.js#L36-L55
train
postcss/postcss-color
index.js
gnuMessage
function gnuMessage(message, source) { return (source ? (source.file ? source.file : "<css input>") + ":" + source.start.line + ":" + source.start.column : "") + " " + message }
javascript
function gnuMessage(message, source) { return (source ? (source.file ? source.file : "<css input>") + ":" + source.start.line + ":" + source.start.column : "") + " " + message }
[ "function", "gnuMessage", "(", "message", ",", "source", ")", "{", "return", "(", "source", "?", "(", "source", ".", "file", "?", "source", ".", "file", ":", "\"<css input>\"", ")", "+", "\":\"", "+", "source", ".", "start", ".", "line", "+", "\":\"", "+", "source", ".", "start", ".", "column", ":", "\"\"", ")", "+", "\" \"", "+", "message", "}" ]
return GNU style message @param {String} message @param {Object} source
[ "return", "GNU", "style", "message" ]
5fce65b72e62d1d3a965edfd1259d7c2e59c035c
https://github.com/postcss/postcss-color/blob/5fce65b72e62d1d3a965edfd1259d7c2e59c035c/index.js#L71-L73
train
endpoints/endpoints
es5/store-bookshelf/lib/read.js
read
function read(model) { var query = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var mode = arguments.length <= 2 || arguments[2] === undefined ? 'read' : arguments[2]; return _columns2['default'](model).then(function (modelColumns) { var fields = query.fields && query.fields[_type2['default'](model)]; var relations = _lodash2['default'].intersection(_all_relations2['default'](model), query.include || []); if (fields) { fields = _lodash2['default'].intersection(modelColumns, fields); // ensure we always select id as the spec requires this to be present if (!_lodash2['default'].contains(fields, 'id')) { fields.push('id'); } } return model.collection().query(function (qb) { qb = processFilter(model, qb, query.filter); qb = processSort(model.columns, qb, query.sort); }).fetch({ // adding this in the queryBuilder changes the qb, but fetch still // returns all columns columns: fields, withRelated: relations }).then(function (result) { // This is a lot of gross in order to pass this data into the // formatter later. Need to formalize this in some other way. result.mode = mode; result.relations = relations; result.singleResult = query.singleResult; result.baseType = query.baseType; result.baseId = query.baseId; result.baseRelation = query.baseRelation; return result; }); }); }
javascript
function read(model) { var query = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; var mode = arguments.length <= 2 || arguments[2] === undefined ? 'read' : arguments[2]; return _columns2['default'](model).then(function (modelColumns) { var fields = query.fields && query.fields[_type2['default'](model)]; var relations = _lodash2['default'].intersection(_all_relations2['default'](model), query.include || []); if (fields) { fields = _lodash2['default'].intersection(modelColumns, fields); // ensure we always select id as the spec requires this to be present if (!_lodash2['default'].contains(fields, 'id')) { fields.push('id'); } } return model.collection().query(function (qb) { qb = processFilter(model, qb, query.filter); qb = processSort(model.columns, qb, query.sort); }).fetch({ // adding this in the queryBuilder changes the qb, but fetch still // returns all columns columns: fields, withRelated: relations }).then(function (result) { // This is a lot of gross in order to pass this data into the // formatter later. Need to formalize this in some other way. result.mode = mode; result.relations = relations; result.singleResult = query.singleResult; result.baseType = query.baseType; result.baseId = query.baseId; result.baseRelation = query.baseRelation; return result; }); }); }
[ "function", "read", "(", "model", ")", "{", "var", "query", "=", "arguments", ".", "length", "<=", "1", "||", "arguments", "[", "1", "]", "===", "undefined", "?", "{", "}", ":", "arguments", "[", "1", "]", ";", "var", "mode", "=", "arguments", ".", "length", "<=", "2", "||", "arguments", "[", "2", "]", "===", "undefined", "?", "'read'", ":", "arguments", "[", "2", "]", ";", "return", "_columns2", "[", "'default'", "]", "(", "model", ")", ".", "then", "(", "function", "(", "modelColumns", ")", "{", "var", "fields", "=", "query", ".", "fields", "&&", "query", ".", "fields", "[", "_type2", "[", "'default'", "]", "(", "model", ")", "]", ";", "var", "relations", "=", "_lodash2", "[", "'default'", "]", ".", "intersection", "(", "_all_relations2", "[", "'default'", "]", "(", "model", ")", ",", "query", ".", "include", "||", "[", "]", ")", ";", "if", "(", "fields", ")", "{", "fields", "=", "_lodash2", "[", "'default'", "]", ".", "intersection", "(", "modelColumns", ",", "fields", ")", ";", "if", "(", "!", "_lodash2", "[", "'default'", "]", ".", "contains", "(", "fields", ",", "'id'", ")", ")", "{", "fields", ".", "push", "(", "'id'", ")", ";", "}", "}", "return", "model", ".", "collection", "(", ")", ".", "query", "(", "function", "(", "qb", ")", "{", "qb", "=", "processFilter", "(", "model", ",", "qb", ",", "query", ".", "filter", ")", ";", "qb", "=", "processSort", "(", "model", ".", "columns", ",", "qb", ",", "query", ".", "sort", ")", ";", "}", ")", ".", "fetch", "(", "{", "columns", ":", "fields", ",", "withRelated", ":", "relations", "}", ")", ".", "then", "(", "function", "(", "result", ")", "{", "result", ".", "mode", "=", "mode", ";", "result", ".", "relations", "=", "relations", ";", "result", ".", "singleResult", "=", "query", ".", "singleResult", ";", "result", ".", "baseType", "=", "query", ".", "baseType", ";", "result", ".", "baseId", "=", "query", ".", "baseId", ";", "result", ".", "baseRelation", "=", "query", ".", "baseRelation", ";", "return", "result", ";", "}", ")", ";", "}", ")", ";", "}" ]
Retrieves a collection of models from the database. @param {Bookshelf.Model} model - a bookshelf model class @param {Object} query - the output of Request#query @param {Object} mode - the mode of the request (single/related/relation) @return {Promise.Bookshelf.Collection} Models that match the request.
[ "Retrieves", "a", "collection", "of", "models", "from", "the", "database", "." ]
1ef8dd72a2e25cd44e534cedaba89f11ad70e19e
https://github.com/endpoints/endpoints/blob/1ef8dd72a2e25cd44e534cedaba89f11ad70e19e/es5/store-bookshelf/lib/read.js#L33-L67
train
endpoints/endpoints
es5/store-bookshelf/lib/related.js
related
function related(input, relation) { return relation.split('.').reduce(function (input, relationSegment) { if (_is_many2['default'](input)) { // iterate each model and add its related models to the collection return input.reduce(function (result, model) { var related = model.related(relationSegment); return result.add(related.models ? related.models : related); }, _related_collection2['default'](input.model, relationSegment)); } return input.related(relationSegment); }, input); }
javascript
function related(input, relation) { return relation.split('.').reduce(function (input, relationSegment) { if (_is_many2['default'](input)) { // iterate each model and add its related models to the collection return input.reduce(function (result, model) { var related = model.related(relationSegment); return result.add(related.models ? related.models : related); }, _related_collection2['default'](input.model, relationSegment)); } return input.related(relationSegment); }, input); }
[ "function", "related", "(", "input", ",", "relation", ")", "{", "return", "relation", ".", "split", "(", "'.'", ")", ".", "reduce", "(", "function", "(", "input", ",", "relationSegment", ")", "{", "if", "(", "_is_many2", "[", "'default'", "]", "(", "input", ")", ")", "{", "return", "input", ".", "reduce", "(", "function", "(", "result", ",", "model", ")", "{", "var", "related", "=", "model", ".", "related", "(", "relationSegment", ")", ";", "return", "result", ".", "add", "(", "related", ".", "models", "?", "related", ".", "models", ":", "related", ")", ";", "}", ",", "_related_collection2", "[", "'default'", "]", "(", "input", ".", "model", ",", "relationSegment", ")", ")", ";", "}", "return", "input", ".", "related", "(", "relationSegment", ")", ";", "}", ",", "input", ")", ";", "}" ]
Given a model or collection and a dot-notated relation string, traverse the relations and return the related models from the last segment in the relation string. @param {Bookshelf.Model|Bookshelf.Collection} input @param {String} relation @return {Bookshelf.Model|Bookshelf.Collection}
[ "Given", "a", "model", "or", "collection", "and", "a", "dot", "-", "notated", "relation", "string", "traverse", "the", "relations", "and", "return", "the", "related", "models", "from", "the", "last", "segment", "in", "the", "relation", "string", "." ]
1ef8dd72a2e25cd44e534cedaba89f11ad70e19e
https://github.com/endpoints/endpoints/blob/1ef8dd72a2e25cd44e534cedaba89f11ad70e19e/es5/store-bookshelf/lib/related.js#L26-L37
train
endpoints/endpoints
es5/store-bookshelf/lib/destroy_relation.js
destroyRelation
function destroyRelation(model, relations) { if (!model) { throw new Error('No model provided.'); } return _destructure2['default'](model, relations).then(function (destructured) { var relations = destructured.relations; return _transact2['default'](model, function (transaction) { return _relate2['default'](model, relations, 'delete', transaction); }); }); }
javascript
function destroyRelation(model, relations) { if (!model) { throw new Error('No model provided.'); } return _destructure2['default'](model, relations).then(function (destructured) { var relations = destructured.relations; return _transact2['default'](model, function (transaction) { return _relate2['default'](model, relations, 'delete', transaction); }); }); }
[ "function", "destroyRelation", "(", "model", ",", "relations", ")", "{", "if", "(", "!", "model", ")", "{", "throw", "new", "Error", "(", "'No model provided.'", ")", ";", "}", "return", "_destructure2", "[", "'default'", "]", "(", "model", ",", "relations", ")", ".", "then", "(", "function", "(", "destructured", ")", "{", "var", "relations", "=", "destructured", ".", "relations", ";", "return", "_transact2", "[", "'default'", "]", "(", "model", ",", "function", "(", "transaction", ")", "{", "return", "_relate2", "[", "'default'", "]", "(", "model", ",", "relations", ",", "'delete'", ",", "transaction", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Destroys relations on a model. @param {Bookshelf.Model} model - A bookshelf model instance @param {Object} relations - An object containing the relations. @return {Promise.Bookshelf.Model} The updated model.
[ "Destroys", "relations", "on", "a", "model", "." ]
1ef8dd72a2e25cd44e534cedaba89f11ad70e19e
https://github.com/endpoints/endpoints/blob/1ef8dd72a2e25cd44e534cedaba89f11ad70e19e/es5/store-bookshelf/lib/destroy_relation.js#L28-L38
train
anvaka/ngraph.physics.simulator
lib/spring.js
Spring
function Spring(fromBody, toBody, length, coeff, weight) { this.from = fromBody; this.to = toBody; this.length = length; this.coeff = coeff; this.weight = typeof weight === 'number' ? weight : 1; }
javascript
function Spring(fromBody, toBody, length, coeff, weight) { this.from = fromBody; this.to = toBody; this.length = length; this.coeff = coeff; this.weight = typeof weight === 'number' ? weight : 1; }
[ "function", "Spring", "(", "fromBody", ",", "toBody", ",", "length", ",", "coeff", ",", "weight", ")", "{", "this", ".", "from", "=", "fromBody", ";", "this", ".", "to", "=", "toBody", ";", "this", ".", "length", "=", "length", ";", "this", ".", "coeff", "=", "coeff", ";", "this", ".", "weight", "=", "typeof", "weight", "===", "'number'", "?", "weight", ":", "1", ";", "}" ]
Represents a physical spring. Spring connects two bodies, has rest length stiffness coefficient and optional weight
[ "Represents", "a", "physical", "spring", ".", "Spring", "connects", "two", "bodies", "has", "rest", "length", "stiffness", "coefficient", "and", "optional", "weight" ]
4483a9b3c9b0c53bceb61aef6921a61b9f0f7295
https://github.com/anvaka/ngraph.physics.simulator/blob/4483a9b3c9b0c53bceb61aef6921a61b9f0f7295/lib/spring.js#L7-L14
train
anvaka/ngraph.physics.simulator
index.js
function (pos) { if (!pos) { throw new Error('Body position is required'); } var body = createBody(pos); bodies.push(body); return body; }
javascript
function (pos) { if (!pos) { throw new Error('Body position is required'); } var body = createBody(pos); bodies.push(body); return body; }
[ "function", "(", "pos", ")", "{", "if", "(", "!", "pos", ")", "{", "throw", "new", "Error", "(", "'Body position is required'", ")", ";", "}", "var", "body", "=", "createBody", "(", "pos", ")", ";", "bodies", ".", "push", "(", "body", ")", ";", "return", "body", ";", "}" ]
Adds body to the system at given position @param {Object} pos position of a body @returns {ngraph.physics.primitives.Body} added body
[ "Adds", "body", "to", "the", "system", "at", "given", "position" ]
4483a9b3c9b0c53bceb61aef6921a61b9f0f7295
https://github.com/anvaka/ngraph.physics.simulator/blob/4483a9b3c9b0c53bceb61aef6921a61b9f0f7295/index.js#L128-L136
train
anvaka/ngraph.physics.simulator
index.js
function (body) { if (!body) { return; } var idx = bodies.indexOf(body); if (idx < 0) { return; } bodies.splice(idx, 1); if (bodies.length === 0) { bounds.reset(); } return true; }
javascript
function (body) { if (!body) { return; } var idx = bodies.indexOf(body); if (idx < 0) { return; } bodies.splice(idx, 1); if (bodies.length === 0) { bounds.reset(); } return true; }
[ "function", "(", "body", ")", "{", "if", "(", "!", "body", ")", "{", "return", ";", "}", "var", "idx", "=", "bodies", ".", "indexOf", "(", "body", ")", ";", "if", "(", "idx", "<", "0", ")", "{", "return", ";", "}", "bodies", ".", "splice", "(", "idx", ",", "1", ")", ";", "if", "(", "bodies", ".", "length", "===", "0", ")", "{", "bounds", ".", "reset", "(", ")", ";", "}", "return", "true", ";", "}" ]
Removes body from the system @param {ngraph.physics.primitives.Body} body to remove @returns {Boolean} true if body found and removed. falsy otherwise;
[ "Removes", "body", "from", "the", "system" ]
4483a9b3c9b0c53bceb61aef6921a61b9f0f7295
https://github.com/anvaka/ngraph.physics.simulator/blob/4483a9b3c9b0c53bceb61aef6921a61b9f0f7295/index.js#L145-L156
train
anvaka/ngraph.physics.simulator
index.js
function (body1, body2, springLength, springWeight, springCoefficient) { if (!body1 || !body2) { throw new Error('Cannot add null spring to force simulator'); } if (typeof springLength !== 'number') { springLength = -1; // assume global configuration } var spring = new Spring(body1, body2, springLength, springCoefficient >= 0 ? springCoefficient : -1, springWeight); springs.push(spring); // TODO: could mark simulator as dirty. return spring; }
javascript
function (body1, body2, springLength, springWeight, springCoefficient) { if (!body1 || !body2) { throw new Error('Cannot add null spring to force simulator'); } if (typeof springLength !== 'number') { springLength = -1; // assume global configuration } var spring = new Spring(body1, body2, springLength, springCoefficient >= 0 ? springCoefficient : -1, springWeight); springs.push(spring); // TODO: could mark simulator as dirty. return spring; }
[ "function", "(", "body1", ",", "body2", ",", "springLength", ",", "springWeight", ",", "springCoefficient", ")", "{", "if", "(", "!", "body1", "||", "!", "body2", ")", "{", "throw", "new", "Error", "(", "'Cannot add null spring to force simulator'", ")", ";", "}", "if", "(", "typeof", "springLength", "!==", "'number'", ")", "{", "springLength", "=", "-", "1", ";", "}", "var", "spring", "=", "new", "Spring", "(", "body1", ",", "body2", ",", "springLength", ",", "springCoefficient", ">=", "0", "?", "springCoefficient", ":", "-", "1", ",", "springWeight", ")", ";", "springs", ".", "push", "(", "spring", ")", ";", "return", "spring", ";", "}" ]
Adds a spring to this simulation. @returns {Object} - a handle for a spring. If you want to later remove spring pass it to removeSpring() method.
[ "Adds", "a", "spring", "to", "this", "simulation", "." ]
4483a9b3c9b0c53bceb61aef6921a61b9f0f7295
https://github.com/anvaka/ngraph.physics.simulator/blob/4483a9b3c9b0c53bceb61aef6921a61b9f0f7295/index.js#L164-L178
train
anvaka/ngraph.physics.simulator
index.js
function (spring) { if (!spring) { return; } var idx = springs.indexOf(spring); if (idx > -1) { springs.splice(idx, 1); return true; } }
javascript
function (spring) { if (!spring) { return; } var idx = springs.indexOf(spring); if (idx > -1) { springs.splice(idx, 1); return true; } }
[ "function", "(", "spring", ")", "{", "if", "(", "!", "spring", ")", "{", "return", ";", "}", "var", "idx", "=", "springs", ".", "indexOf", "(", "spring", ")", ";", "if", "(", "idx", ">", "-", "1", ")", "{", "springs", ".", "splice", "(", "idx", ",", "1", ")", ";", "return", "true", ";", "}", "}" ]
Removes spring from the system @param {Object} spring to remove. Spring is an object returned by addSpring @returns {Boolean} true if spring found and removed. falsy otherwise;
[ "Removes", "spring", "from", "the", "system" ]
4483a9b3c9b0c53bceb61aef6921a61b9f0f7295
https://github.com/anvaka/ngraph.physics.simulator/blob/4483a9b3c9b0c53bceb61aef6921a61b9f0f7295/index.js#L194-L201
train
endpoints/endpoints
es5/store-bookshelf/lib/create.js
create
function create(model) { var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; if (!model) { throw new Error('No model provided.'); } return _destructure2['default'](model.forge(), params).then(function (destructured) { var attributes = destructured.attributes; var relations = destructured.relations; return _transact2['default'](model, function (transaction) { return model.forge(attributes).save(null, { method: 'insert', transacting: transaction }).tap(function (newModel) { return _relate2['default'](newModel, relations, 'create', transaction); }).then(function (newModel) { return model.forge({ id: newModel.id }).fetch({ transacting: transaction }); }); }); }); }
javascript
function create(model) { var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; if (!model) { throw new Error('No model provided.'); } return _destructure2['default'](model.forge(), params).then(function (destructured) { var attributes = destructured.attributes; var relations = destructured.relations; return _transact2['default'](model, function (transaction) { return model.forge(attributes).save(null, { method: 'insert', transacting: transaction }).tap(function (newModel) { return _relate2['default'](newModel, relations, 'create', transaction); }).then(function (newModel) { return model.forge({ id: newModel.id }).fetch({ transacting: transaction }); }); }); }); }
[ "function", "create", "(", "model", ")", "{", "var", "params", "=", "arguments", ".", "length", "<=", "1", "||", "arguments", "[", "1", "]", "===", "undefined", "?", "{", "}", ":", "arguments", "[", "1", "]", ";", "if", "(", "!", "model", ")", "{", "throw", "new", "Error", "(", "'No model provided.'", ")", ";", "}", "return", "_destructure2", "[", "'default'", "]", "(", "model", ".", "forge", "(", ")", ",", "params", ")", ".", "then", "(", "function", "(", "destructured", ")", "{", "var", "attributes", "=", "destructured", ".", "attributes", ";", "var", "relations", "=", "destructured", ".", "relations", ";", "return", "_transact2", "[", "'default'", "]", "(", "model", ",", "function", "(", "transaction", ")", "{", "return", "model", ".", "forge", "(", "attributes", ")", ".", "save", "(", "null", ",", "{", "method", ":", "'insert'", ",", "transacting", ":", "transaction", "}", ")", ".", "tap", "(", "function", "(", "newModel", ")", "{", "return", "_relate2", "[", "'default'", "]", "(", "newModel", ",", "relations", ",", "'create'", ",", "transaction", ")", ";", "}", ")", ".", "then", "(", "function", "(", "newModel", ")", "{", "return", "model", ".", "forge", "(", "{", "id", ":", "newModel", ".", "id", "}", ")", ".", "fetch", "(", "{", "transacting", ":", "transaction", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Creates a model. @param {Bookshelf.Model} model - A bookshelf model instance @param {Object} params - An object containing the params from the request. @returns {Promise.Bookshelf.Model} The created model.
[ "Creates", "a", "model", "." ]
1ef8dd72a2e25cd44e534cedaba89f11ad70e19e
https://github.com/endpoints/endpoints/blob/1ef8dd72a2e25cd44e534cedaba89f11ad70e19e/es5/store-bookshelf/lib/create.js#L28-L49
train
Prasanna-sr/express-routes-versioning
index.js
getVersion
function getVersion(req) { var version; if (!req.version) { if (req.headers && req.headers['accept-version']) { version = req.headers['accept-version']; } } else { version = String(req.version); } return version; }
javascript
function getVersion(req) { var version; if (!req.version) { if (req.headers && req.headers['accept-version']) { version = req.headers['accept-version']; } } else { version = String(req.version); } return version; }
[ "function", "getVersion", "(", "req", ")", "{", "var", "version", ";", "if", "(", "!", "req", ".", "version", ")", "{", "if", "(", "req", ".", "headers", "&&", "req", ".", "headers", "[", "'accept-version'", "]", ")", "{", "version", "=", "req", ".", "headers", "[", "'accept-version'", "]", ";", "}", "}", "else", "{", "version", "=", "String", "(", "req", ".", "version", ")", ";", "}", "return", "version", ";", "}" ]
Gets the version of the application either from accept-version headers or req.version property
[ "Gets", "the", "version", "of", "the", "application", "either", "from", "accept", "-", "version", "headers", "or", "req", ".", "version", "property" ]
0a02657786aff2d81bb050cbd37f7c6bf8bb3c60
https://github.com/Prasanna-sr/express-routes-versioning/blob/0a02657786aff2d81bb050cbd37f7c6bf8bb3c60/index.js#L106-L116
train
flogvit/phaser-swipe
swipe.js
Swipe
function Swipe(game, model) { var self = this; self.DIRECTION_UP = 1; self.DIRECTION_DOWN = 2; self.DIRECTION_LEFT = 4; self.DIRECTION_RIGHT = 8; self.DIRECTION_UP_RIGHT = 16; self.DIRECTION_UP_LEFT = 32; self.DIRECTION_DOWN_RIGHT = 64; self.DIRECTION_DOWN_LEFT = 128; self.game = game; self.model = model !== undefined ? model : null; self.dragLength = 100; self.diagonalDelta = 50; self.swiping = false; self.direction = null; self.tmpDirection = null; self.tmpCallback = null; self.diagonalDisabled = false; this.game.input.onDown.add(function () { self.swiping = true; }); this.game.input.onUp.add(function () { self.swiping = false; }) this.setupKeyboard(); }
javascript
function Swipe(game, model) { var self = this; self.DIRECTION_UP = 1; self.DIRECTION_DOWN = 2; self.DIRECTION_LEFT = 4; self.DIRECTION_RIGHT = 8; self.DIRECTION_UP_RIGHT = 16; self.DIRECTION_UP_LEFT = 32; self.DIRECTION_DOWN_RIGHT = 64; self.DIRECTION_DOWN_LEFT = 128; self.game = game; self.model = model !== undefined ? model : null; self.dragLength = 100; self.diagonalDelta = 50; self.swiping = false; self.direction = null; self.tmpDirection = null; self.tmpCallback = null; self.diagonalDisabled = false; this.game.input.onDown.add(function () { self.swiping = true; }); this.game.input.onUp.add(function () { self.swiping = false; }) this.setupKeyboard(); }
[ "function", "Swipe", "(", "game", ",", "model", ")", "{", "var", "self", "=", "this", ";", "self", ".", "DIRECTION_UP", "=", "1", ";", "self", ".", "DIRECTION_DOWN", "=", "2", ";", "self", ".", "DIRECTION_LEFT", "=", "4", ";", "self", ".", "DIRECTION_RIGHT", "=", "8", ";", "self", ".", "DIRECTION_UP_RIGHT", "=", "16", ";", "self", ".", "DIRECTION_UP_LEFT", "=", "32", ";", "self", ".", "DIRECTION_DOWN_RIGHT", "=", "64", ";", "self", ".", "DIRECTION_DOWN_LEFT", "=", "128", ";", "self", ".", "game", "=", "game", ";", "self", ".", "model", "=", "model", "!==", "undefined", "?", "model", ":", "null", ";", "self", ".", "dragLength", "=", "100", ";", "self", ".", "diagonalDelta", "=", "50", ";", "self", ".", "swiping", "=", "false", ";", "self", ".", "direction", "=", "null", ";", "self", ".", "tmpDirection", "=", "null", ";", "self", ".", "tmpCallback", "=", "null", ";", "self", ".", "diagonalDisabled", "=", "false", ";", "this", ".", "game", ".", "input", ".", "onDown", ".", "add", "(", "function", "(", ")", "{", "self", ".", "swiping", "=", "true", ";", "}", ")", ";", "this", ".", "game", ".", "input", ".", "onUp", ".", "add", "(", "function", "(", ")", "{", "self", ".", "swiping", "=", "false", ";", "}", ")", "this", ".", "setupKeyboard", "(", ")", ";", "}" ]
Created by flogvit on 2015-11-03. @copyright Cellar Labs AS, 2015, www.cellarlabs.com, all rights reserved @file @license MIT @author Vegard Hanssen <[email protected]>
[ "Created", "by", "flogvit", "on", "2015", "-", "11", "-", "03", "." ]
1236f983bca824bbda715e2c5bb1021fa47ba9eb
https://github.com/flogvit/phaser-swipe/blob/1236f983bca824bbda715e2c5bb1021fa47ba9eb/swipe.js#L12-L42
train
endpoints/endpoints
es5/store-bookshelf/lib/create_relation.js
createRelation
function createRelation(model, relationName, data) { if (!model) { throw new Error('No model provided.'); } return _transact2['default'](model, function (transaction) { var existing = _related2['default'](model, relationName).map(function (rel) { return { id: _id2['default'](rel), type: _type2['default'](rel) }; }); var all = data.concat(existing); // TODO: should i be doing a deep comparison instead? var unique = _lodash2['default'].uniq(all, JSON.stringify.bind(null)); return _relate2['default'](model, { name: relationName, data: unique }, 'add', transaction); }); }
javascript
function createRelation(model, relationName, data) { if (!model) { throw new Error('No model provided.'); } return _transact2['default'](model, function (transaction) { var existing = _related2['default'](model, relationName).map(function (rel) { return { id: _id2['default'](rel), type: _type2['default'](rel) }; }); var all = data.concat(existing); // TODO: should i be doing a deep comparison instead? var unique = _lodash2['default'].uniq(all, JSON.stringify.bind(null)); return _relate2['default'](model, { name: relationName, data: unique }, 'add', transaction); }); }
[ "function", "createRelation", "(", "model", ",", "relationName", ",", "data", ")", "{", "if", "(", "!", "model", ")", "{", "throw", "new", "Error", "(", "'No model provided.'", ")", ";", "}", "return", "_transact2", "[", "'default'", "]", "(", "model", ",", "function", "(", "transaction", ")", "{", "var", "existing", "=", "_related2", "[", "'default'", "]", "(", "model", ",", "relationName", ")", ".", "map", "(", "function", "(", "rel", ")", "{", "return", "{", "id", ":", "_id2", "[", "'default'", "]", "(", "rel", ")", ",", "type", ":", "_type2", "[", "'default'", "]", "(", "rel", ")", "}", ";", "}", ")", ";", "var", "all", "=", "data", ".", "concat", "(", "existing", ")", ";", "var", "unique", "=", "_lodash2", "[", "'default'", "]", ".", "uniq", "(", "all", ",", "JSON", ".", "stringify", ".", "bind", "(", "null", ")", ")", ";", "return", "_relate2", "[", "'default'", "]", "(", "model", ",", "{", "name", ":", "relationName", ",", "data", ":", "unique", "}", ",", "'add'", ",", "transaction", ")", ";", "}", ")", ";", "}" ]
Creates a new relations on a model. @param {Bookshelf.Model} model - A bookshelf model instance @param {String} relationName - An object containing the relations. @param {Array} data - linkage data @returns {Promise.Bookshelf.Model} The updated model.
[ "Creates", "a", "new", "relations", "on", "a", "model", "." ]
1ef8dd72a2e25cd44e534cedaba89f11ad70e19e
https://github.com/endpoints/endpoints/blob/1ef8dd72a2e25cd44e534cedaba89f11ad70e19e/es5/store-bookshelf/lib/create_relation.js#L41-L60
train
endpoints/endpoints
es5/store-bookshelf/lib/update.js
update
function update(model) { var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; if (!model) { throw new Error('No model provided.'); } var currentState = model.toJSON({ shallow: true }); currentState.id = String(currentState.id); return _destructure2['default'](model, params).then(function (destructured) { var attributes = destructured.attributes; var relations = destructured.relations; return _transact2['default'](model, function (transaction) { return model.save(attributes, { patch: true, method: 'update', transacting: transaction }).tap(function (model) { return _relate2['default'](model, relations, 'update', transaction); }).then(function (model) { // if model didn't change, return null // model.previousAttributes() is broken. // https://github.com/tgriesser/bookshelf/issues/326 var updatedState = model.toJSON({ shallow: true }); updatedState.id = String(updatedState.id); return _lodash2['default'].isEqual(currentState, updatedState) ? null : model; }); }); }); }
javascript
function update(model) { var params = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1]; if (!model) { throw new Error('No model provided.'); } var currentState = model.toJSON({ shallow: true }); currentState.id = String(currentState.id); return _destructure2['default'](model, params).then(function (destructured) { var attributes = destructured.attributes; var relations = destructured.relations; return _transact2['default'](model, function (transaction) { return model.save(attributes, { patch: true, method: 'update', transacting: transaction }).tap(function (model) { return _relate2['default'](model, relations, 'update', transaction); }).then(function (model) { // if model didn't change, return null // model.previousAttributes() is broken. // https://github.com/tgriesser/bookshelf/issues/326 var updatedState = model.toJSON({ shallow: true }); updatedState.id = String(updatedState.id); return _lodash2['default'].isEqual(currentState, updatedState) ? null : model; }); }); }); }
[ "function", "update", "(", "model", ")", "{", "var", "params", "=", "arguments", ".", "length", "<=", "1", "||", "arguments", "[", "1", "]", "===", "undefined", "?", "{", "}", ":", "arguments", "[", "1", "]", ";", "if", "(", "!", "model", ")", "{", "throw", "new", "Error", "(", "'No model provided.'", ")", ";", "}", "var", "currentState", "=", "model", ".", "toJSON", "(", "{", "shallow", ":", "true", "}", ")", ";", "currentState", ".", "id", "=", "String", "(", "currentState", ".", "id", ")", ";", "return", "_destructure2", "[", "'default'", "]", "(", "model", ",", "params", ")", ".", "then", "(", "function", "(", "destructured", ")", "{", "var", "attributes", "=", "destructured", ".", "attributes", ";", "var", "relations", "=", "destructured", ".", "relations", ";", "return", "_transact2", "[", "'default'", "]", "(", "model", ",", "function", "(", "transaction", ")", "{", "return", "model", ".", "save", "(", "attributes", ",", "{", "patch", ":", "true", ",", "method", ":", "'update'", ",", "transacting", ":", "transaction", "}", ")", ".", "tap", "(", "function", "(", "model", ")", "{", "return", "_relate2", "[", "'default'", "]", "(", "model", ",", "relations", ",", "'update'", ",", "transaction", ")", ";", "}", ")", ".", "then", "(", "function", "(", "model", ")", "{", "var", "updatedState", "=", "model", ".", "toJSON", "(", "{", "shallow", ":", "true", "}", ")", ";", "updatedState", ".", "id", "=", "String", "(", "updatedState", ".", "id", ")", ";", "return", "_lodash2", "[", "'default'", "]", ".", "isEqual", "(", "currentState", ",", "updatedState", ")", "?", "null", ":", "model", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Updates a model. @param {Bookshelf.Model} model - A bookshelf model instance @param {Object} params - An object containing the params from the request. @returns {Promise.Bookshelf.Model|null} - The updated model or null if nothing has changed.
[ "Updates", "a", "model", "." ]
1ef8dd72a2e25cd44e534cedaba89f11ad70e19e
https://github.com/endpoints/endpoints/blob/1ef8dd72a2e25cd44e534cedaba89f11ad70e19e/es5/store-bookshelf/lib/update.js#L33-L63
train
stormpath/stormpath-sdk-node
lib/resource/mixins/SaveableMixin.js
saveResource
function saveResource(callback) { var self = this; self._applyCustomDataUpdatesIfNecessary(function () { self.dataStore.saveResource(self, callback); }); }
javascript
function saveResource(callback) { var self = this; self._applyCustomDataUpdatesIfNecessary(function () { self.dataStore.saveResource(self, callback); }); }
[ "function", "saveResource", "(", "callback", ")", "{", "var", "self", "=", "this", ";", "self", ".", "_applyCustomDataUpdatesIfNecessary", "(", "function", "(", ")", "{", "self", ".", "dataStore", ".", "saveResource", "(", "self", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Save changes to this resource. @param {Function} callback The function to call when the save operation is complete. Will be called with the parameters (err, updatedResource).
[ "Save", "changes", "to", "this", "resource", "." ]
da1d653d02a276296a0fc2616689c852d2c0db90
https://github.com/stormpath/stormpath-sdk-node/blob/da1d653d02a276296a0fc2616689c852d2c0db90/lib/resource/mixins/SaveableMixin.js#L24-L29
train
DenisCarriere/geocoder-geojson
providers/bing.js
toGeoJSON
function toGeoJSON(json, options = Options) { const collection = helpers.featureCollection([]) json.resourceSets[0].resources.map(result => { // Point GeoJSON const point = parsePoint(result) const bbox = parseBBox(result) let confidence = confidenceScore(bbox) const properties = { confidence, authenticationResultCode: json.authenticationResultCode, brandLogoUri: json.brandLogoUri, copyright: json.copyright, entityType: result.entityType, matchCodes: result.matchCodes, name: result.name, statusCode: json.statusCode, statusDescription: json.statusDescription, traceId: json.traceId, } Object.keys(result.address).forEach(key => properties[key] = result.address[key]) // Store Point to GeoJSON feature collection if (point) { point.bbox = bbox point.properties = properties collection.features.push(point) } }) return collection }
javascript
function toGeoJSON(json, options = Options) { const collection = helpers.featureCollection([]) json.resourceSets[0].resources.map(result => { // Point GeoJSON const point = parsePoint(result) const bbox = parseBBox(result) let confidence = confidenceScore(bbox) const properties = { confidence, authenticationResultCode: json.authenticationResultCode, brandLogoUri: json.brandLogoUri, copyright: json.copyright, entityType: result.entityType, matchCodes: result.matchCodes, name: result.name, statusCode: json.statusCode, statusDescription: json.statusDescription, traceId: json.traceId, } Object.keys(result.address).forEach(key => properties[key] = result.address[key]) // Store Point to GeoJSON feature collection if (point) { point.bbox = bbox point.properties = properties collection.features.push(point) } }) return collection }
[ "function", "toGeoJSON", "(", "json", ",", "options", "=", "Options", ")", "{", "const", "collection", "=", "helpers", ".", "featureCollection", "(", "[", "]", ")", "json", ".", "resourceSets", "[", "0", "]", ".", "resources", ".", "map", "(", "result", "=>", "{", "const", "point", "=", "parsePoint", "(", "result", ")", "const", "bbox", "=", "parseBBox", "(", "result", ")", "let", "confidence", "=", "confidenceScore", "(", "bbox", ")", "const", "properties", "=", "{", "confidence", ",", "authenticationResultCode", ":", "json", ".", "authenticationResultCode", ",", "brandLogoUri", ":", "json", ".", "brandLogoUri", ",", "copyright", ":", "json", ".", "copyright", ",", "entityType", ":", "result", ".", "entityType", ",", "matchCodes", ":", "result", ".", "matchCodes", ",", "name", ":", "result", ".", "name", ",", "statusCode", ":", "json", ".", "statusCode", ",", "statusDescription", ":", "json", ".", "statusDescription", ",", "traceId", ":", "json", ".", "traceId", ",", "}", "Object", ".", "keys", "(", "result", ".", "address", ")", ".", "forEach", "(", "key", "=>", "properties", "[", "key", "]", "=", "result", ".", "address", "[", "key", "]", ")", "if", "(", "point", ")", "{", "point", ".", "bbox", "=", "bbox", "point", ".", "properties", "=", "properties", "collection", ".", "features", ".", "push", "(", "point", ")", "}", "}", ")", "return", "collection", "}" ]
Convert Bing results into GeoJSON
[ "Convert", "Bing", "results", "into", "GeoJSON" ]
801b34ed715e6e78f073f04dc975500dbfdd1542
https://github.com/DenisCarriere/geocoder-geojson/blob/801b34ed715e6e78f073f04dc975500dbfdd1542/providers/bing.js#L21-L50
train
DenisCarriere/geocoder-geojson
utils/utils.js
error
function error (message) { console.log(chalk.bgRed.white('[Error]' + message)) throw new Error(message) }
javascript
function error (message) { console.log(chalk.bgRed.white('[Error]' + message)) throw new Error(message) }
[ "function", "error", "(", "message", ")", "{", "console", ".", "log", "(", "chalk", ".", "bgRed", ".", "white", "(", "'[Error]'", "+", "message", ")", ")", "throw", "new", "Error", "(", "message", ")", "}" ]
Pretty Error message
[ "Pretty", "Error", "message" ]
801b34ed715e6e78f073f04dc975500dbfdd1542
https://github.com/DenisCarriere/geocoder-geojson/blob/801b34ed715e6e78f073f04dc975500dbfdd1542/utils/utils.js#L9-L12
train
DenisCarriere/geocoder-geojson
providers/google.js
parseAddressComponents
function parseAddressComponents(components, short = Options.short) { const results = {} components.map(component => { if (short) { results[component.types[0]] = component.short_name } else { results[component.types[0]] = component.long_name } }) return results }
javascript
function parseAddressComponents(components, short = Options.short) { const results = {} components.map(component => { if (short) { results[component.types[0]] = component.short_name } else { results[component.types[0]] = component.long_name } }) return results }
[ "function", "parseAddressComponents", "(", "components", ",", "short", "=", "Options", ".", "short", ")", "{", "const", "results", "=", "{", "}", "components", ".", "map", "(", "component", "=>", "{", "if", "(", "short", ")", "{", "results", "[", "component", ".", "types", "[", "0", "]", "]", "=", "component", ".", "short_name", "}", "else", "{", "results", "[", "component", ".", "types", "[", "0", "]", "]", "=", "component", ".", "long_name", "}", "}", ")", "return", "results", "}" ]
Parses Address Component into a single layer Object
[ "Parses", "Address", "Component", "into", "a", "single", "layer", "Object" ]
801b34ed715e6e78f073f04dc975500dbfdd1542
https://github.com/DenisCarriere/geocoder-geojson/blob/801b34ed715e6e78f073f04dc975500dbfdd1542/providers/google.js#L13-L20
train
DenisCarriere/geocoder-geojson
providers/google.js
parseBBox
function parseBBox(result) { if (result.geometry) { if (result.geometry.viewport) { const viewport = result.geometry.viewport return [viewport.southwest.lng, viewport.southwest.lat, viewport.northeast.lng, viewport.northeast.lat] } } }
javascript
function parseBBox(result) { if (result.geometry) { if (result.geometry.viewport) { const viewport = result.geometry.viewport return [viewport.southwest.lng, viewport.southwest.lat, viewport.northeast.lng, viewport.northeast.lat] } } }
[ "function", "parseBBox", "(", "result", ")", "{", "if", "(", "result", ".", "geometry", ")", "{", "if", "(", "result", ".", "geometry", ".", "viewport", ")", "{", "const", "viewport", "=", "result", ".", "geometry", ".", "viewport", "return", "[", "viewport", ".", "southwest", ".", "lng", ",", "viewport", ".", "southwest", ".", "lat", ",", "viewport", ".", "northeast", ".", "lng", ",", "viewport", ".", "northeast", ".", "lat", "]", "}", "}", "}" ]
Converts GoogleResult Bounds to BBox
[ "Converts", "GoogleResult", "Bounds", "to", "BBox" ]
801b34ed715e6e78f073f04dc975500dbfdd1542
https://github.com/DenisCarriere/geocoder-geojson/blob/801b34ed715e6e78f073f04dc975500dbfdd1542/providers/google.js#L25-L32
train
DenisCarriere/geocoder-geojson
providers/google.js
parsePoint
function parsePoint(result) { if (result.geometry) { if (result.geometry.location) { const {lng, lat} = result.geometry.location return helpers.point([lng, lat]) } } }
javascript
function parsePoint(result) { if (result.geometry) { if (result.geometry.location) { const {lng, lat} = result.geometry.location return helpers.point([lng, lat]) } } }
[ "function", "parsePoint", "(", "result", ")", "{", "if", "(", "result", ".", "geometry", ")", "{", "if", "(", "result", ".", "geometry", ".", "location", ")", "{", "const", "{", "lng", ",", "lat", "}", "=", "result", ".", "geometry", ".", "location", "return", "helpers", ".", "point", "(", "[", "lng", ",", "lat", "]", ")", "}", "}", "}" ]
Converts GoogleResult to GeoJSON Point
[ "Converts", "GoogleResult", "to", "GeoJSON", "Point" ]
801b34ed715e6e78f073f04dc975500dbfdd1542
https://github.com/DenisCarriere/geocoder-geojson/blob/801b34ed715e6e78f073f04dc975500dbfdd1542/providers/google.js#L37-L44
train
DenisCarriere/geocoder-geojson
providers/google.js
toGeoJSON
function toGeoJSON(json, options = Options) { const short = options.short || Options.short const collection = helpers.featureCollection([]) json.results.map(result => { // Get Geometries const point = parsePoint(result) const bbox = parseBBox(result) // Calculate Confidence score const location_type = result.geometry.location_type let confidence = confidenceScore(bbox) if (location_type === 'ROOFTOP') { confidence = 10 } // GeoJSON Point properties const properties = { confidence, location_type, formatted_address: result.formatted_address, place_id: result.place_id, types: result.types, } // Google Specific Properties const components = parseAddressComponents(result.address_components, short) Object.keys(components).forEach(key => properties[key] = components[key]) // Store Point to GeoJSON feature collection if (point) { point.bbox = bbox point.properties = properties collection.features.push(point) } }) return collection }
javascript
function toGeoJSON(json, options = Options) { const short = options.short || Options.short const collection = helpers.featureCollection([]) json.results.map(result => { // Get Geometries const point = parsePoint(result) const bbox = parseBBox(result) // Calculate Confidence score const location_type = result.geometry.location_type let confidence = confidenceScore(bbox) if (location_type === 'ROOFTOP') { confidence = 10 } // GeoJSON Point properties const properties = { confidence, location_type, formatted_address: result.formatted_address, place_id: result.place_id, types: result.types, } // Google Specific Properties const components = parseAddressComponents(result.address_components, short) Object.keys(components).forEach(key => properties[key] = components[key]) // Store Point to GeoJSON feature collection if (point) { point.bbox = bbox point.properties = properties collection.features.push(point) } }) return collection }
[ "function", "toGeoJSON", "(", "json", ",", "options", "=", "Options", ")", "{", "const", "short", "=", "options", ".", "short", "||", "Options", ".", "short", "const", "collection", "=", "helpers", ".", "featureCollection", "(", "[", "]", ")", "json", ".", "results", ".", "map", "(", "result", "=>", "{", "const", "point", "=", "parsePoint", "(", "result", ")", "const", "bbox", "=", "parseBBox", "(", "result", ")", "const", "location_type", "=", "result", ".", "geometry", ".", "location_type", "let", "confidence", "=", "confidenceScore", "(", "bbox", ")", "if", "(", "location_type", "===", "'ROOFTOP'", ")", "{", "confidence", "=", "10", "}", "const", "properties", "=", "{", "confidence", ",", "location_type", ",", "formatted_address", ":", "result", ".", "formatted_address", ",", "place_id", ":", "result", ".", "place_id", ",", "types", ":", "result", ".", "types", ",", "}", "const", "components", "=", "parseAddressComponents", "(", "result", ".", "address_components", ",", "short", ")", "Object", ".", "keys", "(", "components", ")", ".", "forEach", "(", "key", "=>", "properties", "[", "key", "]", "=", "components", "[", "key", "]", ")", "if", "(", "point", ")", "{", "point", ".", "bbox", "=", "bbox", "point", ".", "properties", "=", "properties", "collection", ".", "features", ".", "push", "(", "point", ")", "}", "}", ")", "return", "collection", "}" ]
Convert Google results into GeoJSON
[ "Convert", "Google", "results", "into", "GeoJSON" ]
801b34ed715e6e78f073f04dc975500dbfdd1542
https://github.com/DenisCarriere/geocoder-geojson/blob/801b34ed715e6e78f073f04dc975500dbfdd1542/providers/google.js#L49-L83
train
DenisCarriere/geocoder-geojson
providers/mapbox.js
toGeoJSON
function toGeoJSON(json, options = Options) { const collection = featureCollection([]) collection.features = json.features.map(result => { return result }) return collection }
javascript
function toGeoJSON(json, options = Options) { const collection = featureCollection([]) collection.features = json.features.map(result => { return result }) return collection }
[ "function", "toGeoJSON", "(", "json", ",", "options", "=", "Options", ")", "{", "const", "collection", "=", "featureCollection", "(", "[", "]", ")", "collection", ".", "features", "=", "json", ".", "features", ".", "map", "(", "result", "=>", "{", "return", "result", "}", ")", "return", "collection", "}" ]
Convert Mapbox results into GeoJSON
[ "Convert", "Mapbox", "results", "into", "GeoJSON" ]
801b34ed715e6e78f073f04dc975500dbfdd1542
https://github.com/DenisCarriere/geocoder-geojson/blob/801b34ed715e6e78f073f04dc975500dbfdd1542/providers/mapbox.js#L13-L19
train
DenisCarriere/geocoder-geojson
index.js
request
function request(url, geojsonParser, params = {}, options = utils.Options) { // Create custom Axios instance const instance = axios.create({}) // Remove any existing default Authorization headers if (instance.defaults.headers.common && instance.defaults.headers.common.Authorization) { delete instance.defaults.headers.common.Authorization } if (instance.defaults.headers.Authorization) { delete instance.defaults.headers.Authorization } // Handle request return new Promise((resolve, reject) => { instance.get(url, {params}).then(response => { if (options.raw !== undefined) { return resolve(response.data) } const geojson = geojsonParser(response.data, options) return resolve(geojson) }) }) }
javascript
function request(url, geojsonParser, params = {}, options = utils.Options) { // Create custom Axios instance const instance = axios.create({}) // Remove any existing default Authorization headers if (instance.defaults.headers.common && instance.defaults.headers.common.Authorization) { delete instance.defaults.headers.common.Authorization } if (instance.defaults.headers.Authorization) { delete instance.defaults.headers.Authorization } // Handle request return new Promise((resolve, reject) => { instance.get(url, {params}).then(response => { if (options.raw !== undefined) { return resolve(response.data) } const geojson = geojsonParser(response.data, options) return resolve(geojson) }) }) }
[ "function", "request", "(", "url", ",", "geojsonParser", ",", "params", "=", "{", "}", ",", "options", "=", "utils", ".", "Options", ")", "{", "const", "instance", "=", "axios", ".", "create", "(", "{", "}", ")", "if", "(", "instance", ".", "defaults", ".", "headers", ".", "common", "&&", "instance", ".", "defaults", ".", "headers", ".", "common", ".", "Authorization", ")", "{", "delete", "instance", ".", "defaults", ".", "headers", ".", "common", ".", "Authorization", "}", "if", "(", "instance", ".", "defaults", ".", "headers", ".", "Authorization", ")", "{", "delete", "instance", ".", "defaults", ".", "headers", ".", "Authorization", "}", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "instance", ".", "get", "(", "url", ",", "{", "params", "}", ")", ".", "then", "(", "response", "=>", "{", "if", "(", "options", ".", "raw", "!==", "undefined", ")", "{", "return", "resolve", "(", "response", ".", "data", ")", "}", "const", "geojson", "=", "geojsonParser", "(", "response", ".", "data", ",", "options", ")", "return", "resolve", "(", "geojson", ")", "}", ")", "}", ")", "}" ]
Generic GET function to normalize all of the requests @param {string} url URL @param {function} geojsonParser Customized function to generate a GeoJSON Point FeatureCollection @param {Object} params Query String @param {Object} options Options used for HTTP request & GeoJSON Parser function @returns {Promise<Points>} Results in GeoJSON FeatureCollection Points
[ "Generic", "GET", "function", "to", "normalize", "all", "of", "the", "requests" ]
801b34ed715e6e78f073f04dc975500dbfdd1542
https://github.com/DenisCarriere/geocoder-geojson/blob/801b34ed715e6e78f073f04dc975500dbfdd1542/index.js#L251-L267
train
dxinteractive/jsdoc-react-proptypes
src/plugin.js
getInThere
function getInThere(thing, path) { var out = thing; var apathy = path.split('.'); for(var i =0 ; i < apathy.length; i ++ ) { if(!out) { return null; } out = out[apathy[i]]; } return out; }
javascript
function getInThere(thing, path) { var out = thing; var apathy = path.split('.'); for(var i =0 ; i < apathy.length; i ++ ) { if(!out) { return null; } out = out[apathy[i]]; } return out; }
[ "function", "getInThere", "(", "thing", ",", "path", ")", "{", "var", "out", "=", "thing", ";", "var", "apathy", "=", "path", ".", "split", "(", "'.'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "apathy", ".", "length", ";", "i", "++", ")", "{", "if", "(", "!", "out", ")", "{", "return", "null", ";", "}", "out", "=", "out", "[", "apathy", "[", "i", "]", "]", ";", "}", "return", "out", ";", "}" ]
climb inside of the various animals in the safe way
[ "climb", "inside", "of", "the", "various", "animals", "in", "the", "safe", "way" ]
88b01b91f659d88e53585f154d06e4b5287b0a70
https://github.com/dxinteractive/jsdoc-react-proptypes/blob/88b01b91f659d88e53585f154d06e4b5287b0a70/src/plugin.js#L17-L28
train
DenisCarriere/geocoder-geojson
providers/wikidata.js
toGeoJSON
function toGeoJSON(json, options = Options) { const languages = options.languages || Options.languages const collection = helpers.featureCollection([]) if (json.results !== undefined) { if (json.results.bindings !== undefined) { json.results.bindings.map(result => { // Standard Wikidata tags const id = result.place.value.match(/entity\/(.+)/)[1] const [lng, lat] = result.location.value.match(/\(([\-\.\d]+) ([\-\.\d]+)\)/).slice(1, 3).map(n => Number(n)) const distance = Number(result.distance.value) const properties = { id, distance, } if (result.placeDescription) { properties.description = result.placeDescription.value } // Parse languages languages.map(language => { const match = result[`name_${ language }`] if (match !== undefined) { properties[`name:${ language }`] = match.value } }) // Create Point const point = helpers.point([lng, lat], properties) point.id = id // Add to GeoJSON Feature Collection collection.features.push(point) }) } } return collection }
javascript
function toGeoJSON(json, options = Options) { const languages = options.languages || Options.languages const collection = helpers.featureCollection([]) if (json.results !== undefined) { if (json.results.bindings !== undefined) { json.results.bindings.map(result => { // Standard Wikidata tags const id = result.place.value.match(/entity\/(.+)/)[1] const [lng, lat] = result.location.value.match(/\(([\-\.\d]+) ([\-\.\d]+)\)/).slice(1, 3).map(n => Number(n)) const distance = Number(result.distance.value) const properties = { id, distance, } if (result.placeDescription) { properties.description = result.placeDescription.value } // Parse languages languages.map(language => { const match = result[`name_${ language }`] if (match !== undefined) { properties[`name:${ language }`] = match.value } }) // Create Point const point = helpers.point([lng, lat], properties) point.id = id // Add to GeoJSON Feature Collection collection.features.push(point) }) } } return collection }
[ "function", "toGeoJSON", "(", "json", ",", "options", "=", "Options", ")", "{", "const", "languages", "=", "options", ".", "languages", "||", "Options", ".", "languages", "const", "collection", "=", "helpers", ".", "featureCollection", "(", "[", "]", ")", "if", "(", "json", ".", "results", "!==", "undefined", ")", "{", "if", "(", "json", ".", "results", ".", "bindings", "!==", "undefined", ")", "{", "json", ".", "results", ".", "bindings", ".", "map", "(", "result", "=>", "{", "const", "id", "=", "result", ".", "place", ".", "value", ".", "match", "(", "/", "entity\\/(.+)", "/", ")", "[", "1", "]", "const", "[", "lng", ",", "lat", "]", "=", "result", ".", "location", ".", "value", ".", "match", "(", "/", "\\(([\\-\\.\\d]+) ([\\-\\.\\d]+)\\)", "/", ")", ".", "slice", "(", "1", ",", "3", ")", ".", "map", "(", "n", "=>", "Number", "(", "n", ")", ")", "const", "distance", "=", "Number", "(", "result", ".", "distance", ".", "value", ")", "const", "properties", "=", "{", "id", ",", "distance", ",", "}", "if", "(", "result", ".", "placeDescription", ")", "{", "properties", ".", "description", "=", "result", ".", "placeDescription", ".", "value", "}", "languages", ".", "map", "(", "language", "=>", "{", "const", "match", "=", "result", "[", "`", "${", "language", "}", "`", "]", "if", "(", "match", "!==", "undefined", ")", "{", "properties", "[", "`", "${", "language", "}", "`", "]", "=", "match", ".", "value", "}", "}", ")", "const", "point", "=", "helpers", ".", "point", "(", "[", "lng", ",", "lat", "]", ",", "properties", ")", "point", ".", "id", "=", "id", "collection", ".", "features", ".", "push", "(", "point", ")", "}", ")", "}", "}", "return", "collection", "}" ]
Convert Wikidata SPARQL results into GeoJSON
[ "Convert", "Wikidata", "SPARQL", "results", "into", "GeoJSON" ]
801b34ed715e6e78f073f04dc975500dbfdd1542
https://github.com/DenisCarriere/geocoder-geojson/blob/801b34ed715e6e78f073f04dc975500dbfdd1542/providers/wikidata.js#L89-L125
train
henrychavez/materialize-tags
dist/js/materialize-tags.js
function () { var self = this; // Unbind events self.$container.off('keydown', 'input'); self.$container.off('click', '[role=remove]'); self.$container.remove(); self.$element.removeData('materialtags'); self.$element.show(); }
javascript
function () { var self = this; // Unbind events self.$container.off('keydown', 'input'); self.$container.off('click', '[role=remove]'); self.$container.remove(); self.$element.removeData('materialtags'); self.$element.show(); }
[ "function", "(", ")", "{", "var", "self", "=", "this", ";", "self", ".", "$container", ".", "off", "(", "'keydown'", ",", "'input'", ")", ";", "self", ".", "$container", ".", "off", "(", "'click'", ",", "'[role=remove]'", ")", ";", "self", ".", "$container", ".", "remove", "(", ")", ";", "self", ".", "$element", ".", "removeData", "(", "'materialtags'", ")", ";", "self", ".", "$element", ".", "show", "(", ")", ";", "}" ]
Removes all materialtags behaviour and unregsiter all event handlers
[ "Removes", "all", "materialtags", "behaviour", "and", "unregsiter", "all", "event", "handlers" ]
6ca0d3f128ddf0a491c9d5c01c955e5723103187
https://github.com/henrychavez/materialize-tags/blob/6ca0d3f128ddf0a491c9d5c01c955e5723103187/dist/js/materialize-tags.js#L602-L613
train
faressoft/onesignal
index.js
OneSignal
function OneSignal(apiKey, appId, sandbox) { // Default value for sandbox argument if (typeof sandbox === 'undefined') { sandbox = false; } /** * The api key of Signal One * @type {String} */ const API_KEY = apiKey; /** * The app id of Signal One * @type {String} */ const APP_ID = appId; /** * Use sandbox certificate * @type {String} */ const SANDBOX = apiKey; /** * Handle resolving or rejecting One Signal response * * @param {Object} error * @param {Object} response * @param {String} body * @param {Function} reject * @param {Function} resolve */ function responseHandle(error, response, body, reject, resolve) { if (error) { return reject(error); } try { body = JSON.parse(body); } catch (e) { return reject(new Error('Wrong JSON Format')); } resolve(body); } /** * Register a new device and its identifier to OneSignal and get OneSignal ID * * @param {String} identifier the device token * @param {String} osType ios, android * @return {Promise} resolve with OneSignal ID */ this.addDevice = function(identifier, osType) { var deviceType = osType == 'ios' ? 0 : 1; var options = { method: 'POST', url: 'https://onesignal.com/api/v1/players', headers: { authorization: 'Basic ' + API_KEY, 'cache-control': 'no-cache', 'content-type': 'application/json; charset=utf-8' }, body: JSON.stringify({ app_id: APP_ID, device_type: deviceType, identifier: identifier, language: 'en', test_type: SANDBOX ? 1 : null }) }; return new Promise(function(resolve, reject) { request(options, function(error, response, body) { responseHandle(error, response, body, reject, function(body) { resolve(body.id); }); }); }); }; /** * Update the identifier of an existing device * * @param {String} oneSignalId the one signal device id * @param {String} newIdentifier the new device token * @return {Promise} */ this.editDevice = function(oneSignalId, newIdentifier) { var options = { method: 'PUT', url: 'https://onesignal.com/api/v1/players/' + oneSignalId, headers: { authorization: 'Basic ' + API_KEY, 'cache-control': 'no-cache', 'content-type': 'application/json; charset=utf-8' }, body: JSON.stringify({ app_id: APP_ID, identifier: newIdentifier }) }; return new Promise(function(resolve, reject) { request(options, function(error, response, body) { responseHandle(error, response, body, reject, resolve); }); }); }; /** * Create and send a notification * * @param {String} message the notification message * @param {Object} data any custom data * @param {Array} oneSignalIds a list of OneSignal devices ids * @return {Promise} */ this.createNotification = function(message, data, oneSignalIds) { var options = { method: 'POST', url: 'https://onesignal.com/api/v1/notifications', headers: { authorization: 'Basic ' + API_KEY, 'cache-control': 'no-cache', 'content-type': 'application/json; charset=utf-8' }, body: JSON.stringify({ app_id: APP_ID, include_player_ids: oneSignalIds, contents: { en: message }, data: data }) }; return new Promise(function(resolve, reject) { request(options, function(error, response, body) { responseHandle(error, response, body, reject, resolve); }); }); }; }
javascript
function OneSignal(apiKey, appId, sandbox) { // Default value for sandbox argument if (typeof sandbox === 'undefined') { sandbox = false; } /** * The api key of Signal One * @type {String} */ const API_KEY = apiKey; /** * The app id of Signal One * @type {String} */ const APP_ID = appId; /** * Use sandbox certificate * @type {String} */ const SANDBOX = apiKey; /** * Handle resolving or rejecting One Signal response * * @param {Object} error * @param {Object} response * @param {String} body * @param {Function} reject * @param {Function} resolve */ function responseHandle(error, response, body, reject, resolve) { if (error) { return reject(error); } try { body = JSON.parse(body); } catch (e) { return reject(new Error('Wrong JSON Format')); } resolve(body); } /** * Register a new device and its identifier to OneSignal and get OneSignal ID * * @param {String} identifier the device token * @param {String} osType ios, android * @return {Promise} resolve with OneSignal ID */ this.addDevice = function(identifier, osType) { var deviceType = osType == 'ios' ? 0 : 1; var options = { method: 'POST', url: 'https://onesignal.com/api/v1/players', headers: { authorization: 'Basic ' + API_KEY, 'cache-control': 'no-cache', 'content-type': 'application/json; charset=utf-8' }, body: JSON.stringify({ app_id: APP_ID, device_type: deviceType, identifier: identifier, language: 'en', test_type: SANDBOX ? 1 : null }) }; return new Promise(function(resolve, reject) { request(options, function(error, response, body) { responseHandle(error, response, body, reject, function(body) { resolve(body.id); }); }); }); }; /** * Update the identifier of an existing device * * @param {String} oneSignalId the one signal device id * @param {String} newIdentifier the new device token * @return {Promise} */ this.editDevice = function(oneSignalId, newIdentifier) { var options = { method: 'PUT', url: 'https://onesignal.com/api/v1/players/' + oneSignalId, headers: { authorization: 'Basic ' + API_KEY, 'cache-control': 'no-cache', 'content-type': 'application/json; charset=utf-8' }, body: JSON.stringify({ app_id: APP_ID, identifier: newIdentifier }) }; return new Promise(function(resolve, reject) { request(options, function(error, response, body) { responseHandle(error, response, body, reject, resolve); }); }); }; /** * Create and send a notification * * @param {String} message the notification message * @param {Object} data any custom data * @param {Array} oneSignalIds a list of OneSignal devices ids * @return {Promise} */ this.createNotification = function(message, data, oneSignalIds) { var options = { method: 'POST', url: 'https://onesignal.com/api/v1/notifications', headers: { authorization: 'Basic ' + API_KEY, 'cache-control': 'no-cache', 'content-type': 'application/json; charset=utf-8' }, body: JSON.stringify({ app_id: APP_ID, include_player_ids: oneSignalIds, contents: { en: message }, data: data }) }; return new Promise(function(resolve, reject) { request(options, function(error, response, body) { responseHandle(error, response, body, reject, resolve); }); }); }; }
[ "function", "OneSignal", "(", "apiKey", ",", "appId", ",", "sandbox", ")", "{", "if", "(", "typeof", "sandbox", "===", "'undefined'", ")", "{", "sandbox", "=", "false", ";", "}", "const", "API_KEY", "=", "apiKey", ";", "const", "APP_ID", "=", "appId", ";", "const", "SANDBOX", "=", "apiKey", ";", "function", "responseHandle", "(", "error", ",", "response", ",", "body", ",", "reject", ",", "resolve", ")", "{", "if", "(", "error", ")", "{", "return", "reject", "(", "error", ")", ";", "}", "try", "{", "body", "=", "JSON", ".", "parse", "(", "body", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "reject", "(", "new", "Error", "(", "'Wrong JSON Format'", ")", ")", ";", "}", "resolve", "(", "body", ")", ";", "}", "this", ".", "addDevice", "=", "function", "(", "identifier", ",", "osType", ")", "{", "var", "deviceType", "=", "osType", "==", "'ios'", "?", "0", ":", "1", ";", "var", "options", "=", "{", "method", ":", "'POST'", ",", "url", ":", "'https://onesignal.com/api/v1/players'", ",", "headers", ":", "{", "authorization", ":", "'Basic '", "+", "API_KEY", ",", "'cache-control'", ":", "'no-cache'", ",", "'content-type'", ":", "'application/json; charset=utf-8'", "}", ",", "body", ":", "JSON", ".", "stringify", "(", "{", "app_id", ":", "APP_ID", ",", "device_type", ":", "deviceType", ",", "identifier", ":", "identifier", ",", "language", ":", "'en'", ",", "test_type", ":", "SANDBOX", "?", "1", ":", "null", "}", ")", "}", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "request", "(", "options", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "responseHandle", "(", "error", ",", "response", ",", "body", ",", "reject", ",", "function", "(", "body", ")", "{", "resolve", "(", "body", ".", "id", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "this", ".", "editDevice", "=", "function", "(", "oneSignalId", ",", "newIdentifier", ")", "{", "var", "options", "=", "{", "method", ":", "'PUT'", ",", "url", ":", "'https://onesignal.com/api/v1/players/'", "+", "oneSignalId", ",", "headers", ":", "{", "authorization", ":", "'Basic '", "+", "API_KEY", ",", "'cache-control'", ":", "'no-cache'", ",", "'content-type'", ":", "'application/json; charset=utf-8'", "}", ",", "body", ":", "JSON", ".", "stringify", "(", "{", "app_id", ":", "APP_ID", ",", "identifier", ":", "newIdentifier", "}", ")", "}", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "request", "(", "options", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "responseHandle", "(", "error", ",", "response", ",", "body", ",", "reject", ",", "resolve", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "this", ".", "createNotification", "=", "function", "(", "message", ",", "data", ",", "oneSignalIds", ")", "{", "var", "options", "=", "{", "method", ":", "'POST'", ",", "url", ":", "'https://onesignal.com/api/v1/notifications'", ",", "headers", ":", "{", "authorization", ":", "'Basic '", "+", "API_KEY", ",", "'cache-control'", ":", "'no-cache'", ",", "'content-type'", ":", "'application/json; charset=utf-8'", "}", ",", "body", ":", "JSON", ".", "stringify", "(", "{", "app_id", ":", "APP_ID", ",", "include_player_ids", ":", "oneSignalIds", ",", "contents", ":", "{", "en", ":", "message", "}", ",", "data", ":", "data", "}", ")", "}", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "request", "(", "options", ",", "function", "(", "error", ",", "response", ",", "body", ")", "{", "responseHandle", "(", "error", ",", "response", ",", "body", ",", "reject", ",", "resolve", ")", ";", "}", ")", ";", "}", ")", ";", "}", ";", "}" ]
One Signal Client @param {String} apiKey REST API Key @param {String} appId OneSignal App ID @param {Boolean} sandbox use the sandbox certificate for iOS (default: false)
[ "One", "Signal", "Client" ]
269b1abdeeae5fbf39e1eb5f144d30ad9fd0987f
https://github.com/faressoft/onesignal/blob/269b1abdeeae5fbf39e1eb5f144d30ad9fd0987f/index.js#L16-L185
train
faressoft/onesignal
index.js
responseHandle
function responseHandle(error, response, body, reject, resolve) { if (error) { return reject(error); } try { body = JSON.parse(body); } catch (e) { return reject(new Error('Wrong JSON Format')); } resolve(body); }
javascript
function responseHandle(error, response, body, reject, resolve) { if (error) { return reject(error); } try { body = JSON.parse(body); } catch (e) { return reject(new Error('Wrong JSON Format')); } resolve(body); }
[ "function", "responseHandle", "(", "error", ",", "response", ",", "body", ",", "reject", ",", "resolve", ")", "{", "if", "(", "error", ")", "{", "return", "reject", "(", "error", ")", ";", "}", "try", "{", "body", "=", "JSON", ".", "parse", "(", "body", ")", ";", "}", "catch", "(", "e", ")", "{", "return", "reject", "(", "new", "Error", "(", "'Wrong JSON Format'", ")", ")", ";", "}", "resolve", "(", "body", ")", ";", "}" ]
Handle resolving or rejecting One Signal response @param {Object} error @param {Object} response @param {String} body @param {Function} reject @param {Function} resolve
[ "Handle", "resolving", "or", "rejecting", "One", "Signal", "response" ]
269b1abdeeae5fbf39e1eb5f144d30ad9fd0987f
https://github.com/faressoft/onesignal/blob/269b1abdeeae5fbf39e1eb5f144d30ad9fd0987f/index.js#L50-L64
train
bbondy/abp-filter-parser
src/abp-filter-parser.js
findFirstSeparatorChar
function findFirstSeparatorChar(input, startPos) { for (let i = startPos; i < input.length; i++) { if (separatorCharacters.indexOf(input[i]) !== -1) { return i; } } return -1; }
javascript
function findFirstSeparatorChar(input, startPos) { for (let i = startPos; i < input.length; i++) { if (separatorCharacters.indexOf(input[i]) !== -1) { return i; } } return -1; }
[ "function", "findFirstSeparatorChar", "(", "input", ",", "startPos", ")", "{", "for", "(", "let", "i", "=", "startPos", ";", "i", "<", "input", ".", "length", ";", "i", "++", ")", "{", "if", "(", "separatorCharacters", ".", "indexOf", "(", "input", "[", "i", "]", ")", "!==", "-", "1", ")", "{", "return", "i", ";", "}", "}", "return", "-", "1", ";", "}" ]
Finds the first separator character in the input string
[ "Finds", "the", "first", "separator", "character", "in", "the", "input", "string" ]
653690db8a229cc8cd5cafad393dc1e0260dd1f8
https://github.com/bbondy/abp-filter-parser/blob/653690db8a229cc8cd5cafad393dc1e0260dd1f8/src/abp-filter-parser.js#L130-L137
train
bbondy/abp-filter-parser
src/abp-filter-parser.js
getDomainIndex
function getDomainIndex(input) { let index = input.indexOf(':'); ++index; while (input[index] === '/') { index++; } return index; }
javascript
function getDomainIndex(input) { let index = input.indexOf(':'); ++index; while (input[index] === '/') { index++; } return index; }
[ "function", "getDomainIndex", "(", "input", ")", "{", "let", "index", "=", "input", ".", "indexOf", "(", "':'", ")", ";", "++", "index", ";", "while", "(", "input", "[", "index", "]", "===", "'/'", ")", "{", "index", "++", ";", "}", "return", "index", ";", "}" ]
Obtains the domain index of the input filter line
[ "Obtains", "the", "domain", "index", "of", "the", "input", "filter", "line" ]
653690db8a229cc8cd5cafad393dc1e0260dd1f8
https://github.com/bbondy/abp-filter-parser/blob/653690db8a229cc8cd5cafad393dc1e0260dd1f8/src/abp-filter-parser.js#L300-L307
train
bbondy/abp-filter-parser
src/abp-filter-parser.js
matchOptions
function matchOptions(parsedFilterData, input, contextParams = {}) { if (contextParams.elementTypeMask !== undefined && parsedFilterData.options) { if (parsedFilterData.options.elementTypeMask !== undefined && !(parsedFilterData.options.elementTypeMask & contextParams.elementTypeMask)) { return false; } if (parsedFilterData.options.skipElementTypeMask !== undefined && parsedFilterData.options.skipElementTypeMask & contextParams.elementTypeMask) { return false; } } // Domain option check if (contextParams.domain !== undefined && parsedFilterData.options) { if (parsedFilterData.options.domains || parsedFilterData.options.skipDomains) { // Get the domains that should be considered let shouldBlockDomains = parsedFilterData.options.domains.filter((domain) => !isThirdPartyHost(domain, contextParams.domain)); let shouldSkipDomains = parsedFilterData.options.skipDomains.filter((domain) => !isThirdPartyHost(domain, contextParams.domain)); // Handle cases like: example.com|~foo.example.com should llow for foo.example.com // But ~example.com|foo.example.com should block for foo.example.com let leftOverBlocking = shouldBlockDomains.filter((shouldBlockDomain) => shouldSkipDomains.every((shouldSkipDomain) => isThirdPartyHost(shouldBlockDomain, shouldSkipDomain))); let leftOverSkipping = shouldSkipDomains.filter((shouldSkipDomain) => shouldBlockDomains.every((shouldBlockDomain) => isThirdPartyHost(shouldSkipDomain, shouldBlockDomain))); // If we have none left over, then we shouldn't consider this a match if (shouldBlockDomains.length === 0 && parsedFilterData.options.domains.length !== 0 || shouldBlockDomains.length > 0 && leftOverBlocking.length === 0 || shouldSkipDomains.length > 0 && leftOverSkipping.length > 0) { return false; } } } // If we're in the context of third-party site, then consider third-party option checks if (contextParams['third-party'] !== undefined) { // Is the current rule check for third party only? if (filterDataContainsOption(parsedFilterData, 'third-party')) { let inputHost = getUrlHost(input); let inputHostIsThirdParty = isThirdPartyHost(parsedFilterData.host, inputHost); if (inputHostIsThirdParty || !contextParams['third-party']) { return false; } } } return true; }
javascript
function matchOptions(parsedFilterData, input, contextParams = {}) { if (contextParams.elementTypeMask !== undefined && parsedFilterData.options) { if (parsedFilterData.options.elementTypeMask !== undefined && !(parsedFilterData.options.elementTypeMask & contextParams.elementTypeMask)) { return false; } if (parsedFilterData.options.skipElementTypeMask !== undefined && parsedFilterData.options.skipElementTypeMask & contextParams.elementTypeMask) { return false; } } // Domain option check if (contextParams.domain !== undefined && parsedFilterData.options) { if (parsedFilterData.options.domains || parsedFilterData.options.skipDomains) { // Get the domains that should be considered let shouldBlockDomains = parsedFilterData.options.domains.filter((domain) => !isThirdPartyHost(domain, contextParams.domain)); let shouldSkipDomains = parsedFilterData.options.skipDomains.filter((domain) => !isThirdPartyHost(domain, contextParams.domain)); // Handle cases like: example.com|~foo.example.com should llow for foo.example.com // But ~example.com|foo.example.com should block for foo.example.com let leftOverBlocking = shouldBlockDomains.filter((shouldBlockDomain) => shouldSkipDomains.every((shouldSkipDomain) => isThirdPartyHost(shouldBlockDomain, shouldSkipDomain))); let leftOverSkipping = shouldSkipDomains.filter((shouldSkipDomain) => shouldBlockDomains.every((shouldBlockDomain) => isThirdPartyHost(shouldSkipDomain, shouldBlockDomain))); // If we have none left over, then we shouldn't consider this a match if (shouldBlockDomains.length === 0 && parsedFilterData.options.domains.length !== 0 || shouldBlockDomains.length > 0 && leftOverBlocking.length === 0 || shouldSkipDomains.length > 0 && leftOverSkipping.length > 0) { return false; } } } // If we're in the context of third-party site, then consider third-party option checks if (contextParams['third-party'] !== undefined) { // Is the current rule check for third party only? if (filterDataContainsOption(parsedFilterData, 'third-party')) { let inputHost = getUrlHost(input); let inputHostIsThirdParty = isThirdPartyHost(parsedFilterData.host, inputHost); if (inputHostIsThirdParty || !contextParams['third-party']) { return false; } } } return true; }
[ "function", "matchOptions", "(", "parsedFilterData", ",", "input", ",", "contextParams", "=", "{", "}", ")", "{", "if", "(", "contextParams", ".", "elementTypeMask", "!==", "undefined", "&&", "parsedFilterData", ".", "options", ")", "{", "if", "(", "parsedFilterData", ".", "options", ".", "elementTypeMask", "!==", "undefined", "&&", "!", "(", "parsedFilterData", ".", "options", ".", "elementTypeMask", "&", "contextParams", ".", "elementTypeMask", ")", ")", "{", "return", "false", ";", "}", "if", "(", "parsedFilterData", ".", "options", ".", "skipElementTypeMask", "!==", "undefined", "&&", "parsedFilterData", ".", "options", ".", "skipElementTypeMask", "&", "contextParams", ".", "elementTypeMask", ")", "{", "return", "false", ";", "}", "}", "if", "(", "contextParams", ".", "domain", "!==", "undefined", "&&", "parsedFilterData", ".", "options", ")", "{", "if", "(", "parsedFilterData", ".", "options", ".", "domains", "||", "parsedFilterData", ".", "options", ".", "skipDomains", ")", "{", "let", "shouldBlockDomains", "=", "parsedFilterData", ".", "options", ".", "domains", ".", "filter", "(", "(", "domain", ")", "=>", "!", "isThirdPartyHost", "(", "domain", ",", "contextParams", ".", "domain", ")", ")", ";", "let", "shouldSkipDomains", "=", "parsedFilterData", ".", "options", ".", "skipDomains", ".", "filter", "(", "(", "domain", ")", "=>", "!", "isThirdPartyHost", "(", "domain", ",", "contextParams", ".", "domain", ")", ")", ";", "let", "leftOverBlocking", "=", "shouldBlockDomains", ".", "filter", "(", "(", "shouldBlockDomain", ")", "=>", "shouldSkipDomains", ".", "every", "(", "(", "shouldSkipDomain", ")", "=>", "isThirdPartyHost", "(", "shouldBlockDomain", ",", "shouldSkipDomain", ")", ")", ")", ";", "let", "leftOverSkipping", "=", "shouldSkipDomains", ".", "filter", "(", "(", "shouldSkipDomain", ")", "=>", "shouldBlockDomains", ".", "every", "(", "(", "shouldBlockDomain", ")", "=>", "isThirdPartyHost", "(", "shouldSkipDomain", ",", "shouldBlockDomain", ")", ")", ")", ";", "if", "(", "shouldBlockDomains", ".", "length", "===", "0", "&&", "parsedFilterData", ".", "options", ".", "domains", ".", "length", "!==", "0", "||", "shouldBlockDomains", ".", "length", ">", "0", "&&", "leftOverBlocking", ".", "length", "===", "0", "||", "shouldSkipDomains", ".", "length", ">", "0", "&&", "leftOverSkipping", ".", "length", ">", "0", ")", "{", "return", "false", ";", "}", "}", "}", "if", "(", "contextParams", "[", "'third-party'", "]", "!==", "undefined", ")", "{", "if", "(", "filterDataContainsOption", "(", "parsedFilterData", ",", "'third-party'", ")", ")", "{", "let", "inputHost", "=", "getUrlHost", "(", "input", ")", ";", "let", "inputHostIsThirdParty", "=", "isThirdPartyHost", "(", "parsedFilterData", ".", "host", ",", "inputHost", ")", ";", "if", "(", "inputHostIsThirdParty", "||", "!", "contextParams", "[", "'third-party'", "]", ")", "{", "return", "false", ";", "}", "}", "}", "return", "true", ";", "}" ]
Determines if there's a match based on the options, this doesn't mean that the filter rule shoudl be accepted, just that the filter rule should be considered given the current context. By specifying context params, you can filter out the number of rules which are considered.
[ "Determines", "if", "there", "s", "a", "match", "based", "on", "the", "options", "this", "doesn", "t", "mean", "that", "the", "filter", "rule", "shoudl", "be", "accepted", "just", "that", "the", "filter", "rule", "should", "be", "considered", "given", "the", "current", "context", ".", "By", "specifying", "context", "params", "you", "can", "filter", "out", "the", "number", "of", "rules", "which", "are", "considered", "." ]
653690db8a229cc8cd5cafad393dc1e0260dd1f8
https://github.com/bbondy/abp-filter-parser/blob/653690db8a229cc8cd5cafad393dc1e0260dd1f8/src/abp-filter-parser.js#L386-L437
train
fenos/graphql-thinky
src/relay/resolver.js
toCursor
function toCursor(item, index) { const id = item.id; return base64(cursorPrefix + id + cursorSeparator + index); }
javascript
function toCursor(item, index) { const id = item.id; return base64(cursorPrefix + id + cursorSeparator + index); }
[ "function", "toCursor", "(", "item", ",", "index", ")", "{", "const", "id", "=", "item", ".", "id", ";", "return", "base64", "(", "cursorPrefix", "+", "id", "+", "cursorSeparator", "+", "index", ")", ";", "}" ]
Creates a cursor based on the item and the index of where is located on the result set. needed to identify edges @param item @param index @returns {*}
[ "Creates", "a", "cursor", "based", "on", "the", "item", "and", "the", "index", "of", "where", "is", "located", "on", "the", "result", "set", ".", "needed", "to", "identify", "edges" ]
efada88aeaabac7d0e1563e658c5f182273c7805
https://github.com/fenos/graphql-thinky/blob/efada88aeaabac7d0e1563e658c5f182273c7805/src/relay/resolver.js#L18-L21
train
fenos/graphql-thinky
src/relay/resolver.js
fromCursor
function fromCursor(cursor) { cursor = unbase64(cursor); cursor = cursor.substring(cursorPrefix.length, cursor.length); const [id, index] = cursor.split(cursorSeparator); return { id, index }; }
javascript
function fromCursor(cursor) { cursor = unbase64(cursor); cursor = cursor.substring(cursorPrefix.length, cursor.length); const [id, index] = cursor.split(cursorSeparator); return { id, index }; }
[ "function", "fromCursor", "(", "cursor", ")", "{", "cursor", "=", "unbase64", "(", "cursor", ")", ";", "cursor", "=", "cursor", ".", "substring", "(", "cursorPrefix", ".", "length", ",", "cursor", ".", "length", ")", ";", "const", "[", "id", ",", "index", "]", "=", "cursor", ".", "split", "(", "cursorSeparator", ")", ";", "return", "{", "id", ",", "index", "}", ";", "}" ]
Decode a cursor into its component parts @param cursor @returns {{id, index}}
[ "Decode", "a", "cursor", "into", "its", "component", "parts" ]
efada88aeaabac7d0e1563e658c5f182273c7805
https://github.com/fenos/graphql-thinky/blob/efada88aeaabac7d0e1563e658c5f182273c7805/src/relay/resolver.js#L29-L38
train
fenos/graphql-thinky
src/relay/resolver.js
resolveEdge
function resolveEdge(item, index, queriedCursor, args = {}, source) { if (queriedCursor) { index = parseInt(queriedCursor.index, 10) + index; if (index === 0) { index = 1; } else { index++; } } return { cursor: toCursor(item, index), node: item, source }; }
javascript
function resolveEdge(item, index, queriedCursor, args = {}, source) { if (queriedCursor) { index = parseInt(queriedCursor.index, 10) + index; if (index === 0) { index = 1; } else { index++; } } return { cursor: toCursor(item, index), node: item, source }; }
[ "function", "resolveEdge", "(", "item", ",", "index", ",", "queriedCursor", ",", "args", "=", "{", "}", ",", "source", ")", "{", "if", "(", "queriedCursor", ")", "{", "index", "=", "parseInt", "(", "queriedCursor", ".", "index", ",", "10", ")", "+", "index", ";", "if", "(", "index", "===", "0", ")", "{", "index", "=", "1", ";", "}", "else", "{", "index", "++", ";", "}", "}", "return", "{", "cursor", ":", "toCursor", "(", "item", ",", "index", ")", ",", "node", ":", "item", ",", "source", "}", ";", "}" ]
Resolve an edge within it's cursor, node and source @param item @param index @param queriedCursor @param args @param source @returns {{cursor: *, node: *, source: *}}
[ "Resolve", "an", "edge", "within", "it", "s", "cursor", "node", "and", "source" ]
efada88aeaabac7d0e1563e658c5f182273c7805
https://github.com/fenos/graphql-thinky/blob/efada88aeaabac7d0e1563e658c5f182273c7805/src/relay/resolver.js#L51-L65
train
fenos/graphql-thinky
src/relay/resolver.js
createEdgeInfo
function createEdgeInfo(resultset, offset, index) { const limit = offset - index; // retrieve full count from the first edge // or default 10 let fullCount = resultset[0] && resultset[0].fullCount && parseInt(resultset[0].fullCount, 10); if (!resultset[0]) { fullCount = 0; } let hasNextPage = false; let hasPreviousPage = false; if (offset) { const requested = (index + 1) * limit; hasNextPage = requested < fullCount; hasPreviousPage = (requested > limit); } return { hasNextPage, hasPreviousPage }; }
javascript
function createEdgeInfo(resultset, offset, index) { const limit = offset - index; // retrieve full count from the first edge // or default 10 let fullCount = resultset[0] && resultset[0].fullCount && parseInt(resultset[0].fullCount, 10); if (!resultset[0]) { fullCount = 0; } let hasNextPage = false; let hasPreviousPage = false; if (offset) { const requested = (index + 1) * limit; hasNextPage = requested < fullCount; hasPreviousPage = (requested > limit); } return { hasNextPage, hasPreviousPage }; }
[ "function", "createEdgeInfo", "(", "resultset", ",", "offset", ",", "index", ")", "{", "const", "limit", "=", "offset", "-", "index", ";", "let", "fullCount", "=", "resultset", "[", "0", "]", "&&", "resultset", "[", "0", "]", ".", "fullCount", "&&", "parseInt", "(", "resultset", "[", "0", "]", ".", "fullCount", ",", "10", ")", ";", "if", "(", "!", "resultset", "[", "0", "]", ")", "{", "fullCount", "=", "0", ";", "}", "let", "hasNextPage", "=", "false", ";", "let", "hasPreviousPage", "=", "false", ";", "if", "(", "offset", ")", "{", "const", "requested", "=", "(", "index", "+", "1", ")", "*", "limit", ";", "hasNextPage", "=", "requested", "<", "fullCount", ";", "hasPreviousPage", "=", "(", "requested", ">", "limit", ")", ";", "}", "return", "{", "hasNextPage", ",", "hasPreviousPage", "}", ";", "}" ]
Return location information of an edge @param resultset @param offset @param cursor @returns {{hasMorePages: boolean, hasPreviousPage: boolean}}
[ "Return", "location", "information", "of", "an", "edge" ]
efada88aeaabac7d0e1563e658c5f182273c7805
https://github.com/fenos/graphql-thinky/blob/efada88aeaabac7d0e1563e658c5f182273c7805/src/relay/resolver.js#L76-L101
train
mongoosejs/mongoose-ttl
lib/ttl.js
applyTTL
function applyTTL (cond) { if (cond[key]) { cond.$and || (cond.$and = []); var a = {}; a[key] = cond[key]; cond.$and.push(a); var b = {}; b[key] = { $gt: new Date }; cond.$and.push(b); delete cond[key]; } else { cond[key] = { $gt: new Date }; } }
javascript
function applyTTL (cond) { if (cond[key]) { cond.$and || (cond.$and = []); var a = {}; a[key] = cond[key]; cond.$and.push(a); var b = {}; b[key] = { $gt: new Date }; cond.$and.push(b); delete cond[key]; } else { cond[key] = { $gt: new Date }; } }
[ "function", "applyTTL", "(", "cond", ")", "{", "if", "(", "cond", "[", "key", "]", ")", "{", "cond", ".", "$and", "||", "(", "cond", ".", "$and", "=", "[", "]", ")", ";", "var", "a", "=", "{", "}", ";", "a", "[", "key", "]", "=", "cond", "[", "key", "]", ";", "cond", ".", "$and", ".", "push", "(", "a", ")", ";", "var", "b", "=", "{", "}", ";", "b", "[", "key", "]", "=", "{", "$gt", ":", "new", "Date", "}", ";", "cond", ".", "$and", ".", "push", "(", "b", ")", ";", "delete", "cond", "[", "key", "]", ";", "}", "else", "{", "cond", "[", "key", "]", "=", "{", "$gt", ":", "new", "Date", "}", ";", "}", "}" ]
Applies ttl to query conditions. @private
[ "Applies", "ttl", "to", "query", "conditions", "." ]
68510c82bb63a6585760226a69ea7e41fc5dfc4f
https://github.com/mongoosejs/mongoose-ttl/blob/68510c82bb63a6585760226a69ea7e41fc5dfc4f/lib/ttl.js#L230-L243
train
Breeze/breeze.js.labs
b00_breeze.modelLibrary.new-backingstore.js
movePropsToBackingStore
function movePropsToBackingStore(instance) { var bs = getBackingStore(instance); var proto = Object.getPrototypeOf(instance); var stype = proto.entityType || proto.complexType; stype.getProperties().forEach(function(prop) { var propName = prop.name; if (!instance.hasOwnProperty(propName)) return; // pulls off the value, removes the instance property and then rewrites it via ES5 accessor var value = instance[propName]; delete instance[propName]; instance[propName] = value; }); return bs; }
javascript
function movePropsToBackingStore(instance) { var bs = getBackingStore(instance); var proto = Object.getPrototypeOf(instance); var stype = proto.entityType || proto.complexType; stype.getProperties().forEach(function(prop) { var propName = prop.name; if (!instance.hasOwnProperty(propName)) return; // pulls off the value, removes the instance property and then rewrites it via ES5 accessor var value = instance[propName]; delete instance[propName]; instance[propName] = value; }); return bs; }
[ "function", "movePropsToBackingStore", "(", "instance", ")", "{", "var", "bs", "=", "getBackingStore", "(", "instance", ")", ";", "var", "proto", "=", "Object", ".", "getPrototypeOf", "(", "instance", ")", ";", "var", "stype", "=", "proto", ".", "entityType", "||", "proto", ".", "complexType", ";", "stype", ".", "getProperties", "(", ")", ".", "forEach", "(", "function", "(", "prop", ")", "{", "var", "propName", "=", "prop", ".", "name", ";", "if", "(", "!", "instance", ".", "hasOwnProperty", "(", "propName", ")", ")", "return", ";", "var", "value", "=", "instance", "[", "propName", "]", ";", "delete", "instance", "[", "propName", "]", ";", "instance", "[", "propName", "]", "=", "value", ";", "}", ")", ";", "return", "bs", ";", "}" ]
'movePropsToBackingStore' called when an instance is first created via materialization or createEntity. this method cannot be called while a 'defineProperty' accessor is executing because of IE bug mentioned in 'startTracking'.
[ "movePropsToBackingStore", "called", "when", "an", "instance", "is", "first", "created", "via", "materialization", "or", "createEntity", ".", "this", "method", "cannot", "be", "called", "while", "a", "defineProperty", "accessor", "is", "executing", "because", "of", "IE", "bug", "mentioned", "in", "startTracking", "." ]
9bf796ebaf8fc2918744f3723bd5bb1fc48fe011
https://github.com/Breeze/breeze.js.labs/blob/9bf796ebaf8fc2918744f3723bd5bb1fc48fe011/b00_breeze.modelLibrary.new-backingstore.js#L149-L163
train
Breeze/breeze.js.labs
b00_breeze.modelLibrary.new-backingstore.js
movePropDefsToProto
function movePropDefsToProto(proto) { var stype = proto.entityType || proto.complexType; var ctor = proto.constructor; if (!ctor){ throw new Error("No type constructor for EntityType = "+stype.name); } addResetFn(ctor); stype.getProperties().forEach(function(prop) { var propName = prop.name; if (propName in proto) { wrapPrototypeProperty(proto, prop); } else { wrapInstanceProperty(proto, prop); } }); }
javascript
function movePropDefsToProto(proto) { var stype = proto.entityType || proto.complexType; var ctor = proto.constructor; if (!ctor){ throw new Error("No type constructor for EntityType = "+stype.name); } addResetFn(ctor); stype.getProperties().forEach(function(prop) { var propName = prop.name; if (propName in proto) { wrapPrototypeProperty(proto, prop); } else { wrapInstanceProperty(proto, prop); } }); }
[ "function", "movePropDefsToProto", "(", "proto", ")", "{", "var", "stype", "=", "proto", ".", "entityType", "||", "proto", ".", "complexType", ";", "var", "ctor", "=", "proto", ".", "constructor", ";", "if", "(", "!", "ctor", ")", "{", "throw", "new", "Error", "(", "\"No type constructor for EntityType = \"", "+", "stype", ".", "name", ")", ";", "}", "addResetFn", "(", "ctor", ")", ";", "stype", ".", "getProperties", "(", ")", ".", "forEach", "(", "function", "(", "prop", ")", "{", "var", "propName", "=", "prop", ".", "name", ";", "if", "(", "propName", "in", "proto", ")", "{", "wrapPrototypeProperty", "(", "proto", ",", "prop", ")", ";", "}", "else", "{", "wrapInstanceProperty", "(", "proto", ",", "prop", ")", ";", "}", "}", ")", ";", "}" ]
'movePropDefsToProto' called during Metadata initialization to properties for interception
[ "movePropDefsToProto", "called", "during", "Metadata", "initialization", "to", "properties", "for", "interception" ]
9bf796ebaf8fc2918744f3723bd5bb1fc48fe011
https://github.com/Breeze/breeze.js.labs/blob/9bf796ebaf8fc2918744f3723bd5bb1fc48fe011/b00_breeze.modelLibrary.new-backingstore.js#L166-L181
train
Breeze/breeze.js.labs
b00_breeze.modelLibrary.new-backingstore.js
getAccessorFn
function getAccessorFn(bs, propName) { return function () { if (arguments.length == 0) { return bs[propName]; } else { bs[propName] = arguments[0]; } }; }
javascript
function getAccessorFn(bs, propName) { return function () { if (arguments.length == 0) { return bs[propName]; } else { bs[propName] = arguments[0]; } }; }
[ "function", "getAccessorFn", "(", "bs", ",", "propName", ")", "{", "return", "function", "(", ")", "{", "if", "(", "arguments", ".", "length", "==", "0", ")", "{", "return", "bs", "[", "propName", "]", ";", "}", "else", "{", "bs", "[", "propName", "]", "=", "arguments", "[", "0", "]", ";", "}", "}", ";", "}" ]
A caching version of this 'getAccessorFn' was removed as the perf gain is minimal or negative based on simple testing.
[ "A", "caching", "version", "of", "this", "getAccessorFn", "was", "removed", "as", "the", "perf", "gain", "is", "minimal", "or", "negative", "based", "on", "simple", "testing", "." ]
9bf796ebaf8fc2918744f3723bd5bb1fc48fe011
https://github.com/Breeze/breeze.js.labs/blob/9bf796ebaf8fc2918744f3723bd5bb1fc48fe011/b00_breeze.modelLibrary.new-backingstore.js#L257-L265
train
Breeze/breeze.js.labs
breeze.directives.js
linkForInput
function linkForInput() { var valTemplate = config.zValidateTemplate; var requiredTemplate = config.zRequiredTemplate || ''; var decorator = angular.element('<span class="z-decorator"></span>'); if (attrs.zAppendTo){ angular.element(document.querySelector(attrs.zAppendTo)).append(decorator); } else { element.after(decorator); } // unwrap bound elements decorator = decorator[0]; scope.$watch(info.getValErrs, valErrsChanged); // update the message in the validation template // when a validation error changes on an input control // newValue is either a string or null (null when no bound entity) function valErrsChanged(newValue) { // HTML5 custom validity // http://dev.w3.org/html5/spec-preview/constraints.html#the-constraint-validation-api if (domEl.setCustomValidity) { /* only works in HTML 5. Maybe should throw if not available. */ domEl.setCustomValidity(newValue || ''); } var errorHtml = newValue ? valTemplate.replace(/%error%/, newValue) : ""; var isRequired = info.getIsRequired(); var requiredHtml = isRequired ? requiredTemplate : ''; decorator.innerHTML = (isRequired || !!errorHtml) ? requiredHtml + errorHtml : ""; } }
javascript
function linkForInput() { var valTemplate = config.zValidateTemplate; var requiredTemplate = config.zRequiredTemplate || ''; var decorator = angular.element('<span class="z-decorator"></span>'); if (attrs.zAppendTo){ angular.element(document.querySelector(attrs.zAppendTo)).append(decorator); } else { element.after(decorator); } // unwrap bound elements decorator = decorator[0]; scope.$watch(info.getValErrs, valErrsChanged); // update the message in the validation template // when a validation error changes on an input control // newValue is either a string or null (null when no bound entity) function valErrsChanged(newValue) { // HTML5 custom validity // http://dev.w3.org/html5/spec-preview/constraints.html#the-constraint-validation-api if (domEl.setCustomValidity) { /* only works in HTML 5. Maybe should throw if not available. */ domEl.setCustomValidity(newValue || ''); } var errorHtml = newValue ? valTemplate.replace(/%error%/, newValue) : ""; var isRequired = info.getIsRequired(); var requiredHtml = isRequired ? requiredTemplate : ''; decorator.innerHTML = (isRequired || !!errorHtml) ? requiredHtml + errorHtml : ""; } }
[ "function", "linkForInput", "(", ")", "{", "var", "valTemplate", "=", "config", ".", "zValidateTemplate", ";", "var", "requiredTemplate", "=", "config", ".", "zRequiredTemplate", "||", "''", ";", "var", "decorator", "=", "angular", ".", "element", "(", "'<span class=\"z-decorator\"></span>'", ")", ";", "if", "(", "attrs", ".", "zAppendTo", ")", "{", "angular", ".", "element", "(", "document", ".", "querySelector", "(", "attrs", ".", "zAppendTo", ")", ")", ".", "append", "(", "decorator", ")", ";", "}", "else", "{", "element", ".", "after", "(", "decorator", ")", ";", "}", "decorator", "=", "decorator", "[", "0", "]", ";", "scope", ".", "$watch", "(", "info", ".", "getValErrs", ",", "valErrsChanged", ")", ";", "function", "valErrsChanged", "(", "newValue", ")", "{", "if", "(", "domEl", ".", "setCustomValidity", ")", "{", "domEl", ".", "setCustomValidity", "(", "newValue", "||", "''", ")", ";", "}", "var", "errorHtml", "=", "newValue", "?", "valTemplate", ".", "replace", "(", "/", "%error%", "/", ",", "newValue", ")", ":", "\"\"", ";", "var", "isRequired", "=", "info", ".", "getIsRequired", "(", ")", ";", "var", "requiredHtml", "=", "isRequired", "?", "requiredTemplate", ":", "''", ";", "decorator", ".", "innerHTML", "=", "(", "isRequired", "||", "!", "!", "errorHtml", ")", "?", "requiredHtml", "+", "errorHtml", ":", "\"\"", ";", "}", "}" ]
directive is on an input element, so use templates for required and validation display
[ "directive", "is", "on", "an", "input", "element", "so", "use", "templates", "for", "required", "and", "validation", "display" ]
9bf796ebaf8fc2918744f3723bd5bb1fc48fe011
https://github.com/Breeze/breeze.js.labs/blob/9bf796ebaf8fc2918744f3723bd5bb1fc48fe011/breeze.directives.js#L122-L153
train
Breeze/breeze.js.labs
breeze.directives.js
createGetValErrs
function createGetValErrs(info) { return function () { var aspect = info.getEntityAspect(); if (aspect) { var errs = aspect.getValidationErrors(info.propertyPath); if (errs.length) { return errs // concatenate all errors into a single string .map(function (e) { return e.errorMessage; }) .join('; '); } return ''; } // No data bound entity yet. // Return something other than a string so that // watch calls `valErrsChanged` when an entity is bound return null; }; }
javascript
function createGetValErrs(info) { return function () { var aspect = info.getEntityAspect(); if (aspect) { var errs = aspect.getValidationErrors(info.propertyPath); if (errs.length) { return errs // concatenate all errors into a single string .map(function (e) { return e.errorMessage; }) .join('; '); } return ''; } // No data bound entity yet. // Return something other than a string so that // watch calls `valErrsChanged` when an entity is bound return null; }; }
[ "function", "createGetValErrs", "(", "info", ")", "{", "return", "function", "(", ")", "{", "var", "aspect", "=", "info", ".", "getEntityAspect", "(", ")", ";", "if", "(", "aspect", ")", "{", "var", "errs", "=", "aspect", ".", "getValidationErrors", "(", "info", ".", "propertyPath", ")", ";", "if", "(", "errs", ".", "length", ")", "{", "return", "errs", ".", "map", "(", "function", "(", "e", ")", "{", "return", "e", ".", "errorMessage", ";", "}", ")", ".", "join", "(", "'; '", ")", ";", "}", "return", "''", ";", "}", "return", "null", ";", "}", ";", "}" ]
Create the 'getValErrs' function that will be watched
[ "Create", "the", "getValErrs", "function", "that", "will", "be", "watched" ]
9bf796ebaf8fc2918744f3723bd5bb1fc48fe011
https://github.com/Breeze/breeze.js.labs/blob/9bf796ebaf8fc2918744f3723bd5bb1fc48fe011/breeze.directives.js#L226-L244
train
Breeze/breeze.js.labs
breeze.directives.js
getIsRequired
function getIsRequired() { var info = this; if (info.isRequired !== undefined) { return info.isRequired; } // We don't know if it is required yet. // Once bound to the entity we can determine whether the data property is required // Note: Not bound until *second* call to the directive's link function // which is why you MUST call 'getIsRequired' // inside 'valErrsChanged' rather than in the link function var entityType = info.getType(); if (entityType) { // the bound entity is known var requiredProperties = getRequiredPropertiesForEntityType(entityType); return info.isRequired = !!requiredProperties[info.propertyPath]; } return undefined; // don't know yet }
javascript
function getIsRequired() { var info = this; if (info.isRequired !== undefined) { return info.isRequired; } // We don't know if it is required yet. // Once bound to the entity we can determine whether the data property is required // Note: Not bound until *second* call to the directive's link function // which is why you MUST call 'getIsRequired' // inside 'valErrsChanged' rather than in the link function var entityType = info.getType(); if (entityType) { // the bound entity is known var requiredProperties = getRequiredPropertiesForEntityType(entityType); return info.isRequired = !!requiredProperties[info.propertyPath]; } return undefined; // don't know yet }
[ "function", "getIsRequired", "(", ")", "{", "var", "info", "=", "this", ";", "if", "(", "info", ".", "isRequired", "!==", "undefined", ")", "{", "return", "info", ".", "isRequired", ";", "}", "var", "entityType", "=", "info", ".", "getType", "(", ")", ";", "if", "(", "entityType", ")", "{", "var", "requiredProperties", "=", "getRequiredPropertiesForEntityType", "(", "entityType", ")", ";", "return", "info", ".", "isRequired", "=", "!", "!", "requiredProperties", "[", "info", ".", "propertyPath", "]", ";", "}", "return", "undefined", ";", "}" ]
determine if bound property is required.
[ "determine", "if", "bound", "property", "is", "required", "." ]
9bf796ebaf8fc2918744f3723bd5bb1fc48fe011
https://github.com/Breeze/breeze.js.labs/blob/9bf796ebaf8fc2918744f3723bd5bb1fc48fe011/breeze.directives.js#L266-L283
train
fenos/graphql-thinky
src/resolver.js
_isList
function _isList(gqlTye) { if (gqlTye instanceof GraphQLList) { return true; } if (gqlTye instanceof GraphQLNonNull) { return _isList(gqlTye.ofType); } return false; }
javascript
function _isList(gqlTye) { if (gqlTye instanceof GraphQLList) { return true; } if (gqlTye instanceof GraphQLNonNull) { return _isList(gqlTye.ofType); } return false; }
[ "function", "_isList", "(", "gqlTye", ")", "{", "if", "(", "gqlTye", "instanceof", "GraphQLList", ")", "{", "return", "true", ";", "}", "if", "(", "gqlTye", "instanceof", "GraphQLNonNull", ")", "{", "return", "_isList", "(", "gqlTye", ".", "ofType", ")", ";", "}", "return", "false", ";", "}" ]
Determine if the GQL node is a list @param gqlTye @returns {*} @private
[ "Determine", "if", "the", "GQL", "node", "is", "a", "list" ]
efada88aeaabac7d0e1563e658c5f182273c7805
https://github.com/fenos/graphql-thinky/blob/efada88aeaabac7d0e1563e658c5f182273c7805/src/resolver.js#L13-L23
train
rtc-io/rtc-sdp
prefer-codecs.js
convertToCodecDefinition
function convertToCodecDefinition(r, line) { if (!line || line[0] !== 'a') return r; var result = reRtpMap.exec(line[1]); if (!result) return r; // Build the codec definition var codec = result[2]; var typeNum = result[1]; r[codec.toUpperCase()] = { num: typeNum, codec: codec } return r; }
javascript
function convertToCodecDefinition(r, line) { if (!line || line[0] !== 'a') return r; var result = reRtpMap.exec(line[1]); if (!result) return r; // Build the codec definition var codec = result[2]; var typeNum = result[1]; r[codec.toUpperCase()] = { num: typeNum, codec: codec } return r; }
[ "function", "convertToCodecDefinition", "(", "r", ",", "line", ")", "{", "if", "(", "!", "line", "||", "line", "[", "0", "]", "!==", "'a'", ")", "return", "r", ";", "var", "result", "=", "reRtpMap", ".", "exec", "(", "line", "[", "1", "]", ")", ";", "if", "(", "!", "result", ")", "return", "r", ";", "var", "codec", "=", "result", "[", "2", "]", ";", "var", "typeNum", "=", "result", "[", "1", "]", ";", "r", "[", "codec", ".", "toUpperCase", "(", ")", "]", "=", "{", "num", ":", "typeNum", ",", "codec", ":", "codec", "}", "return", "r", ";", "}" ]
Converts rtpmap definitions to a codec lookup object
[ "Converts", "rtpmap", "definitions", "to", "a", "codec", "lookup", "object" ]
64d6cb2ba397db9c2b9b97187a720815cf9fac7a
https://github.com/rtc-io/rtc-sdp/blob/64d6cb2ba397db9c2b9b97187a720815cf9fac7a/prefer-codecs.js#L36-L50
train
swimlane/angular-model-factory
src/modelFactory.js
function(rawObj, arrayInst){ // create an instance var inst = rawObj.constructor === Model ? rawObj : new Model(rawObj); // set a pointer to the array inst.$$array = arrayInst; return inst; }
javascript
function(rawObj, arrayInst){ // create an instance var inst = rawObj.constructor === Model ? rawObj : new Model(rawObj); // set a pointer to the array inst.$$array = arrayInst; return inst; }
[ "function", "(", "rawObj", ",", "arrayInst", ")", "{", "var", "inst", "=", "rawObj", ".", "constructor", "===", "Model", "?", "rawObj", ":", "new", "Model", "(", "rawObj", ")", ";", "inst", ".", "$$array", "=", "arrayInst", ";", "return", "inst", ";", "}" ]
helper function for creating a new instance of a model from a raw JavaScript obj. If it is already a model, it will be left as it is
[ "helper", "function", "for", "creating", "a", "new", "instance", "of", "a", "model", "from", "a", "raw", "JavaScript", "obj", ".", "If", "it", "is", "already", "a", "model", "it", "will", "be", "left", "as", "it", "is" ]
9e876387f964cff1a4d1cca64bd20f86200717f3
https://github.com/swimlane/angular-model-factory/blob/9e876387f964cff1a4d1cca64bd20f86200717f3/src/modelFactory.js#L339-L348
train
natesilva/jayschema
lib/jayschema.js
function(ref, deferred, loaderErr, schema) { if (loaderErr) { return deferred.reject(loaderErr); } if (!this._schemaRegistry.isRegistered(ref)) { this.register(schema, ref); } deferred.resolve(schema); }
javascript
function(ref, deferred, loaderErr, schema) { if (loaderErr) { return deferred.reject(loaderErr); } if (!this._schemaRegistry.isRegistered(ref)) { this.register(schema, ref); } deferred.resolve(schema); }
[ "function", "(", "ref", ",", "deferred", ",", "loaderErr", ",", "schema", ")", "{", "if", "(", "loaderErr", ")", "{", "return", "deferred", ".", "reject", "(", "loaderErr", ")", ";", "}", "if", "(", "!", "this", ".", "_schemaRegistry", ".", "isRegistered", "(", "ref", ")", ")", "{", "this", ".", "register", "(", "schema", ",", "ref", ")", ";", "}", "deferred", ".", "resolve", "(", "schema", ")", ";", "}" ]
function called when the loader finishes loading a schema
[ "function", "called", "when", "the", "loader", "finishes", "loading", "a", "schema" ]
53a77b05999b3b7b55c0a3508912aad13b4f67c4
https://github.com/natesilva/jayschema/blob/53a77b05999b3b7b55c0a3508912aad13b4f67c4/lib/jayschema.js#L144-L148
train
larsvoigt/epub-full-text-search
example/as-a-service/express/controller.js
instantSearch
function instantSearch() { const q = $("#searchbox").val(); if (q === '') return; const matcher = "/matcher?beginsWith=" + q; const request = host + matcher; console.debug(request); $.getJSON(request, '', {}) .done(data => { $("#searchbox").autocomplete({ source: data, select: (event) => { event.stopPropagation(); $("#search").trigger("click"); } }); }) .fail((d, textStatus, error) => { const err = d.status + " " + error + " -> message: " + d.responseText; bootstrapAlert.error(err); console.error(`Search request failed: \n ${err}`); }); }
javascript
function instantSearch() { const q = $("#searchbox").val(); if (q === '') return; const matcher = "/matcher?beginsWith=" + q; const request = host + matcher; console.debug(request); $.getJSON(request, '', {}) .done(data => { $("#searchbox").autocomplete({ source: data, select: (event) => { event.stopPropagation(); $("#search").trigger("click"); } }); }) .fail((d, textStatus, error) => { const err = d.status + " " + error + " -> message: " + d.responseText; bootstrapAlert.error(err); console.error(`Search request failed: \n ${err}`); }); }
[ "function", "instantSearch", "(", ")", "{", "const", "q", "=", "$", "(", "\"#searchbox\"", ")", ".", "val", "(", ")", ";", "if", "(", "q", "===", "''", ")", "return", ";", "const", "matcher", "=", "\"/matcher?beginsWith=\"", "+", "q", ";", "const", "request", "=", "host", "+", "matcher", ";", "console", ".", "debug", "(", "request", ")", ";", "$", ".", "getJSON", "(", "request", ",", "''", ",", "{", "}", ")", ".", "done", "(", "data", "=>", "{", "$", "(", "\"#searchbox\"", ")", ".", "autocomplete", "(", "{", "source", ":", "data", ",", "select", ":", "(", "event", ")", "=>", "{", "event", ".", "stopPropagation", "(", ")", ";", "$", "(", "\"#search\"", ")", ".", "trigger", "(", "\"click\"", ")", ";", "}", "}", ")", ";", "}", ")", ".", "fail", "(", "(", "d", ",", "textStatus", ",", "error", ")", "=>", "{", "const", "err", "=", "d", ".", "status", "+", "\" \"", "+", "error", "+", "\" -> message: \"", "+", "d", ".", "responseText", ";", "bootstrapAlert", ".", "error", "(", "err", ")", ";", "console", ".", "error", "(", "`", "\\n", "${", "err", "}", "`", ")", ";", "}", ")", ";", "}" ]
looking for suggestions
[ "looking", "for", "suggestions" ]
15f511928149b09f7729cbe14de21e5e7261dbf0
https://github.com/larsvoigt/epub-full-text-search/blob/15f511928149b09f7729cbe14de21e5e7261dbf0/example/as-a-service/express/controller.js#L115-L143
train
larsvoigt/epub-full-text-search
src/WebService.js
terminator
function terminator(sig) { if (typeof sig === "string") { winston.log('info', '%s: Received %s - terminating service ...', Date(Date.now()), sig); process.exit(1); } winston.log('info', '%s: EPUB search stopped.', Date(Date.now())); }
javascript
function terminator(sig) { if (typeof sig === "string") { winston.log('info', '%s: Received %s - terminating service ...', Date(Date.now()), sig); process.exit(1); } winston.log('info', '%s: EPUB search stopped.', Date(Date.now())); }
[ "function", "terminator", "(", "sig", ")", "{", "if", "(", "typeof", "sig", "===", "\"string\"", ")", "{", "winston", ".", "log", "(", "'info'", ",", "'%s: Received %s - terminating service ...'", ",", "Date", "(", "Date", ".", "now", "(", ")", ")", ",", "sig", ")", ";", "process", ".", "exit", "(", "1", ")", ";", "}", "winston", ".", "log", "(", "'info'", ",", "'%s: EPUB search stopped.'", ",", "Date", "(", "Date", ".", "now", "(", ")", ")", ")", ";", "}" ]
POST or GET???
[ "POST", "or", "GET???" ]
15f511928149b09f7729cbe14de21e5e7261dbf0
https://github.com/larsvoigt/epub-full-text-search/blob/15f511928149b09f7729cbe14de21e5e7261dbf0/src/WebService.js#L28-L35
train
vingkan/prometheus
pandora/lunr.js
function (config) { var idx = new lunr.Index idx.pipeline.add( lunr.trimmer, lunr.stopWordFilter, lunr.stemmer ) if (config) config.call(idx, idx) return idx }
javascript
function (config) { var idx = new lunr.Index idx.pipeline.add( lunr.trimmer, lunr.stopWordFilter, lunr.stemmer ) if (config) config.call(idx, idx) return idx }
[ "function", "(", "config", ")", "{", "var", "idx", "=", "new", "lunr", ".", "Index", "idx", ".", "pipeline", ".", "add", "(", "lunr", ".", "trimmer", ",", "lunr", ".", "stopWordFilter", ",", "lunr", ".", "stemmer", ")", "if", "(", "config", ")", "config", ".", "call", "(", "idx", ",", "idx", ")", "return", "idx", "}" ]
Convenience function for instantiating a new lunr index and configuring it with the default pipeline functions and the passed config function. When using this convenience function a new index will be created with the following functions already in the pipeline: lunr.StopWordFilter - filters out any stop words before they enter the index lunr.stemmer - stems the tokens before entering the index. Example: var idx = lunr(function () { this.field('title', 10) this.field('tags', 100) this.field('body') this.ref('cid') this.pipeline.add(function () { // some custom pipeline function }) }) @param {Function} config A function that will be called with the new instance of the lunr.Index as both its context and first parameter. It can be used to customize the instance of new lunr.Index. @namespace @module @returns {lunr.Index}
[ "Convenience", "function", "for", "instantiating", "a", "new", "lunr", "index", "and", "configuring", "it", "with", "the", "default", "pipeline", "functions", "and", "the", "passed", "config", "function", "." ]
4dafb04f7329abcfd59e37e29f433a05b2caff8e
https://github.com/vingkan/prometheus/blob/4dafb04f7329abcfd59e37e29f433a05b2caff8e/pandora/lunr.js#L45-L57
train
esatterwhite/node-seeli
lib/command.js
merge
function merge() { let i = 1 , key , val , obj , target ; // make sure we don't modify source element and it's properties // objects are passed by reference target = clone( arguments[0] ); while (obj = arguments[i++]) { for (key in obj) { if ( !hasOwn(obj, key) ) { continue; } val = obj[key]; if ( isObject(val) && isObject(target[key]) ){ // inception, deep merge objects target[key] = merge(target[key], val); } else { let is_url = val && val.type == url; let is_path = val && val.type == path; // make sure arrays, regexp, date, objects are cloned target[key] = clone(val); if( is_url ){ target[key].type = url; } if( is_path ){ target[key].type = path; } } } } return target; }
javascript
function merge() { let i = 1 , key , val , obj , target ; // make sure we don't modify source element and it's properties // objects are passed by reference target = clone( arguments[0] ); while (obj = arguments[i++]) { for (key in obj) { if ( !hasOwn(obj, key) ) { continue; } val = obj[key]; if ( isObject(val) && isObject(target[key]) ){ // inception, deep merge objects target[key] = merge(target[key], val); } else { let is_url = val && val.type == url; let is_path = val && val.type == path; // make sure arrays, regexp, date, objects are cloned target[key] = clone(val); if( is_url ){ target[key].type = url; } if( is_path ){ target[key].type = path; } } } } return target; }
[ "function", "merge", "(", ")", "{", "let", "i", "=", "1", ",", "key", ",", "val", ",", "obj", ",", "target", ";", "target", "=", "clone", "(", "arguments", "[", "0", "]", ")", ";", "while", "(", "obj", "=", "arguments", "[", "i", "++", "]", ")", "{", "for", "(", "key", "in", "obj", ")", "{", "if", "(", "!", "hasOwn", "(", "obj", ",", "key", ")", ")", "{", "continue", ";", "}", "val", "=", "obj", "[", "key", "]", ";", "if", "(", "isObject", "(", "val", ")", "&&", "isObject", "(", "target", "[", "key", "]", ")", ")", "{", "target", "[", "key", "]", "=", "merge", "(", "target", "[", "key", "]", ",", "val", ")", ";", "}", "else", "{", "let", "is_url", "=", "val", "&&", "val", ".", "type", "==", "url", ";", "let", "is_path", "=", "val", "&&", "val", ".", "type", "==", "path", ";", "target", "[", "key", "]", "=", "clone", "(", "val", ")", ";", "if", "(", "is_url", ")", "{", "target", "[", "key", "]", ".", "type", "=", "url", ";", "}", "if", "(", "is_path", ")", "{", "target", "[", "key", "]", ".", "type", "=", "path", ";", "}", "}", "}", "}", "return", "target", ";", "}" ]
Deep merge objects. except for path & url this breaks nopt as it is comparing to those module objects
[ "Deep", "merge", "objects", ".", "except", "for", "path", "&", "url", "this", "breaks", "nopt", "as", "it", "is", "comparing", "to", "those", "module", "objects" ]
706ad7d5333d4c32a2dcbe306ae969ac988aac20
https://github.com/esatterwhite/node-seeli/blob/706ad7d5333d4c32a2dcbe306ae969ac988aac20/lib/command.js#L59-L97
train
nzamani/ui5-nabi-m
demoapp/MyLibraryDemoApp/webapp/Component.js
function() { // call the base component's init function UIComponent.prototype.init.apply(this, arguments); // set the device model this.setModel(models.createDeviceModel(), "device"); // create the views based on the url/hash this.getRouter().initialize(); }
javascript
function() { // call the base component's init function UIComponent.prototype.init.apply(this, arguments); // set the device model this.setModel(models.createDeviceModel(), "device"); // create the views based on the url/hash this.getRouter().initialize(); }
[ "function", "(", ")", "{", "UIComponent", ".", "prototype", ".", "init", ".", "apply", "(", "this", ",", "arguments", ")", ";", "this", ".", "setModel", "(", "models", ".", "createDeviceModel", "(", ")", ",", "\"device\"", ")", ";", "this", ".", "getRouter", "(", ")", ".", "initialize", "(", ")", ";", "}" ]
The component is initialized by UI5 automatically during the startup of the app and calls the init method once. @public @override
[ "The", "component", "is", "initialized", "by", "UI5", "automatically", "during", "the", "startup", "of", "the", "app", "and", "calls", "the", "init", "method", "once", "." ]
0761d2e31298c59e234c05e3ac74038ced572985
https://github.com/nzamani/ui5-nabi-m/blob/0761d2e31298c59e234c05e3ac74038ced572985/demoapp/MyLibraryDemoApp/webapp/Component.js#L19-L28
train
Rovak/node-wallet-api
src/utils/account.js
generateAccount
function generateAccount() { let priKeyBytes = genPriKey(); let addressBytes = getAddressFromPriKey(priKeyBytes); let address = getBase58CheckAddress(addressBytes); let privateKey = byteArray2hexStr(priKeyBytes); return { privateKey, address, } }
javascript
function generateAccount() { let priKeyBytes = genPriKey(); let addressBytes = getAddressFromPriKey(priKeyBytes); let address = getBase58CheckAddress(addressBytes); let privateKey = byteArray2hexStr(priKeyBytes); return { privateKey, address, } }
[ "function", "generateAccount", "(", ")", "{", "let", "priKeyBytes", "=", "genPriKey", "(", ")", ";", "let", "addressBytes", "=", "getAddressFromPriKey", "(", "priKeyBytes", ")", ";", "let", "address", "=", "getBase58CheckAddress", "(", "addressBytes", ")", ";", "let", "privateKey", "=", "byteArray2hexStr", "(", "priKeyBytes", ")", ";", "return", "{", "privateKey", ",", "address", ",", "}", "}" ]
Generate a new account
[ "Generate", "a", "new", "account" ]
5084fe318bb8cecaea35bf73383968ae9bc33094
https://github.com/Rovak/node-wallet-api/blob/5084fe318bb8cecaea35bf73383968ae9bc33094/src/utils/account.js#L8-L18
train
Rovak/node-wallet-api
src/lib/code.js
strToDate
function strToDate(str) { var tempStrs = str.split(" "); var dateStrs = tempStrs[0].split("-"); var year = parseInt(dateStrs[0], 10); var month = parseInt(dateStrs[1], 10) - 1; var day = parseInt(dateStrs[2], 10); if (tempStrs.length > 1) { var timeStrs = tempStrs[1].split("-"); var hour = parseInt(timeStrs [0], 10); var minute = parseInt(timeStrs[1], 10) - 1; var second = parseInt(timeStrs[2], 10); return new Date(year, month, day, hour, minute, second); } return new Date(year, month, day); }
javascript
function strToDate(str) { var tempStrs = str.split(" "); var dateStrs = tempStrs[0].split("-"); var year = parseInt(dateStrs[0], 10); var month = parseInt(dateStrs[1], 10) - 1; var day = parseInt(dateStrs[2], 10); if (tempStrs.length > 1) { var timeStrs = tempStrs[1].split("-"); var hour = parseInt(timeStrs [0], 10); var minute = parseInt(timeStrs[1], 10) - 1; var second = parseInt(timeStrs[2], 10); return new Date(year, month, day, hour, minute, second); } return new Date(year, month, day); }
[ "function", "strToDate", "(", "str", ")", "{", "var", "tempStrs", "=", "str", ".", "split", "(", "\" \"", ")", ";", "var", "dateStrs", "=", "tempStrs", "[", "0", "]", ".", "split", "(", "\"-\"", ")", ";", "var", "year", "=", "parseInt", "(", "dateStrs", "[", "0", "]", ",", "10", ")", ";", "var", "month", "=", "parseInt", "(", "dateStrs", "[", "1", "]", ",", "10", ")", "-", "1", ";", "var", "day", "=", "parseInt", "(", "dateStrs", "[", "2", "]", ",", "10", ")", ";", "if", "(", "tempStrs", ".", "length", ">", "1", ")", "{", "var", "timeStrs", "=", "tempStrs", "[", "1", "]", ".", "split", "(", "\"-\"", ")", ";", "var", "hour", "=", "parseInt", "(", "timeStrs", "[", "0", "]", ",", "10", ")", ";", "var", "minute", "=", "parseInt", "(", "timeStrs", "[", "1", "]", ",", "10", ")", "-", "1", ";", "var", "second", "=", "parseInt", "(", "timeStrs", "[", "2", "]", ",", "10", ")", ";", "return", "new", "Date", "(", "year", ",", "month", ",", "day", ",", "hour", ",", "minute", ",", "second", ")", ";", "}", "return", "new", "Date", "(", "year", ",", "month", ",", "day", ")", ";", "}" ]
yyyy-MM-DD HH-mm-ss
[ "yyyy", "-", "MM", "-", "DD", "HH", "-", "mm", "-", "ss" ]
5084fe318bb8cecaea35bf73383968ae9bc33094
https://github.com/Rovak/node-wallet-api/blob/5084fe318bb8cecaea35bf73383968ae9bc33094/src/lib/code.js#L411-L426
train
cgjs/cgjs
packages/cgjs/cg.js
getProgramDir
function getProgramDir(programFile) { const info = programFile.query_info('standard::', Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, null); if (info.get_is_symlink()) { const symlinkFile = programFile.get_parent().resolve_relative_path(info.get_symlink_target()); return symlinkFile.get_parent(); } else { return programFile.get_parent(); } }
javascript
function getProgramDir(programFile) { const info = programFile.query_info('standard::', Gio.FileQueryInfoFlags.NOFOLLOW_SYMLINKS, null); if (info.get_is_symlink()) { const symlinkFile = programFile.get_parent().resolve_relative_path(info.get_symlink_target()); return symlinkFile.get_parent(); } else { return programFile.get_parent(); } }
[ "function", "getProgramDir", "(", "programFile", ")", "{", "const", "info", "=", "programFile", ".", "query_info", "(", "'standard::'", ",", "Gio", ".", "FileQueryInfoFlags", ".", "NOFOLLOW_SYMLINKS", ",", "null", ")", ";", "if", "(", "info", ".", "get_is_symlink", "(", ")", ")", "{", "const", "symlinkFile", "=", "programFile", ".", "get_parent", "(", ")", ".", "resolve_relative_path", "(", "info", ".", "get_symlink_target", "(", ")", ")", ";", "return", "symlinkFile", ".", "get_parent", "(", ")", ";", "}", "else", "{", "return", "programFile", ".", "get_parent", "(", ")", ";", "}", "}" ]
basic utility for this scope
[ "basic", "utility", "for", "this", "scope" ]
bd2a45dab4ef97affced7ab8f9dbc5dcf7a005db
https://github.com/cgjs/cgjs/blob/bd2a45dab4ef97affced7ab8f9dbc5dcf7a005db/packages/cgjs/cg.js#L71-L79
train
nzamani/ui5-nabi-m
src/nabi/m/thirdparty/pdfjs/web/debugger.js
fontAdded
function fontAdded(fontObj, url) { function properties(obj, list) { var moreInfo = document.createElement('table'); for (var i = 0; i < list.length; i++) { var tr = document.createElement('tr'); var td1 = document.createElement('td'); td1.textContent = list[i]; tr.appendChild(td1); var td2 = document.createElement('td'); td2.textContent = obj[list[i]].toString(); tr.appendChild(td2); moreInfo.appendChild(tr); } return moreInfo; } var moreInfo = properties(fontObj, ['name', 'type']); var fontName = fontObj.loadedName; var font = document.createElement('div'); var name = document.createElement('span'); name.textContent = fontName; var download = document.createElement('a'); if (url) { url = /url\(['"]?([^\)"']+)/.exec(url); download.href = url[1]; } else if (fontObj.data) { url = URL.createObjectURL(new Blob([fontObj.data], { type: fontObj.mimeType, })); download.href = url; } download.textContent = 'Download'; var logIt = document.createElement('a'); logIt.href = ''; logIt.textContent = 'Log'; logIt.addEventListener('click', function(event) { event.preventDefault(); console.log(fontObj); }); var select = document.createElement('input'); select.setAttribute('type', 'checkbox'); select.dataset.fontName = fontName; select.addEventListener('click', (function(select, fontName) { return (function() { selectFont(fontName, select.checked); }); })(select, fontName)); font.appendChild(select); font.appendChild(name); font.appendChild(document.createTextNode(' ')); font.appendChild(download); font.appendChild(document.createTextNode(' ')); font.appendChild(logIt); font.appendChild(moreInfo); fonts.appendChild(font); // Somewhat of a hack, should probably add a hook for when the text layer // is done rendering. setTimeout(() => { if (this.active) { resetSelection(); } }, 2000); }
javascript
function fontAdded(fontObj, url) { function properties(obj, list) { var moreInfo = document.createElement('table'); for (var i = 0; i < list.length; i++) { var tr = document.createElement('tr'); var td1 = document.createElement('td'); td1.textContent = list[i]; tr.appendChild(td1); var td2 = document.createElement('td'); td2.textContent = obj[list[i]].toString(); tr.appendChild(td2); moreInfo.appendChild(tr); } return moreInfo; } var moreInfo = properties(fontObj, ['name', 'type']); var fontName = fontObj.loadedName; var font = document.createElement('div'); var name = document.createElement('span'); name.textContent = fontName; var download = document.createElement('a'); if (url) { url = /url\(['"]?([^\)"']+)/.exec(url); download.href = url[1]; } else if (fontObj.data) { url = URL.createObjectURL(new Blob([fontObj.data], { type: fontObj.mimeType, })); download.href = url; } download.textContent = 'Download'; var logIt = document.createElement('a'); logIt.href = ''; logIt.textContent = 'Log'; logIt.addEventListener('click', function(event) { event.preventDefault(); console.log(fontObj); }); var select = document.createElement('input'); select.setAttribute('type', 'checkbox'); select.dataset.fontName = fontName; select.addEventListener('click', (function(select, fontName) { return (function() { selectFont(fontName, select.checked); }); })(select, fontName)); font.appendChild(select); font.appendChild(name); font.appendChild(document.createTextNode(' ')); font.appendChild(download); font.appendChild(document.createTextNode(' ')); font.appendChild(logIt); font.appendChild(moreInfo); fonts.appendChild(font); // Somewhat of a hack, should probably add a hook for when the text layer // is done rendering. setTimeout(() => { if (this.active) { resetSelection(); } }, 2000); }
[ "function", "fontAdded", "(", "fontObj", ",", "url", ")", "{", "function", "properties", "(", "obj", ",", "list", ")", "{", "var", "moreInfo", "=", "document", ".", "createElement", "(", "'table'", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "var", "tr", "=", "document", ".", "createElement", "(", "'tr'", ")", ";", "var", "td1", "=", "document", ".", "createElement", "(", "'td'", ")", ";", "td1", ".", "textContent", "=", "list", "[", "i", "]", ";", "tr", ".", "appendChild", "(", "td1", ")", ";", "var", "td2", "=", "document", ".", "createElement", "(", "'td'", ")", ";", "td2", ".", "textContent", "=", "obj", "[", "list", "[", "i", "]", "]", ".", "toString", "(", ")", ";", "tr", ".", "appendChild", "(", "td2", ")", ";", "moreInfo", ".", "appendChild", "(", "tr", ")", ";", "}", "return", "moreInfo", ";", "}", "var", "moreInfo", "=", "properties", "(", "fontObj", ",", "[", "'name'", ",", "'type'", "]", ")", ";", "var", "fontName", "=", "fontObj", ".", "loadedName", ";", "var", "font", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "var", "name", "=", "document", ".", "createElement", "(", "'span'", ")", ";", "name", ".", "textContent", "=", "fontName", ";", "var", "download", "=", "document", ".", "createElement", "(", "'a'", ")", ";", "if", "(", "url", ")", "{", "url", "=", "/", "url\\(['\"]?([^\\)\"']+)", "/", ".", "exec", "(", "url", ")", ";", "download", ".", "href", "=", "url", "[", "1", "]", ";", "}", "else", "if", "(", "fontObj", ".", "data", ")", "{", "url", "=", "URL", ".", "createObjectURL", "(", "new", "Blob", "(", "[", "fontObj", ".", "data", "]", ",", "{", "type", ":", "fontObj", ".", "mimeType", ",", "}", ")", ")", ";", "download", ".", "href", "=", "url", ";", "}", "download", ".", "textContent", "=", "'Download'", ";", "var", "logIt", "=", "document", ".", "createElement", "(", "'a'", ")", ";", "logIt", ".", "href", "=", "''", ";", "logIt", ".", "textContent", "=", "'Log'", ";", "logIt", ".", "addEventListener", "(", "'click'", ",", "function", "(", "event", ")", "{", "event", ".", "preventDefault", "(", ")", ";", "console", ".", "log", "(", "fontObj", ")", ";", "}", ")", ";", "var", "select", "=", "document", ".", "createElement", "(", "'input'", ")", ";", "select", ".", "setAttribute", "(", "'type'", ",", "'checkbox'", ")", ";", "select", ".", "dataset", ".", "fontName", "=", "fontName", ";", "select", ".", "addEventListener", "(", "'click'", ",", "(", "function", "(", "select", ",", "fontName", ")", "{", "return", "(", "function", "(", ")", "{", "selectFont", "(", "fontName", ",", "select", ".", "checked", ")", ";", "}", ")", ";", "}", ")", "(", "select", ",", "fontName", ")", ")", ";", "font", ".", "appendChild", "(", "select", ")", ";", "font", ".", "appendChild", "(", "name", ")", ";", "font", ".", "appendChild", "(", "document", ".", "createTextNode", "(", "' '", ")", ")", ";", "font", ".", "appendChild", "(", "download", ")", ";", "font", ".", "appendChild", "(", "document", ".", "createTextNode", "(", "' '", ")", ")", ";", "font", ".", "appendChild", "(", "logIt", ")", ";", "font", ".", "appendChild", "(", "moreInfo", ")", ";", "fonts", ".", "appendChild", "(", "font", ")", ";", "setTimeout", "(", "(", ")", "=>", "{", "if", "(", "this", ".", "active", ")", "{", "resetSelection", "(", ")", ";", "}", "}", ",", "2000", ")", ";", "}" ]
FontInspector specific functions.
[ "FontInspector", "specific", "functions", "." ]
0761d2e31298c59e234c05e3ac74038ced572985
https://github.com/nzamani/ui5-nabi-m/blob/0761d2e31298c59e234c05e3ac74038ced572985/src/nabi/m/thirdparty/pdfjs/web/debugger.js#L96-L157
train
nzamani/ui5-nabi-m
src/nabi/m/thirdparty/pdfjs/web/debugger.js
create
function create(pageIndex) { var debug = document.createElement('div'); debug.id = 'stepper' + pageIndex; debug.setAttribute('hidden', true); debug.className = 'stepper'; stepperDiv.appendChild(debug); var b = document.createElement('option'); b.textContent = 'Page ' + (pageIndex + 1); b.value = pageIndex; stepperChooser.appendChild(b); var initBreakPoints = breakPoints[pageIndex] || []; var stepper = new Stepper(debug, pageIndex, initBreakPoints); steppers.push(stepper); if (steppers.length === 1) { this.selectStepper(pageIndex, false); } return stepper; }
javascript
function create(pageIndex) { var debug = document.createElement('div'); debug.id = 'stepper' + pageIndex; debug.setAttribute('hidden', true); debug.className = 'stepper'; stepperDiv.appendChild(debug); var b = document.createElement('option'); b.textContent = 'Page ' + (pageIndex + 1); b.value = pageIndex; stepperChooser.appendChild(b); var initBreakPoints = breakPoints[pageIndex] || []; var stepper = new Stepper(debug, pageIndex, initBreakPoints); steppers.push(stepper); if (steppers.length === 1) { this.selectStepper(pageIndex, false); } return stepper; }
[ "function", "create", "(", "pageIndex", ")", "{", "var", "debug", "=", "document", ".", "createElement", "(", "'div'", ")", ";", "debug", ".", "id", "=", "'stepper'", "+", "pageIndex", ";", "debug", ".", "setAttribute", "(", "'hidden'", ",", "true", ")", ";", "debug", ".", "className", "=", "'stepper'", ";", "stepperDiv", ".", "appendChild", "(", "debug", ")", ";", "var", "b", "=", "document", ".", "createElement", "(", "'option'", ")", ";", "b", ".", "textContent", "=", "'Page '", "+", "(", "pageIndex", "+", "1", ")", ";", "b", ".", "value", "=", "pageIndex", ";", "stepperChooser", ".", "appendChild", "(", "b", ")", ";", "var", "initBreakPoints", "=", "breakPoints", "[", "pageIndex", "]", "||", "[", "]", ";", "var", "stepper", "=", "new", "Stepper", "(", "debug", ",", "pageIndex", ",", "initBreakPoints", ")", ";", "steppers", ".", "push", "(", "stepper", ")", ";", "if", "(", "steppers", ".", "length", "===", "1", ")", "{", "this", ".", "selectStepper", "(", "pageIndex", ",", "false", ")", ";", "}", "return", "stepper", ";", "}" ]
Stepper specific functions.
[ "Stepper", "specific", "functions", "." ]
0761d2e31298c59e234c05e3ac74038ced572985
https://github.com/nzamani/ui5-nabi-m/blob/0761d2e31298c59e234c05e3ac74038ced572985/src/nabi/m/thirdparty/pdfjs/web/debugger.js#L205-L222
train
nzamani/ui5-nabi-m
src/nabi/m/thirdparty/pdfjs/web/debugger.js
c
function c(tag, textContent) { var d = document.createElement(tag); if (textContent) { d.textContent = textContent; } return d; }
javascript
function c(tag, textContent) { var d = document.createElement(tag); if (textContent) { d.textContent = textContent; } return d; }
[ "function", "c", "(", "tag", ",", "textContent", ")", "{", "var", "d", "=", "document", ".", "createElement", "(", "tag", ")", ";", "if", "(", "textContent", ")", "{", "d", ".", "textContent", "=", "textContent", ";", "}", "return", "d", ";", "}" ]
Shorter way to create element and optionally set textContent.
[ "Shorter", "way", "to", "create", "element", "and", "optionally", "set", "textContent", "." ]
0761d2e31298c59e234c05e3ac74038ced572985
https://github.com/nzamani/ui5-nabi-m/blob/0761d2e31298c59e234c05e3ac74038ced572985/src/nabi/m/thirdparty/pdfjs/web/debugger.js#L253-L259
train
nodeca/charlatan
lib/charlatan.js
repeatRange
function repeatRange(_unused, what, from, to) { return new Array(Helpers.rand(Number(to) + 1, Number(from)) + 1).join(what); }
javascript
function repeatRange(_unused, what, from, to) { return new Array(Helpers.rand(Number(to) + 1, Number(from)) + 1).join(what); }
[ "function", "repeatRange", "(", "_unused", ",", "what", ",", "from", ",", "to", ")", "{", "return", "new", "Array", "(", "Helpers", ".", "rand", "(", "Number", "(", "to", ")", "+", "1", ",", "Number", "(", "from", ")", ")", "+", "1", ")", ".", "join", "(", "what", ")", ";", "}" ]
"baz", 2, 3 -> "bazbaz" or "bazbazbaz"
[ "baz", "2", "3", "-", ">", "bazbaz", "or", "bazbazbaz" ]
d458e093763ed9dc032c79b404e79ad683e8f248
https://github.com/nodeca/charlatan/blob/d458e093763ed9dc032c79b404e79ad683e8f248/lib/charlatan.js#L273-L275
train
Rovak/node-wallet-api
src/utils/crypto.js
getRowBytesFromTransactionBase64
function getRowBytesFromTransactionBase64(base64Data) { let bytesDecode = base64DecodeFromString(base64Data); let transaction = proto.protocol.Transaction.deserializeBinary(bytesDecode); let raw = transaction.getRawData(); return raw.serializeBinary(); }
javascript
function getRowBytesFromTransactionBase64(base64Data) { let bytesDecode = base64DecodeFromString(base64Data); let transaction = proto.protocol.Transaction.deserializeBinary(bytesDecode); let raw = transaction.getRawData(); return raw.serializeBinary(); }
[ "function", "getRowBytesFromTransactionBase64", "(", "base64Data", ")", "{", "let", "bytesDecode", "=", "base64DecodeFromString", "(", "base64Data", ")", ";", "let", "transaction", "=", "proto", ".", "protocol", ".", "Transaction", ".", "deserializeBinary", "(", "bytesDecode", ")", ";", "let", "raw", "=", "transaction", ".", "getRawData", "(", ")", ";", "return", "raw", ".", "serializeBinary", "(", ")", ";", "}" ]
return bytes of rowdata, use to sign.
[ "return", "bytes", "of", "rowdata", "use", "to", "sign", "." ]
5084fe318bb8cecaea35bf73383968ae9bc33094
https://github.com/Rovak/node-wallet-api/blob/5084fe318bb8cecaea35bf73383968ae9bc33094/src/utils/crypto.js#L40-L45
train
Rovak/node-wallet-api
src/utils/crypto.js
genPriKey
function genPriKey() { let ec = new EC('secp256k1'); let key = ec.genKeyPair(); let priKey = key.getPrivate(); let priKeyHex = priKey.toString('hex'); while (priKeyHex.length < 64) { priKeyHex = "0" + priKeyHex; } return hexStr2byteArray(priKeyHex); }
javascript
function genPriKey() { let ec = new EC('secp256k1'); let key = ec.genKeyPair(); let priKey = key.getPrivate(); let priKeyHex = priKey.toString('hex'); while (priKeyHex.length < 64) { priKeyHex = "0" + priKeyHex; } return hexStr2byteArray(priKeyHex); }
[ "function", "genPriKey", "(", ")", "{", "let", "ec", "=", "new", "EC", "(", "'secp256k1'", ")", ";", "let", "key", "=", "ec", ".", "genKeyPair", "(", ")", ";", "let", "priKey", "=", "key", ".", "getPrivate", "(", ")", ";", "let", "priKeyHex", "=", "priKey", ".", "toString", "(", "'hex'", ")", ";", "while", "(", "priKeyHex", ".", "length", "<", "64", ")", "{", "priKeyHex", "=", "\"0\"", "+", "priKeyHex", ";", "}", "return", "hexStr2byteArray", "(", "priKeyHex", ")", ";", "}" ]
gen Ecc priKey for bytes
[ "gen", "Ecc", "priKey", "for", "bytes" ]
5084fe318bb8cecaea35bf73383968ae9bc33094
https://github.com/Rovak/node-wallet-api/blob/5084fe318bb8cecaea35bf73383968ae9bc33094/src/utils/crypto.js#L48-L58
train
Rovak/node-wallet-api
src/utils/crypto.js
getBase58CheckAddress
function getBase58CheckAddress(addressBytes) { var hash0 = SHA256(addressBytes); var hash1 = SHA256(hash0); var checkSum = hash1.slice(0, 4); checkSum = addressBytes.concat(checkSum); var base58Check = encode58(checkSum); return base58Check; }
javascript
function getBase58CheckAddress(addressBytes) { var hash0 = SHA256(addressBytes); var hash1 = SHA256(hash0); var checkSum = hash1.slice(0, 4); checkSum = addressBytes.concat(checkSum); var base58Check = encode58(checkSum); return base58Check; }
[ "function", "getBase58CheckAddress", "(", "addressBytes", ")", "{", "var", "hash0", "=", "SHA256", "(", "addressBytes", ")", ";", "var", "hash1", "=", "SHA256", "(", "hash0", ")", ";", "var", "checkSum", "=", "hash1", ".", "slice", "(", "0", ",", "4", ")", ";", "checkSum", "=", "addressBytes", ".", "concat", "(", "checkSum", ")", ";", "var", "base58Check", "=", "encode58", "(", "checkSum", ")", ";", "return", "base58Check", ";", "}" ]
return address by Base58Check String,
[ "return", "address", "by", "Base58Check", "String" ]
5084fe318bb8cecaea35bf73383968ae9bc33094
https://github.com/Rovak/node-wallet-api/blob/5084fe318bb8cecaea35bf73383968ae9bc33094/src/utils/crypto.js#L81-L89
train
Rovak/node-wallet-api
src/utils/crypto.js
getBase58CheckAddressFromPriKeyBase64String
function getBase58CheckAddressFromPriKeyBase64String(priKeyBase64String) { var priKeyBytes = base64DecodeFromString(priKeyBase64String); var pubBytes = getPubKeyFromPriKey(priKeyBytes); var addressBytes = computeAddress(pubBytes); return getBase58CheckAddress(addressBytes); }
javascript
function getBase58CheckAddressFromPriKeyBase64String(priKeyBase64String) { var priKeyBytes = base64DecodeFromString(priKeyBase64String); var pubBytes = getPubKeyFromPriKey(priKeyBytes); var addressBytes = computeAddress(pubBytes); return getBase58CheckAddress(addressBytes); }
[ "function", "getBase58CheckAddressFromPriKeyBase64String", "(", "priKeyBase64String", ")", "{", "var", "priKeyBytes", "=", "base64DecodeFromString", "(", "priKeyBase64String", ")", ";", "var", "pubBytes", "=", "getPubKeyFromPriKey", "(", "priKeyBytes", ")", ";", "var", "addressBytes", "=", "computeAddress", "(", "pubBytes", ")", ";", "return", "getBase58CheckAddress", "(", "addressBytes", ")", ";", "}" ]
return address by Base58Check String, priKeyBytes is base64String
[ "return", "address", "by", "Base58Check", "String", "priKeyBytes", "is", "base64String" ]
5084fe318bb8cecaea35bf73383968ae9bc33094
https://github.com/Rovak/node-wallet-api/blob/5084fe318bb8cecaea35bf73383968ae9bc33094/src/utils/crypto.js#L142-L147
train
Rovak/node-wallet-api
src/utils/crypto.js
ECKeySign
function ECKeySign(hashBytes, priKeyBytes) { let ec = new EC('secp256k1'); let key = ec.keyFromPrivate(priKeyBytes, 'bytes'); let signature = key.sign(hashBytes); let r = signature.r; let s = signature.s; let id = signature.recoveryParam; let rHex = r.toString('hex'); while (rHex.length < 64) { rHex = "0" + rHex; } let sHex = s.toString('hex'); while (sHex.length < 64) { sHex = "0" + sHex; } let idHex = byte2hexStr(id); let signHex = rHex + sHex + idHex; return hexStr2byteArray(signHex); }
javascript
function ECKeySign(hashBytes, priKeyBytes) { let ec = new EC('secp256k1'); let key = ec.keyFromPrivate(priKeyBytes, 'bytes'); let signature = key.sign(hashBytes); let r = signature.r; let s = signature.s; let id = signature.recoveryParam; let rHex = r.toString('hex'); while (rHex.length < 64) { rHex = "0" + rHex; } let sHex = s.toString('hex'); while (sHex.length < 64) { sHex = "0" + sHex; } let idHex = byte2hexStr(id); let signHex = rHex + sHex + idHex; return hexStr2byteArray(signHex); }
[ "function", "ECKeySign", "(", "hashBytes", ",", "priKeyBytes", ")", "{", "let", "ec", "=", "new", "EC", "(", "'secp256k1'", ")", ";", "let", "key", "=", "ec", ".", "keyFromPrivate", "(", "priKeyBytes", ",", "'bytes'", ")", ";", "let", "signature", "=", "key", ".", "sign", "(", "hashBytes", ")", ";", "let", "r", "=", "signature", ".", "r", ";", "let", "s", "=", "signature", ".", "s", ";", "let", "id", "=", "signature", ".", "recoveryParam", ";", "let", "rHex", "=", "r", ".", "toString", "(", "'hex'", ")", ";", "while", "(", "rHex", ".", "length", "<", "64", ")", "{", "rHex", "=", "\"0\"", "+", "rHex", ";", "}", "let", "sHex", "=", "s", ".", "toString", "(", "'hex'", ")", ";", "while", "(", "sHex", ".", "length", "<", "64", ")", "{", "sHex", "=", "\"0\"", "+", "sHex", ";", "}", "let", "idHex", "=", "byte2hexStr", "(", "id", ")", ";", "let", "signHex", "=", "rHex", "+", "sHex", "+", "idHex", ";", "return", "hexStr2byteArray", "(", "signHex", ")", ";", "}" ]
return sign by 65 bytes r s id. id < 27
[ "return", "sign", "by", "65", "bytes", "r", "s", "id", ".", "id", "<", "27" ]
5084fe318bb8cecaea35bf73383968ae9bc33094
https://github.com/Rovak/node-wallet-api/blob/5084fe318bb8cecaea35bf73383968ae9bc33094/src/utils/crypto.js#L187-L205
train
Rovak/node-wallet-api
src/utils/crypto.js
SHA256
function SHA256(msgBytes) { let shaObj = new jsSHA("SHA-256", "HEX"); let msgHex = byteArray2hexStr(msgBytes); shaObj.update(msgHex); let hashHex = shaObj.getHash("HEX"); return hexStr2byteArray(hashHex); }
javascript
function SHA256(msgBytes) { let shaObj = new jsSHA("SHA-256", "HEX"); let msgHex = byteArray2hexStr(msgBytes); shaObj.update(msgHex); let hashHex = shaObj.getHash("HEX"); return hexStr2byteArray(hashHex); }
[ "function", "SHA256", "(", "msgBytes", ")", "{", "let", "shaObj", "=", "new", "jsSHA", "(", "\"SHA-256\"", ",", "\"HEX\"", ")", ";", "let", "msgHex", "=", "byteArray2hexStr", "(", "msgBytes", ")", ";", "shaObj", ".", "update", "(", "msgHex", ")", ";", "let", "hashHex", "=", "shaObj", ".", "getHash", "(", "\"HEX\"", ")", ";", "return", "hexStr2byteArray", "(", "hashHex", ")", ";", "}" ]
return 32 bytes
[ "return", "32", "bytes" ]
5084fe318bb8cecaea35bf73383968ae9bc33094
https://github.com/Rovak/node-wallet-api/blob/5084fe318bb8cecaea35bf73383968ae9bc33094/src/utils/crypto.js#L209-L215
train
cgjs/cgjs
packages/cgjs/cgjs/require.js
register
function register(module, value) { if (module in CORE_MODULES && DEBUG) { print(`\u26A0\uFE0F ${module} already registered`); } CORE_MODULES[module] = value; }
javascript
function register(module, value) { if (module in CORE_MODULES && DEBUG) { print(`\u26A0\uFE0F ${module} already registered`); } CORE_MODULES[module] = value; }
[ "function", "register", "(", "module", ",", "value", ")", "{", "if", "(", "module", "in", "CORE_MODULES", "&&", "DEBUG", ")", "{", "print", "(", "`", "\\u26A0", "\\uFE0F", "${", "module", "}", "`", ")", ";", "}", "CORE_MODULES", "[", "module", "]", "=", "value", ";", "}" ]
exposed through require but used to enrich the default CommonJS modules environment
[ "exposed", "through", "require", "but", "used", "to", "enrich", "the", "default", "CommonJS", "modules", "environment" ]
bd2a45dab4ef97affced7ab8f9dbc5dcf7a005db
https://github.com/cgjs/cgjs/blob/bd2a45dab4ef97affced7ab8f9dbc5dcf7a005db/packages/cgjs/cgjs/require.js#L87-L92
train
ourcodeworld/internet-available
internet-available.js
internetAvailable
function internetAvailable(settings) { // Require dns-socket module from dependencies var dns = require('dns-socket'); settings = settings || {}; return new Promise(function(resolve, reject){ // Create instance of the DNS resolver var socket = dns({ timeout: (settings.timeout || 5000), retries: (settings.retries || 5) }); // Run the dns lowlevel lookup socket.query({ questions: [{ type: 'A', name: (settings.domainName || "google.com") }] }, (settings.port || 53), (settings.host || '8.8.8.8')); // DNS Address solved, internet available socket.on('response', () => { socket.destroy(() => { resolve(); }); }); // Verify for timeout of the request (cannot reach server) socket.on('timeout', () => { socket.destroy(() => { reject(); }); }); }); }
javascript
function internetAvailable(settings) { // Require dns-socket module from dependencies var dns = require('dns-socket'); settings = settings || {}; return new Promise(function(resolve, reject){ // Create instance of the DNS resolver var socket = dns({ timeout: (settings.timeout || 5000), retries: (settings.retries || 5) }); // Run the dns lowlevel lookup socket.query({ questions: [{ type: 'A', name: (settings.domainName || "google.com") }] }, (settings.port || 53), (settings.host || '8.8.8.8')); // DNS Address solved, internet available socket.on('response', () => { socket.destroy(() => { resolve(); }); }); // Verify for timeout of the request (cannot reach server) socket.on('timeout', () => { socket.destroy(() => { reject(); }); }); }); }
[ "function", "internetAvailable", "(", "settings", ")", "{", "var", "dns", "=", "require", "(", "'dns-socket'", ")", ";", "settings", "=", "settings", "||", "{", "}", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "var", "socket", "=", "dns", "(", "{", "timeout", ":", "(", "settings", ".", "timeout", "||", "5000", ")", ",", "retries", ":", "(", "settings", ".", "retries", "||", "5", ")", "}", ")", ";", "socket", ".", "query", "(", "{", "questions", ":", "[", "{", "type", ":", "'A'", ",", "name", ":", "(", "settings", ".", "domainName", "||", "\"google.com\"", ")", "}", "]", "}", ",", "(", "settings", ".", "port", "||", "53", ")", ",", "(", "settings", ".", "host", "||", "'8.8.8.8'", ")", ")", ";", "socket", ".", "on", "(", "'response'", ",", "(", ")", "=>", "{", "socket", ".", "destroy", "(", "(", ")", "=>", "{", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "socket", ".", "on", "(", "'timeout'", ",", "(", ")", "=>", "{", "socket", ".", "destroy", "(", "(", ")", "=>", "{", "reject", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Internet available is a very simple method that allows you to check if there's an active internet connection by resolving a DNS address and it's developer friendly. @param {Settings.timeout} timeout Execution time in milliseconds @param {Settings.retries} retries Total query attempts made during timeout @param {Settings.domainName} name Domain to check for connection by default google.com @param {Settings.port} port Port where the DNS lookup should check by default 53 @param {Settings.host} host DNS Host where lookup should check by default '8.8.8.8' (Google Public DNS) @return {Promise}
[ "Internet", "available", "is", "a", "very", "simple", "method", "that", "allows", "you", "to", "check", "if", "there", "s", "an", "active", "internet", "connection", "by", "resolving", "a", "DNS", "address", "and", "it", "s", "developer", "friendly", "." ]
b037c68f7e4b8d5664fd7a22ba0675dd01e420c4
https://github.com/ourcodeworld/internet-available/blob/b037c68f7e4b8d5664fd7a22ba0675dd01e420c4/internet-available.js#L12-L46
train
iconic/grunt-svg-toolkit
tasks/lib/process-svg.js
ingestSVG
function ingestSVG(cb) { // :NOTE: xmlMode is important to not lowercase SVG tags // and attributes, like viewBox and clipPath var $ = cheerio.load(data.svg, { xmlMode: true }); cb(null, $, data); }
javascript
function ingestSVG(cb) { // :NOTE: xmlMode is important to not lowercase SVG tags // and attributes, like viewBox and clipPath var $ = cheerio.load(data.svg, { xmlMode: true }); cb(null, $, data); }
[ "function", "ingestSVG", "(", "cb", ")", "{", "var", "$", "=", "cheerio", ".", "load", "(", "data", ".", "svg", ",", "{", "xmlMode", ":", "true", "}", ")", ";", "cb", "(", "null", ",", "$", ",", "data", ")", ";", "}" ]
Parse the SVG into a cheerio object
[ "Parse", "the", "SVG", "into", "a", "cheerio", "object" ]
6d3b6c820e5a400e856264708c5d32571f35f486
https://github.com/iconic/grunt-svg-toolkit/blob/6d3b6c820e5a400e856264708c5d32571f35f486/tasks/lib/process-svg.js#L18-L26
train
iconic/grunt-svg-toolkit
tasks/lib/colorize-svg.js
svgcolor
function svgcolor(el, color) { var styles = window.getComputedStyle(el, null); var fill = styles['fill']; var stroke = styles['stroke']; var isFill, isStroke; if (!fill && !stroke) { isFill = true; } else { if (fill && fill !== 'none') { isFill = true; } if (stroke && stroke !== 'none') { isStroke = true; } } if (isStroke) { el.style.stroke = null; el.setAttribute('stroke', color || stroke); } if (isFill) { el.style.fill = null; el.setAttribute('fill', color || fill); } }
javascript
function svgcolor(el, color) { var styles = window.getComputedStyle(el, null); var fill = styles['fill']; var stroke = styles['stroke']; var isFill, isStroke; if (!fill && !stroke) { isFill = true; } else { if (fill && fill !== 'none') { isFill = true; } if (stroke && stroke !== 'none') { isStroke = true; } } if (isStroke) { el.style.stroke = null; el.setAttribute('stroke', color || stroke); } if (isFill) { el.style.fill = null; el.setAttribute('fill', color || fill); } }
[ "function", "svgcolor", "(", "el", ",", "color", ")", "{", "var", "styles", "=", "window", ".", "getComputedStyle", "(", "el", ",", "null", ")", ";", "var", "fill", "=", "styles", "[", "'fill'", "]", ";", "var", "stroke", "=", "styles", "[", "'stroke'", "]", ";", "var", "isFill", ",", "isStroke", ";", "if", "(", "!", "fill", "&&", "!", "stroke", ")", "{", "isFill", "=", "true", ";", "}", "else", "{", "if", "(", "fill", "&&", "fill", "!==", "'none'", ")", "{", "isFill", "=", "true", ";", "}", "if", "(", "stroke", "&&", "stroke", "!==", "'none'", ")", "{", "isStroke", "=", "true", ";", "}", "}", "if", "(", "isStroke", ")", "{", "el", ".", "style", ".", "stroke", "=", "null", ";", "el", ".", "setAttribute", "(", "'stroke'", ",", "color", "||", "stroke", ")", ";", "}", "if", "(", "isFill", ")", "{", "el", ".", "style", ".", "fill", "=", "null", ";", "el", ".", "setAttribute", "(", "'fill'", ",", "color", "||", "fill", ")", ";", "}", "}" ]
Given an element, color it by inlining a fill or stroke attribute. If color isn't define, it will use the current computed style for use when applying styles via CSS
[ "Given", "an", "element", "color", "it", "by", "inlining", "a", "fill", "or", "stroke", "attribute", ".", "If", "color", "isn", "t", "define", "it", "will", "use", "the", "current", "computed", "style", "for", "use", "when", "applying", "styles", "via", "CSS" ]
6d3b6c820e5a400e856264708c5d32571f35f486
https://github.com/iconic/grunt-svg-toolkit/blob/6d3b6c820e5a400e856264708c5d32571f35f486/tasks/lib/colorize-svg.js#L42-L71
train
cssinjs/jss-default-unit
src/index.js
addCamelCasedVersion
function addCamelCasedVersion(obj) { const regExp = /(-[a-z])/g const replace = str => str[1].toUpperCase() const newObj = {} for (const key in obj) { newObj[key] = obj[key] newObj[key.replace(regExp, replace)] = obj[key] } return newObj }
javascript
function addCamelCasedVersion(obj) { const regExp = /(-[a-z])/g const replace = str => str[1].toUpperCase() const newObj = {} for (const key in obj) { newObj[key] = obj[key] newObj[key.replace(regExp, replace)] = obj[key] } return newObj }
[ "function", "addCamelCasedVersion", "(", "obj", ")", "{", "const", "regExp", "=", "/", "(-[a-z])", "/", "g", "const", "replace", "=", "str", "=>", "str", "[", "1", "]", ".", "toUpperCase", "(", ")", "const", "newObj", "=", "{", "}", "for", "(", "const", "key", "in", "obj", ")", "{", "newObj", "[", "key", "]", "=", "obj", "[", "key", "]", "newObj", "[", "key", ".", "replace", "(", "regExp", ",", "replace", ")", "]", "=", "obj", "[", "key", "]", "}", "return", "newObj", "}" ]
Clones the object and adds a camel cased property version.
[ "Clones", "the", "object", "and", "adds", "a", "camel", "cased", "property", "version", "." ]
ab30fa08a3b037ddaa0b0bd6bd257cee7f6b46f7
https://github.com/cssinjs/jss-default-unit/blob/ab30fa08a3b037ddaa0b0bd6bd257cee7f6b46f7/src/index.js#L6-L15
train
cssinjs/jss-default-unit
src/index.js
iterate
function iterate(prop, value, options) { if (!value) return value let convertedValue = value let type = typeof value if (type === 'object' && Array.isArray(value)) type = 'array' switch (type) { case 'object': if (prop === 'fallbacks') { for (const innerProp in value) { value[innerProp] = iterate(innerProp, value[innerProp], options) } break } for (const innerProp in value) { value[innerProp] = iterate(`${prop}-${innerProp}`, value[innerProp], options) } break case 'array': for (let i = 0; i < value.length; i++) { value[i] = iterate(prop, value[i], options) } break case 'number': if (value !== 0) { convertedValue = value + (options[prop] || units[prop] || '') } break default: break } return convertedValue }
javascript
function iterate(prop, value, options) { if (!value) return value let convertedValue = value let type = typeof value if (type === 'object' && Array.isArray(value)) type = 'array' switch (type) { case 'object': if (prop === 'fallbacks') { for (const innerProp in value) { value[innerProp] = iterate(innerProp, value[innerProp], options) } break } for (const innerProp in value) { value[innerProp] = iterate(`${prop}-${innerProp}`, value[innerProp], options) } break case 'array': for (let i = 0; i < value.length; i++) { value[i] = iterate(prop, value[i], options) } break case 'number': if (value !== 0) { convertedValue = value + (options[prop] || units[prop] || '') } break default: break } return convertedValue }
[ "function", "iterate", "(", "prop", ",", "value", ",", "options", ")", "{", "if", "(", "!", "value", ")", "return", "value", "let", "convertedValue", "=", "value", "let", "type", "=", "typeof", "value", "if", "(", "type", "===", "'object'", "&&", "Array", ".", "isArray", "(", "value", ")", ")", "type", "=", "'array'", "switch", "(", "type", ")", "{", "case", "'object'", ":", "if", "(", "prop", "===", "'fallbacks'", ")", "{", "for", "(", "const", "innerProp", "in", "value", ")", "{", "value", "[", "innerProp", "]", "=", "iterate", "(", "innerProp", ",", "value", "[", "innerProp", "]", ",", "options", ")", "}", "break", "}", "for", "(", "const", "innerProp", "in", "value", ")", "{", "value", "[", "innerProp", "]", "=", "iterate", "(", "`", "${", "prop", "}", "${", "innerProp", "}", "`", ",", "value", "[", "innerProp", "]", ",", "options", ")", "}", "break", "case", "'array'", ":", "for", "(", "let", "i", "=", "0", ";", "i", "<", "value", ".", "length", ";", "i", "++", ")", "{", "value", "[", "i", "]", "=", "iterate", "(", "prop", ",", "value", "[", "i", "]", ",", "options", ")", "}", "break", "case", "'number'", ":", "if", "(", "value", "!==", "0", ")", "{", "convertedValue", "=", "value", "+", "(", "options", "[", "prop", "]", "||", "units", "[", "prop", "]", "||", "''", ")", "}", "break", "default", ":", "break", "}", "return", "convertedValue", "}" ]
Recursive deep style passing function @param {String} current property @param {(Object|Array|Number|String)} property value @param {Object} options @return {(Object|Array|Number|String)} resulting value
[ "Recursive", "deep", "style", "passing", "function" ]
ab30fa08a3b037ddaa0b0bd6bd257cee7f6b46f7
https://github.com/cssinjs/jss-default-unit/blob/ab30fa08a3b037ddaa0b0bd6bd257cee7f6b46f7/src/index.js#L27-L62
train
kaazing/http2.js
lib/protocol/flow.js
Flow
function Flow(flowControlId) { Duplex.call(this, { objectMode: true }); this._window = this._initialWindow = INITIAL_WINDOW_SIZE; this._flowControlId = flowControlId; this._queue = []; this._ended = false; this._received = 0; this._blocked = false; }
javascript
function Flow(flowControlId) { Duplex.call(this, { objectMode: true }); this._window = this._initialWindow = INITIAL_WINDOW_SIZE; this._flowControlId = flowControlId; this._queue = []; this._ended = false; this._received = 0; this._blocked = false; }
[ "function", "Flow", "(", "flowControlId", ")", "{", "Duplex", ".", "call", "(", "this", ",", "{", "objectMode", ":", "true", "}", ")", ";", "this", ".", "_window", "=", "this", ".", "_initialWindow", "=", "INITIAL_WINDOW_SIZE", ";", "this", ".", "_flowControlId", "=", "flowControlId", ";", "this", ".", "_queue", "=", "[", "]", ";", "this", ".", "_ended", "=", "false", ";", "this", ".", "_received", "=", "0", ";", "this", ".", "_blocked", "=", "false", ";", "}" ]
`flowControlId` is needed if only specific WINDOW_UPDATEs should be watched.
[ "flowControlId", "is", "needed", "if", "only", "specific", "WINDOW_UPDATEs", "should", "be", "watched", "." ]
ffc7a2b9a38cd5b0e68d98792264b3587a325088
https://github.com/kaazing/http2.js/blob/ffc7a2b9a38cd5b0e68d98792264b3587a325088/lib/protocol/flow.js#L61-L70
train
GitbookIO/plugin-sharing
index.js
function(cfg) { var sharingLink = _.get(cfg, 'links.sharing', {}); cfg.pluginsConfig.sharing = _.defaults(cfg.pluginsConfig.sharing || {}, {}); _.each(sharingLink, function(enabled, type) { if (enabled != false) return; if (type == 'all') cfg.pluginsConfig.sharing[type] = []; else cfg.pluginsConfig.sharing[type] = false; }); return cfg; }
javascript
function(cfg) { var sharingLink = _.get(cfg, 'links.sharing', {}); cfg.pluginsConfig.sharing = _.defaults(cfg.pluginsConfig.sharing || {}, {}); _.each(sharingLink, function(enabled, type) { if (enabled != false) return; if (type == 'all') cfg.pluginsConfig.sharing[type] = []; else cfg.pluginsConfig.sharing[type] = false; }); return cfg; }
[ "function", "(", "cfg", ")", "{", "var", "sharingLink", "=", "_", ".", "get", "(", "cfg", ",", "'links.sharing'", ",", "{", "}", ")", ";", "cfg", ".", "pluginsConfig", ".", "sharing", "=", "_", ".", "defaults", "(", "cfg", ".", "pluginsConfig", ".", "sharing", "||", "{", "}", ",", "{", "}", ")", ";", "_", ".", "each", "(", "sharingLink", ",", "function", "(", "enabled", ",", "type", ")", "{", "if", "(", "enabled", "!=", "false", ")", "return", ";", "if", "(", "type", "==", "'all'", ")", "cfg", ".", "pluginsConfig", ".", "sharing", "[", "type", "]", "=", "[", "]", ";", "else", "cfg", ".", "pluginsConfig", ".", "sharing", "[", "type", "]", "=", "false", ";", "}", ")", ";", "return", "cfg", ";", "}" ]
Compatibility layer for gitbook < 2.5.0
[ "Compatibility", "layer", "for", "gitbook", "<", "2", ".", "5", ".", "0" ]
728a267fc9e8f3be0c076150a8b6bbdf2bcab4de
https://github.com/GitbookIO/plugin-sharing/blob/728a267fc9e8f3be0c076150a8b6bbdf2bcab4de/index.js#L12-L24
train
klayveR/poe-log-monitor
index.js
readLogStream
async function readLogStream(file, instance) { return new Promise(resolve => { var stream = fs.createReadStream(file, { encoding: 'utf8', highWaterMark: instance.chunkSize }); var hasStarted = false; // Split data into chunks so we dont stall the client stream.on('data', chunk => { if (!hasStarted) instance.emit("parsingStarted"); hasStarted = true; var lines = chunk.toString().split("\n"); // Pause stream until this chunk is completed to avoid spamming the thread stream.pause(); async.each(lines, function (line, callback) { instance.registerMatch(line); callback(); }, function (err) { setTimeout(() => { stream.resume(); }, instance.chunkInterval); }); }); stream.on('end', () => { instance.emit("parsingComplete"); resolve(); stream.close(); }); }); }
javascript
async function readLogStream(file, instance) { return new Promise(resolve => { var stream = fs.createReadStream(file, { encoding: 'utf8', highWaterMark: instance.chunkSize }); var hasStarted = false; // Split data into chunks so we dont stall the client stream.on('data', chunk => { if (!hasStarted) instance.emit("parsingStarted"); hasStarted = true; var lines = chunk.toString().split("\n"); // Pause stream until this chunk is completed to avoid spamming the thread stream.pause(); async.each(lines, function (line, callback) { instance.registerMatch(line); callback(); }, function (err) { setTimeout(() => { stream.resume(); }, instance.chunkInterval); }); }); stream.on('end', () => { instance.emit("parsingComplete"); resolve(); stream.close(); }); }); }
[ "async", "function", "readLogStream", "(", "file", ",", "instance", ")", "{", "return", "new", "Promise", "(", "resolve", "=>", "{", "var", "stream", "=", "fs", ".", "createReadStream", "(", "file", ",", "{", "encoding", ":", "'utf8'", ",", "highWaterMark", ":", "instance", ".", "chunkSize", "}", ")", ";", "var", "hasStarted", "=", "false", ";", "stream", ".", "on", "(", "'data'", ",", "chunk", "=>", "{", "if", "(", "!", "hasStarted", ")", "instance", ".", "emit", "(", "\"parsingStarted\"", ")", ";", "hasStarted", "=", "true", ";", "var", "lines", "=", "chunk", ".", "toString", "(", ")", ".", "split", "(", "\"\\n\"", ")", ";", "\\n", "stream", ".", "pause", "(", ")", ";", "}", ")", ";", "async", ".", "each", "(", "lines", ",", "function", "(", "line", ",", "callback", ")", "{", "instance", ".", "registerMatch", "(", "line", ")", ";", "callback", "(", ")", ";", "}", ",", "function", "(", "err", ")", "{", "setTimeout", "(", "(", ")", "=>", "{", "stream", ".", "resume", "(", ")", ";", "}", ",", "instance", ".", "chunkInterval", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Reads the file and emits events for each included event
[ "Reads", "the", "file", "and", "emits", "events", "for", "each", "included", "event" ]
ba668a275ea653cdb777325fb1d8b1c5610b348a
https://github.com/klayveR/poe-log-monitor/blob/ba668a275ea653cdb777325fb1d8b1c5610b348a/index.js#L71-L97
train
imrvelj/moment-random
src/index.js
momentRandom
function momentRandom(end = moment(), start) { const endTime = +moment(end); const randomNumber = (to, from = 0) => Math.floor(Math.random() * (to - from) + from); if (start) { const startTime = +moment(start); if (startTime > endTime) { throw new Error('End date is before start date!'); } return moment(randomNumber(endTime, startTime)); } return moment(randomNumber(endTime)); }
javascript
function momentRandom(end = moment(), start) { const endTime = +moment(end); const randomNumber = (to, from = 0) => Math.floor(Math.random() * (to - from) + from); if (start) { const startTime = +moment(start); if (startTime > endTime) { throw new Error('End date is before start date!'); } return moment(randomNumber(endTime, startTime)); } return moment(randomNumber(endTime)); }
[ "function", "momentRandom", "(", "end", "=", "moment", "(", ")", ",", "start", ")", "{", "const", "endTime", "=", "+", "moment", "(", "end", ")", ";", "const", "randomNumber", "=", "(", "to", ",", "from", "=", "0", ")", "=>", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "(", "to", "-", "from", ")", "+", "from", ")", ";", "if", "(", "start", ")", "{", "const", "startTime", "=", "+", "moment", "(", "start", ")", ";", "if", "(", "startTime", ">", "endTime", ")", "{", "throw", "new", "Error", "(", "'End date is before start date!'", ")", ";", "}", "return", "moment", "(", "randomNumber", "(", "endTime", ",", "startTime", ")", ")", ";", "}", "return", "moment", "(", "randomNumber", "(", "endTime", ")", ")", ";", "}" ]
Generates a random moment.js object @param {any} end - END date [Anything a moment constructor accepts] @param {any} start - START date [Anything a moment constructor accepts] @returns
[ "Generates", "a", "random", "moment", ".", "js", "object" ]
5945140e303a5964ce24846ecd58a48e1fccd451
https://github.com/imrvelj/moment-random/blob/5945140e303a5964ce24846ecd58a48e1fccd451/src/index.js#L10-L23
train
openchain/openchain-js
lib/apiclient.js
ApiClient
function ApiClient(endpoint) { if (endpoint.length > 0 && endpoint.slice(-1) != "/") { endpoint += "/"; } this.endpoint = endpoint; this.namespace = null; }
javascript
function ApiClient(endpoint) { if (endpoint.length > 0 && endpoint.slice(-1) != "/") { endpoint += "/"; } this.endpoint = endpoint; this.namespace = null; }
[ "function", "ApiClient", "(", "endpoint", ")", "{", "if", "(", "endpoint", ".", "length", ">", "0", "&&", "endpoint", ".", "slice", "(", "-", "1", ")", "!=", "\"/\"", ")", "{", "endpoint", "+=", "\"/\"", ";", "}", "this", ".", "endpoint", "=", "endpoint", ";", "this", ".", "namespace", "=", "null", ";", "}" ]
Represents an Openchain client bound to a specific Openchain endpoint. @constructor @param {string} endpoint The base URL of the endpoint.
[ "Represents", "an", "Openchain", "client", "bound", "to", "a", "specific", "Openchain", "endpoint", "." ]
41ae72504a29ba3067236f489e5117a4bda8d9d6
https://github.com/openchain/openchain-js/blob/41ae72504a29ba3067236f489e5117a4bda8d9d6/lib/apiclient.js#L31-L38
train
jesseskinner/hover
src/util/react/mixin.js
SubscribeMixin
function SubscribeMixin(subscribe, key) { var unsubscribe; return { componentDidMount: function () { // this should never happen if (unsubscribe) { throw new Error('Cannot reuse a mixin.'); } unsubscribe = subscribe(function (data) { // by default, use the store's state as the component's state var state = data; // but if a key is provided, map the data to that key if (key) { state = {}; state[key] = data; } // update the component's state this.setState(state); }.bind(this)); }, componentWillUnmount: function () { // call the unsubscribe function returned from store.getState above if (unsubscribe) { unsubscribe(); // wipe the unsubscribe, so the mixin can be used again maybe unsubscribe = null; } } }; }
javascript
function SubscribeMixin(subscribe, key) { var unsubscribe; return { componentDidMount: function () { // this should never happen if (unsubscribe) { throw new Error('Cannot reuse a mixin.'); } unsubscribe = subscribe(function (data) { // by default, use the store's state as the component's state var state = data; // but if a key is provided, map the data to that key if (key) { state = {}; state[key] = data; } // update the component's state this.setState(state); }.bind(this)); }, componentWillUnmount: function () { // call the unsubscribe function returned from store.getState above if (unsubscribe) { unsubscribe(); // wipe the unsubscribe, so the mixin can be used again maybe unsubscribe = null; } } }; }
[ "function", "SubscribeMixin", "(", "subscribe", ",", "key", ")", "{", "var", "unsubscribe", ";", "return", "{", "componentDidMount", ":", "function", "(", ")", "{", "if", "(", "unsubscribe", ")", "{", "throw", "new", "Error", "(", "'Cannot reuse a mixin.'", ")", ";", "}", "unsubscribe", "=", "subscribe", "(", "function", "(", "data", ")", "{", "var", "state", "=", "data", ";", "if", "(", "key", ")", "{", "state", "=", "{", "}", ";", "state", "[", "key", "]", "=", "data", ";", "}", "this", ".", "setState", "(", "state", ")", ";", "}", ".", "bind", "(", "this", ")", ")", ";", "}", ",", "componentWillUnmount", ":", "function", "(", ")", "{", "if", "(", "unsubscribe", ")", "{", "unsubscribe", "(", ")", ";", "unsubscribe", "=", "null", ";", "}", "}", "}", ";", "}" ]
React mixin, for easily subscribing and unsubscribing to a Hover store Usage: var SubscribeMixin = require('hover/src/util/mixin'); React.createClass({ mixins: [ this will map the state of myStore to this.state.store SubscribeMixin(myStore, 'store') ], render: function () { use this.state.store } }); NOTE: Do not reuse a mixin, each mixin should be only used once.
[ "React", "mixin", "for", "easily", "subscribing", "and", "unsubscribing", "to", "a", "Hover", "store" ]
b2f024eb73f9f3a32a47856321f553c3dec61afb
https://github.com/jesseskinner/hover/blob/b2f024eb73f9f3a32a47856321f553c3dec61afb/src/util/react/mixin.js#L21-L56
train
jaredhanson/junction
lib/junction/application.js
prepareRes
function prepareRes(stanza) { var res = null; if (stanza.is('iq') && (stanza.attr('type') == 'get' || stanza.attr('type') == 'set')) { // TODO: When connected as a component, the from field needs to be set // eplicitly (from = stanza.attrs.to). res = new xmpp.Stanza('iq', { id: stanza.attr('id'), to: stanza.attr('from'), type: 'result' }) } // TODO: Prepare presence and message stanzas (which are optional to send) return res; }
javascript
function prepareRes(stanza) { var res = null; if (stanza.is('iq') && (stanza.attr('type') == 'get' || stanza.attr('type') == 'set')) { // TODO: When connected as a component, the from field needs to be set // eplicitly (from = stanza.attrs.to). res = new xmpp.Stanza('iq', { id: stanza.attr('id'), to: stanza.attr('from'), type: 'result' }) } // TODO: Prepare presence and message stanzas (which are optional to send) return res; }
[ "function", "prepareRes", "(", "stanza", ")", "{", "var", "res", "=", "null", ";", "if", "(", "stanza", ".", "is", "(", "'iq'", ")", "&&", "(", "stanza", ".", "attr", "(", "'type'", ")", "==", "'get'", "||", "stanza", ".", "attr", "(", "'type'", ")", "==", "'set'", ")", ")", "{", "res", "=", "new", "xmpp", ".", "Stanza", "(", "'iq'", ",", "{", "id", ":", "stanza", ".", "attr", "(", "'id'", ")", ",", "to", ":", "stanza", ".", "attr", "(", "'from'", ")", ",", "type", ":", "'result'", "}", ")", "}", "return", "res", ";", "}" ]
Prepare a response to `stanza`. @api private
[ "Prepare", "a", "response", "to", "stanza", "." ]
28854611428687602506b6aed6d2559878b0d6ea
https://github.com/jaredhanson/junction/blob/28854611428687602506b6aed6d2559878b0d6ea/lib/junction/application.js#L255-L268
train
openchain/openchain-js
lib/mutationsigner.js
MutationSigner
function MutationSigner(privateKey) { this.publicKey = ByteBuffer.wrap(privateKey.publicKey.toBuffer()); this._signer = bitcore.crypto.ECDSA().set({ endian: "big", privkey: privateKey.privateKey }); }
javascript
function MutationSigner(privateKey) { this.publicKey = ByteBuffer.wrap(privateKey.publicKey.toBuffer()); this._signer = bitcore.crypto.ECDSA().set({ endian: "big", privkey: privateKey.privateKey }); }
[ "function", "MutationSigner", "(", "privateKey", ")", "{", "this", ".", "publicKey", "=", "ByteBuffer", ".", "wrap", "(", "privateKey", ".", "publicKey", ".", "toBuffer", "(", ")", ")", ";", "this", ".", "_signer", "=", "bitcore", ".", "crypto", ".", "ECDSA", "(", ")", ".", "set", "(", "{", "endian", ":", "\"big\"", ",", "privkey", ":", "privateKey", ".", "privateKey", "}", ")", ";", "}" ]
Provides the ability to sign a mutation. @constructor @param {!HDPrivateKey} privateKey The private key used to sign the mutations.
[ "Provides", "the", "ability", "to", "sign", "a", "mutation", "." ]
41ae72504a29ba3067236f489e5117a4bda8d9d6
https://github.com/openchain/openchain-js/blob/41ae72504a29ba3067236f489e5117a4bda8d9d6/lib/mutationsigner.js#L26-L32
train
gristlabs/yaml-cfn
index.js
splitOne
function splitOne(str, sep) { let index = str.indexOf(sep); return index < 0 ? null : [str.slice(0, index), str.slice(index + sep.length)]; }
javascript
function splitOne(str, sep) { let index = str.indexOf(sep); return index < 0 ? null : [str.slice(0, index), str.slice(index + sep.length)]; }
[ "function", "splitOne", "(", "str", ",", "sep", ")", "{", "let", "index", "=", "str", ".", "indexOf", "(", "sep", ")", ";", "return", "index", "<", "0", "?", "null", ":", "[", "str", ".", "slice", "(", "0", ",", "index", ")", ",", "str", ".", "slice", "(", "index", "+", "sep", ".", "length", ")", "]", ";", "}" ]
Split a string on the given separator just once, returning an array of two parts, or null.
[ "Split", "a", "string", "on", "the", "given", "separator", "just", "once", "returning", "an", "array", "of", "two", "parts", "or", "null", "." ]
8ef43fd002fa29221f058d2be0762e4da6735103
https://github.com/gristlabs/yaml-cfn/blob/8ef43fd002fa29221f058d2be0762e4da6735103/index.js#L19-L22
train
gristlabs/yaml-cfn
index.js
checkType
function checkType(obj, keyName) { return obj && typeof obj === 'object' && Object.keys(obj).length === 1 && obj.hasOwnProperty(keyName); }
javascript
function checkType(obj, keyName) { return obj && typeof obj === 'object' && Object.keys(obj).length === 1 && obj.hasOwnProperty(keyName); }
[ "function", "checkType", "(", "obj", ",", "keyName", ")", "{", "return", "obj", "&&", "typeof", "obj", "===", "'object'", "&&", "Object", ".", "keys", "(", "obj", ")", ".", "length", "===", "1", "&&", "obj", ".", "hasOwnProperty", "(", "keyName", ")", ";", "}" ]
Returns true if obj is a representation of a CloudFormation intrinsic, i.e. an object with a single property at key keyName.
[ "Returns", "true", "if", "obj", "is", "a", "representation", "of", "a", "CloudFormation", "intrinsic", "i", ".", "e", ".", "an", "object", "with", "a", "single", "property", "at", "key", "keyName", "." ]
8ef43fd002fa29221f058d2be0762e4da6735103
https://github.com/gristlabs/yaml-cfn/blob/8ef43fd002fa29221f058d2be0762e4da6735103/index.js#L28-L31
train
jaredhanson/junction
lib/junction/stanzaerror.js
StanzaError
function StanzaError(message, type, condition) { Error.apply(this, arguments); Error.captureStackTrace(this, arguments.callee); this.name = 'StanzaError'; this.message = message || null; this.type = type || 'wait'; this.condition = condition || 'internal-server-error'; }
javascript
function StanzaError(message, type, condition) { Error.apply(this, arguments); Error.captureStackTrace(this, arguments.callee); this.name = 'StanzaError'; this.message = message || null; this.type = type || 'wait'; this.condition = condition || 'internal-server-error'; }
[ "function", "StanzaError", "(", "message", ",", "type", ",", "condition", ")", "{", "Error", ".", "apply", "(", "this", ",", "arguments", ")", ";", "Error", ".", "captureStackTrace", "(", "this", ",", "arguments", ".", "callee", ")", ";", "this", ".", "name", "=", "'StanzaError'", ";", "this", ".", "message", "=", "message", "||", "null", ";", "this", ".", "type", "=", "type", "||", "'wait'", ";", "this", ".", "condition", "=", "condition", "||", "'internal-server-error'", ";", "}" ]
Initialize a new `StanzaError`. @param {String} message @param {String} type @param {String} condition @api public
[ "Initialize", "a", "new", "StanzaError", "." ]
28854611428687602506b6aed6d2559878b0d6ea
https://github.com/jaredhanson/junction/blob/28854611428687602506b6aed6d2559878b0d6ea/lib/junction/stanzaerror.js#L14-L21
train
jaredhanson/junction
lib/junction/index.js
create
function create() { function app(stanza) { app.handle(stanza); } utils.merge(app, application); app._stack = []; app._filters = []; for (var i = 0; i < arguments.length; ++i) { app.use(arguments[i]); } return app; }
javascript
function create() { function app(stanza) { app.handle(stanza); } utils.merge(app, application); app._stack = []; app._filters = []; for (var i = 0; i < arguments.length; ++i) { app.use(arguments[i]); } return app; }
[ "function", "create", "(", ")", "{", "function", "app", "(", "stanza", ")", "{", "app", ".", "handle", "(", "stanza", ")", ";", "}", "utils", ".", "merge", "(", "app", ",", "application", ")", ";", "app", ".", "_stack", "=", "[", "]", ";", "app", ".", "_filters", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "arguments", ".", "length", ";", "++", "i", ")", "{", "app", ".", "use", "(", "arguments", "[", "i", "]", ")", ";", "}", "return", "app", ";", "}" ]
Create a Junction application. @return {Function} @api public
[ "Create", "a", "Junction", "application", "." ]
28854611428687602506b6aed6d2559878b0d6ea
https://github.com/jaredhanson/junction/blob/28854611428687602506b6aed6d2559878b0d6ea/lib/junction/index.js#L28-L37
train
openchain/openchain-js
lib/transactionbuilder.js
TransactionBuilder
function TransactionBuilder(apiClient) { if (typeof apiClient.namespace === "undefined" || apiClient.namespace === null) { throw new Error("The API client has not been initialized"); } this.client = apiClient; this.records = []; this.keys = []; this.metadata = ByteBuffer.fromHex(""); }
javascript
function TransactionBuilder(apiClient) { if (typeof apiClient.namespace === "undefined" || apiClient.namespace === null) { throw new Error("The API client has not been initialized"); } this.client = apiClient; this.records = []; this.keys = []; this.metadata = ByteBuffer.fromHex(""); }
[ "function", "TransactionBuilder", "(", "apiClient", ")", "{", "if", "(", "typeof", "apiClient", ".", "namespace", "===", "\"undefined\"", "||", "apiClient", ".", "namespace", "===", "null", ")", "{", "throw", "new", "Error", "(", "\"The API client has not been initialized\"", ")", ";", "}", "this", ".", "client", "=", "apiClient", ";", "this", ".", "records", "=", "[", "]", ";", "this", ".", "keys", "=", "[", "]", ";", "this", ".", "metadata", "=", "ByteBuffer", ".", "fromHex", "(", "\"\"", ")", ";", "}" ]
Provides the ability to build an Openchain mutation. @constructor @param {!ApiClient} apiClient The API client representing the endpoint on which the mutation should be submitted.
[ "Provides", "the", "ability", "to", "build", "an", "Openchain", "mutation", "." ]
41ae72504a29ba3067236f489e5117a4bda8d9d6
https://github.com/openchain/openchain-js/blob/41ae72504a29ba3067236f489e5117a4bda8d9d6/lib/transactionbuilder.js#L28-L38
train