repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
marionettejs/backbone.radio
src/backbone.radio.js
function(name) { var args = _.toArray(arguments).slice(1); var results = eventsApi(this, 'request', name, args); if (results) { return results; } var channelName = this.channelName; var requests = this._requests; // Check if we should log the request, and if so, do it if (channelName && this._tunedIn) { Radio.log.apply(this, [channelName, name].concat(args)); } // If the request isn't handled, log it in DEBUG mode and exit if (requests && (requests[name] || requests['default'])) { var handler = requests[name] || requests['default']; args = requests[name] ? args : arguments; return callHandler(handler.callback, handler.context, args); } else { Radio.debugLog('An unhandled request was fired', name, channelName); } }
javascript
function(name) { var args = _.toArray(arguments).slice(1); var results = eventsApi(this, 'request', name, args); if (results) { return results; } var channelName = this.channelName; var requests = this._requests; // Check if we should log the request, and if so, do it if (channelName && this._tunedIn) { Radio.log.apply(this, [channelName, name].concat(args)); } // If the request isn't handled, log it in DEBUG mode and exit if (requests && (requests[name] || requests['default'])) { var handler = requests[name] || requests['default']; args = requests[name] ? args : arguments; return callHandler(handler.callback, handler.context, args); } else { Radio.debugLog('An unhandled request was fired', name, channelName); } }
[ "function", "(", "name", ")", "{", "var", "args", "=", "_", ".", "toArray", "(", "arguments", ")", ".", "slice", "(", "1", ")", ";", "var", "results", "=", "eventsApi", "(", "this", ",", "'request'", ",", "name", ",", "args", ")", ";", "if", "(", "results", ")", "{", "return", "results", ";", "}", "var", "channelName", "=", "this", ".", "channelName", ";", "var", "requests", "=", "this", ".", "_requests", ";", "if", "(", "channelName", "&&", "this", ".", "_tunedIn", ")", "{", "Radio", ".", "log", ".", "apply", "(", "this", ",", "[", "channelName", ",", "name", "]", ".", "concat", "(", "args", ")", ")", ";", "}", "if", "(", "requests", "&&", "(", "requests", "[", "name", "]", "||", "requests", "[", "'default'", "]", ")", ")", "{", "var", "handler", "=", "requests", "[", "name", "]", "||", "requests", "[", "'default'", "]", ";", "args", "=", "requests", "[", "name", "]", "?", "args", ":", "arguments", ";", "return", "callHandler", "(", "handler", ".", "callback", ",", "handler", ".", "context", ",", "args", ")", ";", "}", "else", "{", "Radio", ".", "debugLog", "(", "'An unhandled request was fired'", ",", "name", ",", "channelName", ")", ";", "}", "}" ]
Make a request
[ "Make", "a", "request" ]
7a58ade84bedb5551c2e12bdd3434d0fd6b1bdbd
https://github.com/marionettejs/backbone.radio/blob/7a58ade84bedb5551c2e12bdd3434d0fd6b1bdbd/src/backbone.radio.js#L181-L203
train
marionettejs/backbone.radio
src/backbone.radio.js
function(name, callback, context) { if (eventsApi(this, 'replyOnce', name, [callback, context])) { return this; } var self = this; var once = _.once(function() { self.stopReplying(name); return makeCallback(callback).apply(this, arguments); }); return this.reply(name, once, context); }
javascript
function(name, callback, context) { if (eventsApi(this, 'replyOnce', name, [callback, context])) { return this; } var self = this; var once = _.once(function() { self.stopReplying(name); return makeCallback(callback).apply(this, arguments); }); return this.reply(name, once, context); }
[ "function", "(", "name", ",", "callback", ",", "context", ")", "{", "if", "(", "eventsApi", "(", "this", ",", "'replyOnce'", ",", "name", ",", "[", "callback", ",", "context", "]", ")", ")", "{", "return", "this", ";", "}", "var", "self", "=", "this", ";", "var", "once", "=", "_", ".", "once", "(", "function", "(", ")", "{", "self", ".", "stopReplying", "(", "name", ")", ";", "return", "makeCallback", "(", "callback", ")", ".", "apply", "(", "this", ",", "arguments", ")", ";", "}", ")", ";", "return", "this", ".", "reply", "(", "name", ",", "once", ",", "context", ")", ";", "}" ]
Set up a handler that can only be requested once
[ "Set", "up", "a", "handler", "that", "can", "only", "be", "requested", "once" ]
7a58ade84bedb5551c2e12bdd3434d0fd6b1bdbd
https://github.com/marionettejs/backbone.radio/blob/7a58ade84bedb5551c2e12bdd3434d0fd6b1bdbd/src/backbone.radio.js#L226-L239
train
lpinca/forwarded-parse
lib/ascii.js
isDelimiter
function isDelimiter(code) { return code === 0x22 // '"' || code === 0x28 // '(' || code === 0x29 // ')' || code === 0x2C // ',' || code === 0x2F // '/' || code >= 0x3A && code <= 0x40 // ':', ';', '<', '=', '>', '?' '@' || code >= 0x5B && code <= 0x5D // '[', '\', ']' || code === 0x7B // '{' || code === 0x7D; // '}' }
javascript
function isDelimiter(code) { return code === 0x22 // '"' || code === 0x28 // '(' || code === 0x29 // ')' || code === 0x2C // ',' || code === 0x2F // '/' || code >= 0x3A && code <= 0x40 // ':', ';', '<', '=', '>', '?' '@' || code >= 0x5B && code <= 0x5D // '[', '\', ']' || code === 0x7B // '{' || code === 0x7D; // '}' }
[ "function", "isDelimiter", "(", "code", ")", "{", "return", "code", "===", "0x22", "||", "code", "===", "0x28", "||", "code", "===", "0x29", "||", "code", "===", "0x2C", "||", "code", "===", "0x2F", "||", "code", ">=", "0x3A", "&&", "code", "<=", "0x40", "||", "code", ">=", "0x5B", "&&", "code", "<=", "0x5D", "||", "code", "===", "0x7B", "||", "code", "===", "0x7D", ";", "}" ]
Check if a character is a delimiter as defined in section 3.2.6 of RFC 7230. @param {number} code The code of the character to check. @returns {boolean} `true` if the character is a delimiter, else `false`. @public
[ "Check", "if", "a", "character", "is", "a", "delimiter", "as", "defined", "in", "section", "3", ".", "2", ".", "6", "of", "RFC", "7230", "." ]
a80ef2cb3892ff7c0a2ec80800cd8aa4580dfe89
https://github.com/lpinca/forwarded-parse/blob/a80ef2cb3892ff7c0a2ec80800cd8aa4580dfe89/lib/ascii.js#L11-L21
train
lpinca/forwarded-parse
lib/ascii.js
isTokenChar
function isTokenChar(code) { return code === 0x21 // '!' || code >= 0x23 && code <= 0x27 // '#', '$', '%', '&', ''' || code === 0x2A // '*' || code === 0x2B // '+' || code === 0x2D // '-' || code === 0x2E // '.' || code >= 0x30 && code <= 0x39 // 0-9 || code >= 0x41 && code <= 0x5A // A-Z || code >= 0x5E && code <= 0x7A // '^', '_', '`', a-z || code === 0x7C // '|' || code === 0x7E; // '~' }
javascript
function isTokenChar(code) { return code === 0x21 // '!' || code >= 0x23 && code <= 0x27 // '#', '$', '%', '&', ''' || code === 0x2A // '*' || code === 0x2B // '+' || code === 0x2D // '-' || code === 0x2E // '.' || code >= 0x30 && code <= 0x39 // 0-9 || code >= 0x41 && code <= 0x5A // A-Z || code >= 0x5E && code <= 0x7A // '^', '_', '`', a-z || code === 0x7C // '|' || code === 0x7E; // '~' }
[ "function", "isTokenChar", "(", "code", ")", "{", "return", "code", "===", "0x21", "||", "code", ">=", "0x23", "&&", "code", "<=", "0x27", "||", "code", "===", "0x2A", "||", "code", "===", "0x2B", "||", "code", "===", "0x2D", "||", "code", "===", "0x2E", "||", "code", ">=", "0x30", "&&", "code", "<=", "0x39", "||", "code", ">=", "0x41", "&&", "code", "<=", "0x5A", "||", "code", ">=", "0x5E", "&&", "code", "<=", "0x7A", "||", "code", "===", "0x7C", "||", "code", "===", "0x7E", ";", "}" ]
Check if a character is allowed in a token as defined in section 3.2.6 of RFC 7230. @param {number} code The code of the character to check. @returns {boolean} `true` if the character is allowed, else `false`. @public
[ "Check", "if", "a", "character", "is", "allowed", "in", "a", "token", "as", "defined", "in", "section", "3", ".", "2", ".", "6", "of", "RFC", "7230", "." ]
a80ef2cb3892ff7c0a2ec80800cd8aa4580dfe89
https://github.com/lpinca/forwarded-parse/blob/a80ef2cb3892ff7c0a2ec80800cd8aa4580dfe89/lib/ascii.js#L31-L43
train
lpinca/forwarded-parse
lib/error.js
ParseError
function ParseError(message, input) { Error.captureStackTrace(this, ParseError); this.name = this.constructor.name; this.message = message; this.input = input; }
javascript
function ParseError(message, input) { Error.captureStackTrace(this, ParseError); this.name = this.constructor.name; this.message = message; this.input = input; }
[ "function", "ParseError", "(", "message", ",", "input", ")", "{", "Error", ".", "captureStackTrace", "(", "this", ",", "ParseError", ")", ";", "this", ".", "name", "=", "this", ".", "constructor", ".", "name", ";", "this", ".", "message", "=", "message", ";", "this", ".", "input", "=", "input", ";", "}" ]
An error thrown by the parser on unexpected input. @constructor @param {string} message The error message. @param {string} input The unexpected input. @public
[ "An", "error", "thrown", "by", "the", "parser", "on", "unexpected", "input", "." ]
a80ef2cb3892ff7c0a2ec80800cd8aa4580dfe89
https://github.com/lpinca/forwarded-parse/blob/a80ef2cb3892ff7c0a2ec80800cd8aa4580dfe89/lib/error.js#L13-L19
train
RisingStack/graffiti-mongoose
src/model/model.js
extractPath
function extractPath(schemaPath) { const subNames = schemaPath.path.split('.'); return reduceRight(subNames, (fields, name, key) => { const obj = {}; if (schemaPath instanceof mongoose.Schema.Types.DocumentArray) { const subSchemaPaths = schemaPath.schema.paths; const fields = extractPaths(subSchemaPaths, { name }); // eslint-disable-line no-use-before-define obj[name] = { name, fields, nonNull: false, type: 'Array', subtype: 'Object' }; } else if (schemaPath instanceof mongoose.Schema.Types.Embedded) { schemaPath.modelName = schemaPath.schema.options.graphqlTypeName || name; // embedded model must be unique Instance const embeddedModel = embeddedModels.hasOwnProperty(schemaPath.modelName) ? embeddedModels[schemaPath.modelName] : getModel(schemaPath); // eslint-disable-line no-use-before-define embeddedModels[schemaPath.modelName] = embeddedModel; obj[name] = { ...getField(schemaPath), embeddedModel }; } else if (key === subNames.length - 1) { obj[name] = getField(schemaPath); } else { obj[name] = { name, fields, nonNull: false, type: 'Object' }; } return obj; }, {}); }
javascript
function extractPath(schemaPath) { const subNames = schemaPath.path.split('.'); return reduceRight(subNames, (fields, name, key) => { const obj = {}; if (schemaPath instanceof mongoose.Schema.Types.DocumentArray) { const subSchemaPaths = schemaPath.schema.paths; const fields = extractPaths(subSchemaPaths, { name }); // eslint-disable-line no-use-before-define obj[name] = { name, fields, nonNull: false, type: 'Array', subtype: 'Object' }; } else if (schemaPath instanceof mongoose.Schema.Types.Embedded) { schemaPath.modelName = schemaPath.schema.options.graphqlTypeName || name; // embedded model must be unique Instance const embeddedModel = embeddedModels.hasOwnProperty(schemaPath.modelName) ? embeddedModels[schemaPath.modelName] : getModel(schemaPath); // eslint-disable-line no-use-before-define embeddedModels[schemaPath.modelName] = embeddedModel; obj[name] = { ...getField(schemaPath), embeddedModel }; } else if (key === subNames.length - 1) { obj[name] = getField(schemaPath); } else { obj[name] = { name, fields, nonNull: false, type: 'Object' }; } return obj; }, {}); }
[ "function", "extractPath", "(", "schemaPath", ")", "{", "const", "subNames", "=", "schemaPath", ".", "path", ".", "split", "(", "'.'", ")", ";", "return", "reduceRight", "(", "subNames", ",", "(", "fields", ",", "name", ",", "key", ")", "=>", "{", "const", "obj", "=", "{", "}", ";", "if", "(", "schemaPath", "instanceof", "mongoose", ".", "Schema", ".", "Types", ".", "DocumentArray", ")", "{", "const", "subSchemaPaths", "=", "schemaPath", ".", "schema", ".", "paths", ";", "const", "fields", "=", "extractPaths", "(", "subSchemaPaths", ",", "{", "name", "}", ")", ";", "obj", "[", "name", "]", "=", "{", "name", ",", "fields", ",", "nonNull", ":", "false", ",", "type", ":", "'Array'", ",", "subtype", ":", "'Object'", "}", ";", "}", "else", "if", "(", "schemaPath", "instanceof", "mongoose", ".", "Schema", ".", "Types", ".", "Embedded", ")", "{", "schemaPath", ".", "modelName", "=", "schemaPath", ".", "schema", ".", "options", ".", "graphqlTypeName", "||", "name", ";", "const", "embeddedModel", "=", "embeddedModels", ".", "hasOwnProperty", "(", "schemaPath", ".", "modelName", ")", "?", "embeddedModels", "[", "schemaPath", ".", "modelName", "]", ":", "getModel", "(", "schemaPath", ")", ";", "embeddedModels", "[", "schemaPath", ".", "modelName", "]", "=", "embeddedModel", ";", "obj", "[", "name", "]", "=", "{", "...", "getField", "(", "schemaPath", ")", ",", "embeddedModel", "}", ";", "}", "else", "if", "(", "key", "===", "subNames", ".", "length", "-", "1", ")", "{", "obj", "[", "name", "]", "=", "getField", "(", "schemaPath", ")", ";", "}", "else", "{", "obj", "[", "name", "]", "=", "{", "name", ",", "fields", ",", "nonNull", ":", "false", ",", "type", ":", "'Object'", "}", ";", "}", "return", "obj", ";", "}", ",", "{", "}", ")", ";", "}" ]
Extracts tree chunk from path if it's a sub-document @method extractPath @param {Object} schemaPath @param {Object} model @return {Object} field
[ "Extracts", "tree", "chunk", "from", "path", "if", "it", "s", "a", "sub", "-", "document" ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/model/model.js#L65-L106
train
RisingStack/graffiti-mongoose
src/model/model.js
extractPaths
function extractPaths(schemaPaths, model) { return reduce(schemaPaths, (fields, schemaPath) => ( merge(fields, extractPath(schemaPath, model)) ), {}); }
javascript
function extractPaths(schemaPaths, model) { return reduce(schemaPaths, (fields, schemaPath) => ( merge(fields, extractPath(schemaPath, model)) ), {}); }
[ "function", "extractPaths", "(", "schemaPaths", ",", "model", ")", "{", "return", "reduce", "(", "schemaPaths", ",", "(", "fields", ",", "schemaPath", ")", "=>", "(", "merge", "(", "fields", ",", "extractPath", "(", "schemaPath", ",", "model", ")", ")", ")", ",", "{", "}", ")", ";", "}" ]
Merge sub-document tree chunks @method extractPaths @param {Object} schemaPaths @param {Object} model @return {Object) extractedSchemaPaths
[ "Merge", "sub", "-", "document", "tree", "chunks" ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/model/model.js#L115-L119
train
RisingStack/graffiti-mongoose
src/model/model.js
getModel
function getModel(model) { const schemaPaths = model.schema.paths; const name = model.modelName; const fields = extractPaths(schemaPaths, { name }); return { name, fields, model }; }
javascript
function getModel(model) { const schemaPaths = model.schema.paths; const name = model.modelName; const fields = extractPaths(schemaPaths, { name }); return { name, fields, model }; }
[ "function", "getModel", "(", "model", ")", "{", "const", "schemaPaths", "=", "model", ".", "schema", ".", "paths", ";", "const", "name", "=", "model", ".", "modelName", ";", "const", "fields", "=", "extractPaths", "(", "schemaPaths", ",", "{", "name", "}", ")", ";", "return", "{", "name", ",", "fields", ",", "model", "}", ";", "}" ]
Turn mongoose model to graffiti model @method getModel @param {Object} model Mongoose model @return {Object} graffiti model
[ "Turn", "mongoose", "model", "to", "graffiti", "model" ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/model/model.js#L127-L138
train
RisingStack/graffiti-mongoose
src/query/query.js
getIdFetcher
function getIdFetcher(graffitiModels) { return function idFetcher(obj, { id: globalId }, context, info) { const { type, id } = fromGlobalId(globalId); if (type === 'Viewer') { return viewer; } else if (graffitiModels[type]) { const Collection = graffitiModels[type].model; return getOne(Collection, { id }, context, info); } return null; }; }
javascript
function getIdFetcher(graffitiModels) { return function idFetcher(obj, { id: globalId }, context, info) { const { type, id } = fromGlobalId(globalId); if (type === 'Viewer') { return viewer; } else if (graffitiModels[type]) { const Collection = graffitiModels[type].model; return getOne(Collection, { id }, context, info); } return null; }; }
[ "function", "getIdFetcher", "(", "graffitiModels", ")", "{", "return", "function", "idFetcher", "(", "obj", ",", "{", "id", ":", "globalId", "}", ",", "context", ",", "info", ")", "{", "const", "{", "type", ",", "id", "}", "=", "fromGlobalId", "(", "globalId", ")", ";", "if", "(", "type", "===", "'Viewer'", ")", "{", "return", "viewer", ";", "}", "else", "if", "(", "graffitiModels", "[", "type", "]", ")", "{", "const", "Collection", "=", "graffitiModels", "[", "type", "]", ".", "model", ";", "return", "getOne", "(", "Collection", ",", "{", "id", "}", ",", "context", ",", "info", ")", ";", "}", "return", "null", ";", "}", ";", "}" ]
Returns an idFetcher function, that can resolve an object based on a global id
[ "Returns", "an", "idFetcher", "function", "that", "can", "resolve", "an", "object", "based", "on", "a", "global", "id" ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/query/query.js#L198-L211
train
RisingStack/graffiti-mongoose
src/query/query.js
emptyConnection
function emptyConnection() { return { count: 0, edges: [], pageInfo: { startCursor: null, endCursor: null, hasPreviousPage: false, hasNextPage: false } }; }
javascript
function emptyConnection() { return { count: 0, edges: [], pageInfo: { startCursor: null, endCursor: null, hasPreviousPage: false, hasNextPage: false } }; }
[ "function", "emptyConnection", "(", ")", "{", "return", "{", "count", ":", "0", ",", "edges", ":", "[", "]", ",", "pageInfo", ":", "{", "startCursor", ":", "null", ",", "endCursor", ":", "null", ",", "hasPreviousPage", ":", "false", ",", "hasNextPage", ":", "false", "}", "}", ";", "}" ]
Helper to get an empty connection.
[ "Helper", "to", "get", "an", "empty", "connection", "." ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/query/query.js#L216-L227
train
RisingStack/graffiti-mongoose
src/query/query.js
connectionFromModel
async function connectionFromModel(graffitiModel, args, context, info) { const Collection = graffitiModel.model; if (!Collection) { return emptyConnection(); } const { before, after, first, last, id, orderBy = { _id: 1 }, ...selector } = args; const begin = getId(after); const end = getId(before); const offset = (first - last) || 0; const limit = last || first; if (id) { selector.id = id; } if (begin) { selector._id = selector._id || {}; selector._id.$gt = begin; } if (end) { selector._id = selector._id || {}; selector._id.$lt = end; } const result = await getList(Collection, selector, { limit, skip: offset, sort: orderBy }, context, info); const count = await getCount(Collection, selector); if (result.length === 0) { return emptyConnection(); } const edges = result.map((value) => ({ cursor: idToCursor(value._id), node: value })); const firstElement = await getFirst(Collection); return { count, edges, pageInfo: { startCursor: edges[0].cursor, endCursor: edges[edges.length - 1].cursor, hasPreviousPage: cursorToId(edges[0].cursor) !== firstElement._id.toString(), hasNextPage: result.length === limit } }; }
javascript
async function connectionFromModel(graffitiModel, args, context, info) { const Collection = graffitiModel.model; if (!Collection) { return emptyConnection(); } const { before, after, first, last, id, orderBy = { _id: 1 }, ...selector } = args; const begin = getId(after); const end = getId(before); const offset = (first - last) || 0; const limit = last || first; if (id) { selector.id = id; } if (begin) { selector._id = selector._id || {}; selector._id.$gt = begin; } if (end) { selector._id = selector._id || {}; selector._id.$lt = end; } const result = await getList(Collection, selector, { limit, skip: offset, sort: orderBy }, context, info); const count = await getCount(Collection, selector); if (result.length === 0) { return emptyConnection(); } const edges = result.map((value) => ({ cursor: idToCursor(value._id), node: value })); const firstElement = await getFirst(Collection); return { count, edges, pageInfo: { startCursor: edges[0].cursor, endCursor: edges[edges.length - 1].cursor, hasPreviousPage: cursorToId(edges[0].cursor) !== firstElement._id.toString(), hasNextPage: result.length === limit } }; }
[ "async", "function", "connectionFromModel", "(", "graffitiModel", ",", "args", ",", "context", ",", "info", ")", "{", "const", "Collection", "=", "graffitiModel", ".", "model", ";", "if", "(", "!", "Collection", ")", "{", "return", "emptyConnection", "(", ")", ";", "}", "const", "{", "before", ",", "after", ",", "first", ",", "last", ",", "id", ",", "orderBy", "=", "{", "_id", ":", "1", "}", ",", "...", "selector", "}", "=", "args", ";", "const", "begin", "=", "getId", "(", "after", ")", ";", "const", "end", "=", "getId", "(", "before", ")", ";", "const", "offset", "=", "(", "first", "-", "last", ")", "||", "0", ";", "const", "limit", "=", "last", "||", "first", ";", "if", "(", "id", ")", "{", "selector", ".", "id", "=", "id", ";", "}", "if", "(", "begin", ")", "{", "selector", ".", "_id", "=", "selector", ".", "_id", "||", "{", "}", ";", "selector", ".", "_id", ".", "$gt", "=", "begin", ";", "}", "if", "(", "end", ")", "{", "selector", ".", "_id", "=", "selector", ".", "_id", "||", "{", "}", ";", "selector", ".", "_id", ".", "$lt", "=", "end", ";", "}", "const", "result", "=", "await", "getList", "(", "Collection", ",", "selector", ",", "{", "limit", ",", "skip", ":", "offset", ",", "sort", ":", "orderBy", "}", ",", "context", ",", "info", ")", ";", "const", "count", "=", "await", "getCount", "(", "Collection", ",", "selector", ")", ";", "if", "(", "result", ".", "length", "===", "0", ")", "{", "return", "emptyConnection", "(", ")", ";", "}", "const", "edges", "=", "result", ".", "map", "(", "(", "value", ")", "=>", "(", "{", "cursor", ":", "idToCursor", "(", "value", ".", "_id", ")", ",", "node", ":", "value", "}", ")", ")", ";", "const", "firstElement", "=", "await", "getFirst", "(", "Collection", ")", ";", "return", "{", "count", ",", "edges", ",", "pageInfo", ":", "{", "startCursor", ":", "edges", "[", "0", "]", ".", "cursor", ",", "endCursor", ":", "edges", "[", "edges", ".", "length", "-", "1", "]", ".", "cursor", ",", "hasPreviousPage", ":", "cursorToId", "(", "edges", "[", "0", "]", ".", "cursor", ")", "!==", "firstElement", ".", "_id", ".", "toString", "(", ")", ",", "hasNextPage", ":", "result", ".", "length", "===", "limit", "}", "}", ";", "}" ]
Returns a connection based on a graffitiModel
[ "Returns", "a", "connection", "based", "on", "a", "graffitiModel" ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/query/query.js#L269-L324
train
RisingStack/graffiti-mongoose
src/type/type.js
stringToGraphQLType
function stringToGraphQLType(type) { switch (type) { case 'String': return GraphQLString; case 'Number': return GraphQLFloat; case 'Date': return GraphQLDate; case 'Buffer': return GraphQLBuffer; case 'Boolean': return GraphQLBoolean; case 'ObjectID': return GraphQLID; default: return GraphQLGeneric; } }
javascript
function stringToGraphQLType(type) { switch (type) { case 'String': return GraphQLString; case 'Number': return GraphQLFloat; case 'Date': return GraphQLDate; case 'Buffer': return GraphQLBuffer; case 'Boolean': return GraphQLBoolean; case 'ObjectID': return GraphQLID; default: return GraphQLGeneric; } }
[ "function", "stringToGraphQLType", "(", "type", ")", "{", "switch", "(", "type", ")", "{", "case", "'String'", ":", "return", "GraphQLString", ";", "case", "'Number'", ":", "return", "GraphQLFloat", ";", "case", "'Date'", ":", "return", "GraphQLDate", ";", "case", "'Buffer'", ":", "return", "GraphQLBuffer", ";", "case", "'Boolean'", ":", "return", "GraphQLBoolean", ";", "case", "'ObjectID'", ":", "return", "GraphQLID", ";", "default", ":", "return", "GraphQLGeneric", ";", "}", "}" ]
Returns a GraphQL type based on a String representation @param {String} type @return {GraphQLType}
[ "Returns", "a", "GraphQL", "type", "based", "on", "a", "String", "representation" ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/type/type.js#L61-L78
train
RisingStack/graffiti-mongoose
src/type/type.js
listToGraphQLEnumType
function listToGraphQLEnumType(list, name) { const values = reduce(list, (values, val) => { values[val] = { value: val }; return values; }, {}); return new GraphQLEnumType({ name, values }); }
javascript
function listToGraphQLEnumType(list, name) { const values = reduce(list, (values, val) => { values[val] = { value: val }; return values; }, {}); return new GraphQLEnumType({ name, values }); }
[ "function", "listToGraphQLEnumType", "(", "list", ",", "name", ")", "{", "const", "values", "=", "reduce", "(", "list", ",", "(", "values", ",", "val", ")", "=>", "{", "values", "[", "val", "]", "=", "{", "value", ":", "val", "}", ";", "return", "values", ";", "}", ",", "{", "}", ")", ";", "return", "new", "GraphQLEnumType", "(", "{", "name", ",", "values", "}", ")", ";", "}" ]
Returns a GraphQL Enum type based on a List of Strings @param {Array} list @param {String} name @return {Object}
[ "Returns", "a", "GraphQL", "Enum", "type", "based", "on", "a", "List", "of", "Strings" ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/type/type.js#L86-L92
train
RisingStack/graffiti-mongoose
src/type/type.js
getTypeFields
function getTypeFields(type) { const fields = type._typeConfig.fields; return isFunction(fields) ? fields() : fields; }
javascript
function getTypeFields(type) { const fields = type._typeConfig.fields; return isFunction(fields) ? fields() : fields; }
[ "function", "getTypeFields", "(", "type", ")", "{", "const", "fields", "=", "type", ".", "_typeConfig", ".", "fields", ";", "return", "isFunction", "(", "fields", ")", "?", "fields", "(", ")", ":", "fields", ";", "}" ]
Extracts the fields of a GraphQL type @param {GraphQLType} type @return {Object}
[ "Extracts", "the", "fields", "of", "a", "GraphQL", "type" ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/type/type.js#L99-L102
train
RisingStack/graffiti-mongoose
src/type/type.js
getOrderByType
function getOrderByType({ name }, fields) { if (!orderByTypes[name]) { // save new enum orderByTypes[name] = new GraphQLEnumType({ name: `orderBy${name}`, values: reduce(fields, (values, field) => { if (field.type instanceof GraphQLScalarType) { const upperCaseName = field.name.toUpperCase(); values[`${upperCaseName}_ASC`] = { name: `${upperCaseName}_ASC`, value: { [field.name]: 1 } }; values[`${upperCaseName}_DESC`] = { name: `${upperCaseName}_DESC`, value: { [field.name]: -1 } }; } return values; }, {}) }); } return orderByTypes[name]; }
javascript
function getOrderByType({ name }, fields) { if (!orderByTypes[name]) { // save new enum orderByTypes[name] = new GraphQLEnumType({ name: `orderBy${name}`, values: reduce(fields, (values, field) => { if (field.type instanceof GraphQLScalarType) { const upperCaseName = field.name.toUpperCase(); values[`${upperCaseName}_ASC`] = { name: `${upperCaseName}_ASC`, value: { [field.name]: 1 } }; values[`${upperCaseName}_DESC`] = { name: `${upperCaseName}_DESC`, value: { [field.name]: -1 } }; } return values; }, {}) }); } return orderByTypes[name]; }
[ "function", "getOrderByType", "(", "{", "name", "}", ",", "fields", ")", "{", "if", "(", "!", "orderByTypes", "[", "name", "]", ")", "{", "orderByTypes", "[", "name", "]", "=", "new", "GraphQLEnumType", "(", "{", "name", ":", "`", "${", "name", "}", "`", ",", "values", ":", "reduce", "(", "fields", ",", "(", "values", ",", "field", ")", "=>", "{", "if", "(", "field", ".", "type", "instanceof", "GraphQLScalarType", ")", "{", "const", "upperCaseName", "=", "field", ".", "name", ".", "toUpperCase", "(", ")", ";", "values", "[", "`", "${", "upperCaseName", "}", "`", "]", "=", "{", "name", ":", "`", "${", "upperCaseName", "}", "`", ",", "value", ":", "{", "[", "field", ".", "name", "]", ":", "1", "}", "}", ";", "values", "[", "`", "${", "upperCaseName", "}", "`", "]", "=", "{", "name", ":", "`", "${", "upperCaseName", "}", "`", ",", "value", ":", "{", "[", "field", ".", "name", "]", ":", "-", "1", "}", "}", ";", "}", "return", "values", ";", "}", ",", "{", "}", ")", "}", ")", ";", "}", "return", "orderByTypes", "[", "name", "]", ";", "}" ]
Returns order by GraphQLEnumType for fields @param {{String}} {name} @param {Object} fields @return {GraphQLEnumType}
[ "Returns", "order", "by", "GraphQLEnumType", "for", "fields" ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/type/type.js#L120-L147
train
RisingStack/graffiti-mongoose
src/type/type.js
getArguments
function getArguments(type, args = {}) { const fields = getTypeFields(type); return reduce(fields, (args, field) => { // Extract non null fields, those are not required in the arguments if (field.type instanceof GraphQLNonNull && field.name !== 'id') { field.type = field.type.ofType; } if (field.type instanceof GraphQLScalarType) { args[field.name] = field; } return args; }, { ...args, orderBy: { name: 'orderBy', type: getOrderByType(type, fields) } }); }
javascript
function getArguments(type, args = {}) { const fields = getTypeFields(type); return reduce(fields, (args, field) => { // Extract non null fields, those are not required in the arguments if (field.type instanceof GraphQLNonNull && field.name !== 'id') { field.type = field.type.ofType; } if (field.type instanceof GraphQLScalarType) { args[field.name] = field; } return args; }, { ...args, orderBy: { name: 'orderBy', type: getOrderByType(type, fields) } }); }
[ "function", "getArguments", "(", "type", ",", "args", "=", "{", "}", ")", "{", "const", "fields", "=", "getTypeFields", "(", "type", ")", ";", "return", "reduce", "(", "fields", ",", "(", "args", ",", "field", ")", "=>", "{", "if", "(", "field", ".", "type", "instanceof", "GraphQLNonNull", "&&", "field", ".", "name", "!==", "'id'", ")", "{", "field", ".", "type", "=", "field", ".", "type", ".", "ofType", ";", "}", "if", "(", "field", ".", "type", "instanceof", "GraphQLScalarType", ")", "{", "args", "[", "field", ".", "name", "]", "=", "field", ";", "}", "return", "args", ";", "}", ",", "{", "...", "args", ",", "orderBy", ":", "{", "name", ":", "'orderBy'", ",", "type", ":", "getOrderByType", "(", "type", ",", "fields", ")", "}", "}", ")", ";", "}" ]
Returns query arguments for a GraphQL type @param {GraphQLType} type @param {Object} args @return {Object}
[ "Returns", "query", "arguments", "for", "a", "GraphQL", "type" ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/type/type.js#L155-L176
train
RisingStack/graffiti-mongoose
src/type/type.js
getTypeFieldName
function getTypeFieldName(typeName, fieldName) { const fieldNameCapitalized = fieldName.charAt(0).toUpperCase() + fieldName.slice(1); return `${typeName}${fieldNameCapitalized}`; }
javascript
function getTypeFieldName(typeName, fieldName) { const fieldNameCapitalized = fieldName.charAt(0).toUpperCase() + fieldName.slice(1); return `${typeName}${fieldNameCapitalized}`; }
[ "function", "getTypeFieldName", "(", "typeName", ",", "fieldName", ")", "{", "const", "fieldNameCapitalized", "=", "fieldName", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "fieldName", ".", "slice", "(", "1", ")", ";", "return", "`", "${", "typeName", "}", "${", "fieldNameCapitalized", "}", "`", ";", "}" ]
Returns a concatenation of type and field name, used for nestedObjects @param {String} typeName @param {String} fieldName @returns {String}
[ "Returns", "a", "concatenation", "of", "type", "and", "field", "name", "used", "for", "nestedObjects" ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/type/type.js#L184-L187
train
RisingStack/graffiti-mongoose
src/schema/schema.js
getFields
function getFields(graffitiModels, { hooks = {}, mutation = true, allowMongoIDMutation = false, customQueries = {}, customMutations = {} } = {}) { const types = type.getTypes(graffitiModels); const { viewer, singular } = hooks; const viewerFields = reduce(types, (fields, type, key) => { type.name = type.name || key; const graffitiModel = graffitiModels[type.name]; return { ...fields, ...getConnectionField(graffitiModel, type, hooks), ...getSingularQueryField(graffitiModel, type, hooks) }; }, { id: globalIdField('Viewer') }); setTypeFields(GraphQLViewer, viewerFields); const viewerField = { name: 'Viewer', type: GraphQLViewer, resolve: addHooks(() => viewerInstance, viewer) }; const { queries, mutations } = reduce(types, ({ queries, mutations }, type, key) => { type.name = type.name || key; const graffitiModel = graffitiModels[type.name]; return { queries: { ...queries, ...getQueryField(graffitiModel, type, hooks) }, mutations: { ...mutations, ...getMutationField(graffitiModel, type, viewerField, hooks, allowMongoIDMutation) } }; }, { queries: isFunction(customQueries) ? customQueries(mapValues(types, (type) => createInputObject(type)), types) : customQueries, mutations: isFunction(customMutations) ? customMutations(mapValues(types, (type) => createInputObject(type)), types) : customMutations }); const RootQuery = new GraphQLObjectType({ name: 'RootQuery', fields: { ...queries, viewer: viewerField, node: { name: 'node', description: 'Fetches an object given its ID', type: nodeInterface, args: { id: { type: new GraphQLNonNull(GraphQLID), description: 'The ID of an object' } }, resolve: addHooks(getIdFetcher(graffitiModels), singular) } } }); const RootMutation = new GraphQLObjectType({ name: 'RootMutation', fields: mutations }); const fields = { query: RootQuery }; if (mutation) { fields.mutation = RootMutation; } return fields; }
javascript
function getFields(graffitiModels, { hooks = {}, mutation = true, allowMongoIDMutation = false, customQueries = {}, customMutations = {} } = {}) { const types = type.getTypes(graffitiModels); const { viewer, singular } = hooks; const viewerFields = reduce(types, (fields, type, key) => { type.name = type.name || key; const graffitiModel = graffitiModels[type.name]; return { ...fields, ...getConnectionField(graffitiModel, type, hooks), ...getSingularQueryField(graffitiModel, type, hooks) }; }, { id: globalIdField('Viewer') }); setTypeFields(GraphQLViewer, viewerFields); const viewerField = { name: 'Viewer', type: GraphQLViewer, resolve: addHooks(() => viewerInstance, viewer) }; const { queries, mutations } = reduce(types, ({ queries, mutations }, type, key) => { type.name = type.name || key; const graffitiModel = graffitiModels[type.name]; return { queries: { ...queries, ...getQueryField(graffitiModel, type, hooks) }, mutations: { ...mutations, ...getMutationField(graffitiModel, type, viewerField, hooks, allowMongoIDMutation) } }; }, { queries: isFunction(customQueries) ? customQueries(mapValues(types, (type) => createInputObject(type)), types) : customQueries, mutations: isFunction(customMutations) ? customMutations(mapValues(types, (type) => createInputObject(type)), types) : customMutations }); const RootQuery = new GraphQLObjectType({ name: 'RootQuery', fields: { ...queries, viewer: viewerField, node: { name: 'node', description: 'Fetches an object given its ID', type: nodeInterface, args: { id: { type: new GraphQLNonNull(GraphQLID), description: 'The ID of an object' } }, resolve: addHooks(getIdFetcher(graffitiModels), singular) } } }); const RootMutation = new GraphQLObjectType({ name: 'RootMutation', fields: mutations }); const fields = { query: RootQuery }; if (mutation) { fields.mutation = RootMutation; } return fields; }
[ "function", "getFields", "(", "graffitiModels", ",", "{", "hooks", "=", "{", "}", ",", "mutation", "=", "true", ",", "allowMongoIDMutation", "=", "false", ",", "customQueries", "=", "{", "}", ",", "customMutations", "=", "{", "}", "}", "=", "{", "}", ")", "{", "const", "types", "=", "type", ".", "getTypes", "(", "graffitiModels", ")", ";", "const", "{", "viewer", ",", "singular", "}", "=", "hooks", ";", "const", "viewerFields", "=", "reduce", "(", "types", ",", "(", "fields", ",", "type", ",", "key", ")", "=>", "{", "type", ".", "name", "=", "type", ".", "name", "||", "key", ";", "const", "graffitiModel", "=", "graffitiModels", "[", "type", ".", "name", "]", ";", "return", "{", "...", "fields", ",", "...", "getConnectionField", "(", "graffitiModel", ",", "type", ",", "hooks", ")", ",", "...", "getSingularQueryField", "(", "graffitiModel", ",", "type", ",", "hooks", ")", "}", ";", "}", ",", "{", "id", ":", "globalIdField", "(", "'Viewer'", ")", "}", ")", ";", "setTypeFields", "(", "GraphQLViewer", ",", "viewerFields", ")", ";", "const", "viewerField", "=", "{", "name", ":", "'Viewer'", ",", "type", ":", "GraphQLViewer", ",", "resolve", ":", "addHooks", "(", "(", ")", "=>", "viewerInstance", ",", "viewer", ")", "}", ";", "const", "{", "queries", ",", "mutations", "}", "=", "reduce", "(", "types", ",", "(", "{", "queries", ",", "mutations", "}", ",", "type", ",", "key", ")", "=>", "{", "type", ".", "name", "=", "type", ".", "name", "||", "key", ";", "const", "graffitiModel", "=", "graffitiModels", "[", "type", ".", "name", "]", ";", "return", "{", "queries", ":", "{", "...", "queries", ",", "...", "getQueryField", "(", "graffitiModel", ",", "type", ",", "hooks", ")", "}", ",", "mutations", ":", "{", "...", "mutations", ",", "...", "getMutationField", "(", "graffitiModel", ",", "type", ",", "viewerField", ",", "hooks", ",", "allowMongoIDMutation", ")", "}", "}", ";", "}", ",", "{", "queries", ":", "isFunction", "(", "customQueries", ")", "?", "customQueries", "(", "mapValues", "(", "types", ",", "(", "type", ")", "=>", "createInputObject", "(", "type", ")", ")", ",", "types", ")", ":", "customQueries", ",", "mutations", ":", "isFunction", "(", "customMutations", ")", "?", "customMutations", "(", "mapValues", "(", "types", ",", "(", "type", ")", "=>", "createInputObject", "(", "type", ")", ")", ",", "types", ")", ":", "customMutations", "}", ")", ";", "const", "RootQuery", "=", "new", "GraphQLObjectType", "(", "{", "name", ":", "'RootQuery'", ",", "fields", ":", "{", "...", "queries", ",", "viewer", ":", "viewerField", ",", "node", ":", "{", "name", ":", "'node'", ",", "description", ":", "'Fetches an object given its ID'", ",", "type", ":", "nodeInterface", ",", "args", ":", "{", "id", ":", "{", "type", ":", "new", "GraphQLNonNull", "(", "GraphQLID", ")", ",", "description", ":", "'The ID of an object'", "}", "}", ",", "resolve", ":", "addHooks", "(", "getIdFetcher", "(", "graffitiModels", ")", ",", "singular", ")", "}", "}", "}", ")", ";", "const", "RootMutation", "=", "new", "GraphQLObjectType", "(", "{", "name", ":", "'RootMutation'", ",", "fields", ":", "mutations", "}", ")", ";", "const", "fields", "=", "{", "query", ":", "RootQuery", "}", ";", "if", "(", "mutation", ")", "{", "fields", ".", "mutation", "=", "RootMutation", ";", "}", "return", "fields", ";", "}" ]
Returns query and mutation root fields @param {Array} graffitiModels @param {{Object, Boolean}} {hooks, mutation, allowMongoIDMutation} @return {Object}
[ "Returns", "query", "and", "mutation", "root", "fields" ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/schema/schema.js#L231-L313
train
RisingStack/graffiti-mongoose
src/schema/schema.js
getSchema
function getSchema(mongooseModels, options) { if (!isArray(mongooseModels)) { mongooseModels = [mongooseModels]; } const graffitiModels = model.getModels(mongooseModels); const fields = getFields(graffitiModels, options); return new GraphQLSchema(fields); }
javascript
function getSchema(mongooseModels, options) { if (!isArray(mongooseModels)) { mongooseModels = [mongooseModels]; } const graffitiModels = model.getModels(mongooseModels); const fields = getFields(graffitiModels, options); return new GraphQLSchema(fields); }
[ "function", "getSchema", "(", "mongooseModels", ",", "options", ")", "{", "if", "(", "!", "isArray", "(", "mongooseModels", ")", ")", "{", "mongooseModels", "=", "[", "mongooseModels", "]", ";", "}", "const", "graffitiModels", "=", "model", ".", "getModels", "(", "mongooseModels", ")", ";", "const", "fields", "=", "getFields", "(", "graffitiModels", ",", "options", ")", ";", "return", "new", "GraphQLSchema", "(", "fields", ")", ";", "}" ]
Returns a GraphQL schema including query and mutation fields @param {Array} mongooseModels @param {Object} options @return {GraphQLSchema}
[ "Returns", "a", "GraphQL", "schema", "including", "query", "and", "mutation", "fields" ]
414c91e4b2081bf0d14ecd2de545f621713f5da7
https://github.com/RisingStack/graffiti-mongoose/blob/414c91e4b2081bf0d14ecd2de545f621713f5da7/src/schema/schema.js#L321-L328
train
FWeinb/grunt-svgstore
tasks/svgstore.js
function (name) { var dotPos = name.indexOf('.'); if (dotPos > -1) { name = name.substring(0, dotPos); } return name; }
javascript
function (name) { var dotPos = name.indexOf('.'); if (dotPos > -1) { name = name.substring(0, dotPos); } return name; }
[ "function", "(", "name", ")", "{", "var", "dotPos", "=", "name", ".", "indexOf", "(", "'.'", ")", ";", "if", "(", "dotPos", ">", "-", "1", ")", "{", "name", "=", "name", ".", "substring", "(", "0", ",", "dotPos", ")", ";", "}", "return", "name", ";", "}" ]
Default function used to extract an id from a name
[ "Default", "function", "used", "to", "extract", "an", "id", "from", "a", "name" ]
e9fa79cb44925bb85af31db55bc925aed536907d
https://github.com/FWeinb/grunt-svgstore/blob/e9fa79cb44925bb85af31db55bc925aed536907d/tasks/svgstore.js#L46-L52
train
taptapship/wiredep
lib/detect-dependencies.js
detectDependencies
function detectDependencies(config) { var allDependencies = {}; if (config.get('dependencies')) { $._.assign(allDependencies, config.get('bower.json').dependencies); } if (config.get('dev-dependencies')) { $._.assign(allDependencies, config.get('bower.json').devDependencies); } if (config.get('include-self')) { allDependencies[config.get('bower.json').name] = config.get('bower.json').version; } $._.each(allDependencies, gatherInfo(config)); config.set('global-dependencies-sorted', filterExcludedDependencies( config.get('detectable-file-types'). reduce(function (acc, fileType) { if (!acc[fileType]) { acc[fileType] = prioritizeDependencies(config, '.' + fileType); } return acc; }, {}), config.get('exclude') )); return config; }
javascript
function detectDependencies(config) { var allDependencies = {}; if (config.get('dependencies')) { $._.assign(allDependencies, config.get('bower.json').dependencies); } if (config.get('dev-dependencies')) { $._.assign(allDependencies, config.get('bower.json').devDependencies); } if (config.get('include-self')) { allDependencies[config.get('bower.json').name] = config.get('bower.json').version; } $._.each(allDependencies, gatherInfo(config)); config.set('global-dependencies-sorted', filterExcludedDependencies( config.get('detectable-file-types'). reduce(function (acc, fileType) { if (!acc[fileType]) { acc[fileType] = prioritizeDependencies(config, '.' + fileType); } return acc; }, {}), config.get('exclude') )); return config; }
[ "function", "detectDependencies", "(", "config", ")", "{", "var", "allDependencies", "=", "{", "}", ";", "if", "(", "config", ".", "get", "(", "'dependencies'", ")", ")", "{", "$", ".", "_", ".", "assign", "(", "allDependencies", ",", "config", ".", "get", "(", "'bower.json'", ")", ".", "dependencies", ")", ";", "}", "if", "(", "config", ".", "get", "(", "'dev-dependencies'", ")", ")", "{", "$", ".", "_", ".", "assign", "(", "allDependencies", ",", "config", ".", "get", "(", "'bower.json'", ")", ".", "devDependencies", ")", ";", "}", "if", "(", "config", ".", "get", "(", "'include-self'", ")", ")", "{", "allDependencies", "[", "config", ".", "get", "(", "'bower.json'", ")", ".", "name", "]", "=", "config", ".", "get", "(", "'bower.json'", ")", ".", "version", ";", "}", "$", ".", "_", ".", "each", "(", "allDependencies", ",", "gatherInfo", "(", "config", ")", ")", ";", "config", ".", "set", "(", "'global-dependencies-sorted'", ",", "filterExcludedDependencies", "(", "config", ".", "get", "(", "'detectable-file-types'", ")", ".", "reduce", "(", "function", "(", "acc", ",", "fileType", ")", "{", "if", "(", "!", "acc", "[", "fileType", "]", ")", "{", "acc", "[", "fileType", "]", "=", "prioritizeDependencies", "(", "config", ",", "'.'", "+", "fileType", ")", ";", "}", "return", "acc", ";", "}", ",", "{", "}", ")", ",", "config", ".", "get", "(", "'exclude'", ")", ")", ")", ";", "return", "config", ";", "}" ]
Detect dependencies of the components from `bower.json`. @param {object} config the global configuration object. @return {object} config
[ "Detect", "dependencies", "of", "the", "components", "from", "bower", ".", "json", "." ]
0c247f93656147789c6aba5d8fb8decd45ea449c
https://github.com/taptapship/wiredep/blob/0c247f93656147789c6aba5d8fb8decd45ea449c/lib/detect-dependencies.js#L19-L48
train
taptapship/wiredep
lib/inject-dependencies.js
injectDependencies
function injectDependencies(globalConfig) { config = globalConfig; var stream = config.get('stream'); globalDependenciesSorted = config.get('global-dependencies-sorted'); ignorePath = config.get('ignore-path'); fileTypes = config.get('file-types'); if (stream.src) { config.set('stream', { src: injectScriptsStream(stream.path, stream.src, stream.fileType), fileType: stream.fileType }); } else { config.get('src').forEach(injectScripts); } return config; }
javascript
function injectDependencies(globalConfig) { config = globalConfig; var stream = config.get('stream'); globalDependenciesSorted = config.get('global-dependencies-sorted'); ignorePath = config.get('ignore-path'); fileTypes = config.get('file-types'); if (stream.src) { config.set('stream', { src: injectScriptsStream(stream.path, stream.src, stream.fileType), fileType: stream.fileType }); } else { config.get('src').forEach(injectScripts); } return config; }
[ "function", "injectDependencies", "(", "globalConfig", ")", "{", "config", "=", "globalConfig", ";", "var", "stream", "=", "config", ".", "get", "(", "'stream'", ")", ";", "globalDependenciesSorted", "=", "config", ".", "get", "(", "'global-dependencies-sorted'", ")", ";", "ignorePath", "=", "config", ".", "get", "(", "'ignore-path'", ")", ";", "fileTypes", "=", "config", ".", "get", "(", "'file-types'", ")", ";", "if", "(", "stream", ".", "src", ")", "{", "config", ".", "set", "(", "'stream'", ",", "{", "src", ":", "injectScriptsStream", "(", "stream", ".", "path", ",", "stream", ".", "src", ",", "stream", ".", "fileType", ")", ",", "fileType", ":", "stream", ".", "fileType", "}", ")", ";", "}", "else", "{", "config", ".", "get", "(", "'src'", ")", ".", "forEach", "(", "injectScripts", ")", ";", "}", "return", "config", ";", "}" ]
Inject dependencies into the specified source file. @param {object} globalConfig the global configuration object. @return {object} config
[ "Inject", "dependencies", "into", "the", "specified", "source", "file", "." ]
0c247f93656147789c6aba5d8fb8decd45ea449c
https://github.com/taptapship/wiredep/blob/0c247f93656147789c6aba5d8fb8decd45ea449c/lib/inject-dependencies.js#L20-L38
train
smartystreets/jquery.liveaddress
src/liveAddressPlugin.js
uiTagOffset
function uiTagOffset(corners) { return { top: corners.top + corners.height / 2 - 10, left: corners.right - 6 }; }
javascript
function uiTagOffset(corners) { return { top: corners.top + corners.height / 2 - 10, left: corners.right - 6 }; }
[ "function", "uiTagOffset", "(", "corners", ")", "{", "return", "{", "top", ":", "corners", ".", "top", "+", "corners", ".", "height", "/", "2", "-", "10", ",", "left", ":", "corners", ".", "right", "-", "6", "}", ";", "}" ]
Computes where the little checkmark tag of the UI goes, relative to the boundaries of the last field
[ "Computes", "where", "the", "little", "checkmark", "tag", "of", "the", "UI", "goes", "relative", "to", "the", "boundaries", "of", "the", "last", "field" ]
1e76580ada9405797f5472eb54571b68d5a64a27
https://github.com/smartystreets/jquery.liveaddress/blob/1e76580ada9405797f5472eb54571b68d5a64a27/src/liveAddressPlugin.js#L1052-L1057
train
smartystreets/jquery.liveaddress
src/liveAddressPlugin.js
filterDomElement
function filterDomElement(domElement, names, labels) { /* Where we look to find a match, in this order: name, id, <label> tags, placeholder, title Our searches first conduct fairly liberal "contains" searches: if the attribute even contains the name or label, we map it. The names and labels we choose to find are very particular. */ var name = lowercase(domElement.name); var id = lowercase(domElement.id); var selectorSafeID = id.replace(/[\[|\]|\(|\)|\:|\'|\"|\=|\||\#|\.|\!|\||\@|\^|\&|\*]/g, "\\\\$&"); var placeholder = lowercase(domElement.placeholder); var title = lowercase(domElement.title); // First look through name and id attributes of the element, the most common for (var i = 0; i < names.length; i++) if (name.indexOf(names[i]) > -1 || id.indexOf(names[i]) > -1) return true; // If we can't find it in name or id, look at labels associated to the element. // Webkit automatically associates labels with form elements for us. But for other // browsers, we have to find them manually, which this next block does. if (!("labels" in domElement)) { var lbl = $("label[for=\"" + selectorSafeID + "\"]")[0] || $(domElement).parents("label")[0]; domElement.labels = !lbl ? [] : [lbl]; } // Iterate through the <label> tags now to search for a match. for (var i = 0; i < domElement.labels.length; i++) { // This inner loop compares each label value with what we're looking for for (var j = 0; j < labels.length; j++) if ($(domElement.labels[i]).text().toLowerCase().indexOf(labels[j]) > -1) return true; } // Still not found? Then look in "placeholder" or "title"... for (var i = 0; i < labels.length; i++) if (placeholder.indexOf(labels[i]) > -1 || title.indexOf(labels[i]) > -1) return true; // Got all the way to here? Probably not a match then. return false; }
javascript
function filterDomElement(domElement, names, labels) { /* Where we look to find a match, in this order: name, id, <label> tags, placeholder, title Our searches first conduct fairly liberal "contains" searches: if the attribute even contains the name or label, we map it. The names and labels we choose to find are very particular. */ var name = lowercase(domElement.name); var id = lowercase(domElement.id); var selectorSafeID = id.replace(/[\[|\]|\(|\)|\:|\'|\"|\=|\||\#|\.|\!|\||\@|\^|\&|\*]/g, "\\\\$&"); var placeholder = lowercase(domElement.placeholder); var title = lowercase(domElement.title); // First look through name and id attributes of the element, the most common for (var i = 0; i < names.length; i++) if (name.indexOf(names[i]) > -1 || id.indexOf(names[i]) > -1) return true; // If we can't find it in name or id, look at labels associated to the element. // Webkit automatically associates labels with form elements for us. But for other // browsers, we have to find them manually, which this next block does. if (!("labels" in domElement)) { var lbl = $("label[for=\"" + selectorSafeID + "\"]")[0] || $(domElement).parents("label")[0]; domElement.labels = !lbl ? [] : [lbl]; } // Iterate through the <label> tags now to search for a match. for (var i = 0; i < domElement.labels.length; i++) { // This inner loop compares each label value with what we're looking for for (var j = 0; j < labels.length; j++) if ($(domElement.labels[i]).text().toLowerCase().indexOf(labels[j]) > -1) return true; } // Still not found? Then look in "placeholder" or "title"... for (var i = 0; i < labels.length; i++) if (placeholder.indexOf(labels[i]) > -1 || title.indexOf(labels[i]) > -1) return true; // Got all the way to here? Probably not a match then. return false; }
[ "function", "filterDomElement", "(", "domElement", ",", "names", ",", "labels", ")", "{", "var", "name", "=", "lowercase", "(", "domElement", ".", "name", ")", ";", "var", "id", "=", "lowercase", "(", "domElement", ".", "id", ")", ";", "var", "selectorSafeID", "=", "id", ".", "replace", "(", "/", "[\\[|\\]|\\(|\\)|\\:|\\'|\\\"|\\=|\\||\\#|\\.|\\!|\\||\\@|\\^|\\&|\\*]", "/", "g", ",", "\"\\\\\\\\$&\"", ")", ";", "\\\\", "\\\\", "var", "placeholder", "=", "lowercase", "(", "domElement", ".", "placeholder", ")", ";", "var", "title", "=", "lowercase", "(", "domElement", ".", "title", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "names", ".", "length", ";", "i", "++", ")", "if", "(", "name", ".", "indexOf", "(", "names", "[", "i", "]", ")", ">", "-", "1", "||", "id", ".", "indexOf", "(", "names", "[", "i", "]", ")", ">", "-", "1", ")", "return", "true", ";", "if", "(", "!", "(", "\"labels\"", "in", "domElement", ")", ")", "{", "var", "lbl", "=", "$", "(", "\"label[for=\\\"\"", "+", "\\\"", "+", "selectorSafeID", ")", "[", "\"\\\"]\"", "]", "||", "\\\"", ";", "0", "}", "$", "(", "domElement", ")", ".", "parents", "(", "\"label\"", ")", "[", "0", "]", "}" ]
This function is used to find and properly map elements to their field type
[ "This", "function", "is", "used", "to", "find", "and", "properly", "map", "elements", "to", "their", "field", "type" ]
1e76580ada9405797f5472eb54571b68d5a64a27
https://github.com/smartystreets/jquery.liveaddress/blob/1e76580ada9405797f5472eb54571b68d5a64a27/src/liveAddressPlugin.js#L1060-L1103
train
smartystreets/jquery.liveaddress
src/liveAddressPlugin.js
turnOffAllClicks
function turnOffAllClicks(selectors) { if (Array.isArray(selectors) || typeof selectors == "object") { for (var selector in selectors) { if (selectors.hasOwnProperty(selector)) { $("body").off("click", selectors[selector]); } } } else if (typeof selectors === "string") { $("body").off("click", selectors); } else { alert("ERROR: Not an array, string, or object passed in to turn off all clicks"); } }
javascript
function turnOffAllClicks(selectors) { if (Array.isArray(selectors) || typeof selectors == "object") { for (var selector in selectors) { if (selectors.hasOwnProperty(selector)) { $("body").off("click", selectors[selector]); } } } else if (typeof selectors === "string") { $("body").off("click", selectors); } else { alert("ERROR: Not an array, string, or object passed in to turn off all clicks"); } }
[ "function", "turnOffAllClicks", "(", "selectors", ")", "{", "if", "(", "Array", ".", "isArray", "(", "selectors", ")", "||", "typeof", "selectors", "==", "\"object\"", ")", "{", "for", "(", "var", "selector", "in", "selectors", ")", "{", "if", "(", "selectors", ".", "hasOwnProperty", "(", "selector", ")", ")", "{", "$", "(", "\"body\"", ")", ".", "off", "(", "\"click\"", ",", "selectors", "[", "selector", "]", ")", ";", "}", "}", "}", "else", "if", "(", "typeof", "selectors", "===", "\"string\"", ")", "{", "$", "(", "\"body\"", ")", ".", "off", "(", "\"click\"", ",", "selectors", ")", ";", "}", "else", "{", "alert", "(", "\"ERROR: Not an array, string, or object passed in to turn off all clicks\"", ")", ";", "}", "}" ]
When we're done with a "pop-up" where the user chooses what to do, we need to remove all other events bound on that whole "pop-up" so that it doesn't interfere with any future "pop-ups".
[ "When", "we", "re", "done", "with", "a", "pop", "-", "up", "where", "the", "user", "chooses", "what", "to", "do", "we", "need", "to", "remove", "all", "other", "events", "bound", "on", "that", "whole", "pop", "-", "up", "so", "that", "it", "doesn", "t", "interfere", "with", "any", "future", "pop", "-", "ups", "." ]
1e76580ada9405797f5472eb54571b68d5a64a27
https://github.com/smartystreets/jquery.liveaddress/blob/1e76580ada9405797f5472eb54571b68d5a64a27/src/liveAddressPlugin.js#L1120-L1132
train
smartystreets/jquery.liveaddress
src/liveAddressPlugin.js
function (invokeOn, invokeFunction) { if (invokeOn && typeof invokeOn !== "function" && invokeFunction) { if (invokeFunction == "click") { setTimeout(function () { $(invokeOn).click(); // Very particular: we MUST fire the native "click" event! }, 5); } else if (invokeFunction == "submit") $(invokeOn).submit(); // For submit(), we have to use jQuery's, so that all its submit handlers fire. } }
javascript
function (invokeOn, invokeFunction) { if (invokeOn && typeof invokeOn !== "function" && invokeFunction) { if (invokeFunction == "click") { setTimeout(function () { $(invokeOn).click(); // Very particular: we MUST fire the native "click" event! }, 5); } else if (invokeFunction == "submit") $(invokeOn).submit(); // For submit(), we have to use jQuery's, so that all its submit handlers fire. } }
[ "function", "(", "invokeOn", ",", "invokeFunction", ")", "{", "if", "(", "invokeOn", "&&", "typeof", "invokeOn", "!==", "\"function\"", "&&", "invokeFunction", ")", "{", "if", "(", "invokeFunction", "==", "\"click\"", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "$", "(", "invokeOn", ")", ".", "click", "(", ")", ";", "}", ",", "5", ")", ";", "}", "else", "if", "(", "invokeFunction", "==", "\"submit\"", ")", "$", "(", "invokeOn", ")", ".", "submit", "(", ")", ";", "}", "}" ]
Submits a form by calling `click` on a button element or `submit` on a form element
[ "Submits", "a", "form", "by", "calling", "click", "on", "a", "button", "element", "or", "submit", "on", "a", "form", "element" ]
1e76580ada9405797f5472eb54571b68d5a64a27
https://github.com/smartystreets/jquery.liveaddress/blob/1e76580ada9405797f5472eb54571b68d5a64a27/src/liveAddressPlugin.js#L2830-L2839
train
Modernizr/customizr
src/utils.js
function (options, patterns) { // Return all matching filepaths. var matches = processPatterns(patterns, function (pattern) { // Find all matching files for this pattern. return glob.sync(pattern, options); }); // Filter result set? if (options.filter) { matches = matches.filter(function (filepath) { filepath = path.join(options.cwd || '', filepath); try { if (typeof options.filter === 'function') { return options.filter(filepath); } else { // If the file is of the right type and exists, this should work. return fs.statSync(filepath)[options.filter](); } } catch (e) { // Otherwise, it's probably not the right type. return false; } }); } return matches; }
javascript
function (options, patterns) { // Return all matching filepaths. var matches = processPatterns(patterns, function (pattern) { // Find all matching files for this pattern. return glob.sync(pattern, options); }); // Filter result set? if (options.filter) { matches = matches.filter(function (filepath) { filepath = path.join(options.cwd || '', filepath); try { if (typeof options.filter === 'function') { return options.filter(filepath); } else { // If the file is of the right type and exists, this should work. return fs.statSync(filepath)[options.filter](); } } catch (e) { // Otherwise, it's probably not the right type. return false; } }); } return matches; }
[ "function", "(", "options", ",", "patterns", ")", "{", "var", "matches", "=", "processPatterns", "(", "patterns", ",", "function", "(", "pattern", ")", "{", "return", "glob", ".", "sync", "(", "pattern", ",", "options", ")", ";", "}", ")", ";", "if", "(", "options", ".", "filter", ")", "{", "matches", "=", "matches", ".", "filter", "(", "function", "(", "filepath", ")", "{", "filepath", "=", "path", ".", "join", "(", "options", ".", "cwd", "||", "''", ",", "filepath", ")", ";", "try", "{", "if", "(", "typeof", "options", ".", "filter", "===", "'function'", ")", "{", "return", "options", ".", "filter", "(", "filepath", ")", ";", "}", "else", "{", "return", "fs", ".", "statSync", "(", "filepath", ")", "[", "options", ".", "filter", "]", "(", ")", ";", "}", "}", "catch", "(", "e", ")", "{", "return", "false", ";", "}", "}", ")", ";", "}", "return", "matches", ";", "}" ]
Return an array of all file paths that match the given wildcard patterns.
[ "Return", "an", "array", "of", "all", "file", "paths", "that", "match", "the", "given", "wildcard", "patterns", "." ]
01541efc72bf08fdaf127270aad1abcc26968398
https://github.com/Modernizr/customizr/blob/01541efc72bf08fdaf127270aad1abcc26968398/src/utils.js#L59-L86
train
immersive-web/cardboard-vr-display
src/sensor-fusion/fusion-pose-sensor.js
FusionPoseSensor
function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) { this.yawOnly = yawOnly; this.accelerometer = new MathUtil.Vector3(); this.gyroscope = new MathUtil.Vector3(); this.filter = new ComplementaryFilter(kFilter, isDebug); this.posePredictor = new PosePredictor(predictionTime, isDebug); this.isFirefoxAndroid = Util.isFirefoxAndroid(); this.isIOS = Util.isIOS(); // Chrome as of m66 started reporting `rotationRate` in degrees rather // than radians, to be consistent with other browsers. // https://github.com/immersive-web/cardboard-vr-display/issues/18 let chromeVersion = Util.getChromeVersion(); this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66; // In Chrome m65 there's a regression of devicemotion events. Fallback // to using deviceorientation for these specific builds. More information // at `Util.isChromeWithoutDeviceMotion`. this.isWithoutDeviceMotion = Util.isChromeWithoutDeviceMotion(); this.filterToWorldQ = new MathUtil.Quaternion(); // Set the filter to world transform, depending on OS. if (Util.isIOS()) { this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), Math.PI / 2); } else { this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), -Math.PI / 2); } this.inverseWorldToScreenQ = new MathUtil.Quaternion(); this.worldToScreenQ = new MathUtil.Quaternion(); this.originalPoseAdjustQ = new MathUtil.Quaternion(); this.originalPoseAdjustQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1), -window.orientation * Math.PI / 180); this.setScreenTransform_(); // Adjust this filter for being in landscape mode. if (Util.isLandscapeMode()) { this.filterToWorldQ.multiply(this.inverseWorldToScreenQ); } // Keep track of a reset transform for resetSensor. this.resetQ = new MathUtil.Quaternion(); this.orientationOut_ = new Float32Array(4); this.start(); }
javascript
function FusionPoseSensor(kFilter, predictionTime, yawOnly, isDebug) { this.yawOnly = yawOnly; this.accelerometer = new MathUtil.Vector3(); this.gyroscope = new MathUtil.Vector3(); this.filter = new ComplementaryFilter(kFilter, isDebug); this.posePredictor = new PosePredictor(predictionTime, isDebug); this.isFirefoxAndroid = Util.isFirefoxAndroid(); this.isIOS = Util.isIOS(); // Chrome as of m66 started reporting `rotationRate` in degrees rather // than radians, to be consistent with other browsers. // https://github.com/immersive-web/cardboard-vr-display/issues/18 let chromeVersion = Util.getChromeVersion(); this.isDeviceMotionInRadians = !this.isIOS && chromeVersion && chromeVersion < 66; // In Chrome m65 there's a regression of devicemotion events. Fallback // to using deviceorientation for these specific builds. More information // at `Util.isChromeWithoutDeviceMotion`. this.isWithoutDeviceMotion = Util.isChromeWithoutDeviceMotion(); this.filterToWorldQ = new MathUtil.Quaternion(); // Set the filter to world transform, depending on OS. if (Util.isIOS()) { this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), Math.PI / 2); } else { this.filterToWorldQ.setFromAxisAngle(new MathUtil.Vector3(1, 0, 0), -Math.PI / 2); } this.inverseWorldToScreenQ = new MathUtil.Quaternion(); this.worldToScreenQ = new MathUtil.Quaternion(); this.originalPoseAdjustQ = new MathUtil.Quaternion(); this.originalPoseAdjustQ.setFromAxisAngle(new MathUtil.Vector3(0, 0, 1), -window.orientation * Math.PI / 180); this.setScreenTransform_(); // Adjust this filter for being in landscape mode. if (Util.isLandscapeMode()) { this.filterToWorldQ.multiply(this.inverseWorldToScreenQ); } // Keep track of a reset transform for resetSensor. this.resetQ = new MathUtil.Quaternion(); this.orientationOut_ = new Float32Array(4); this.start(); }
[ "function", "FusionPoseSensor", "(", "kFilter", ",", "predictionTime", ",", "yawOnly", ",", "isDebug", ")", "{", "this", ".", "yawOnly", "=", "yawOnly", ";", "this", ".", "accelerometer", "=", "new", "MathUtil", ".", "Vector3", "(", ")", ";", "this", ".", "gyroscope", "=", "new", "MathUtil", ".", "Vector3", "(", ")", ";", "this", ".", "filter", "=", "new", "ComplementaryFilter", "(", "kFilter", ",", "isDebug", ")", ";", "this", ".", "posePredictor", "=", "new", "PosePredictor", "(", "predictionTime", ",", "isDebug", ")", ";", "this", ".", "isFirefoxAndroid", "=", "Util", ".", "isFirefoxAndroid", "(", ")", ";", "this", ".", "isIOS", "=", "Util", ".", "isIOS", "(", ")", ";", "let", "chromeVersion", "=", "Util", ".", "getChromeVersion", "(", ")", ";", "this", ".", "isDeviceMotionInRadians", "=", "!", "this", ".", "isIOS", "&&", "chromeVersion", "&&", "chromeVersion", "<", "66", ";", "this", ".", "isWithoutDeviceMotion", "=", "Util", ".", "isChromeWithoutDeviceMotion", "(", ")", ";", "this", ".", "filterToWorldQ", "=", "new", "MathUtil", ".", "Quaternion", "(", ")", ";", "if", "(", "Util", ".", "isIOS", "(", ")", ")", "{", "this", ".", "filterToWorldQ", ".", "setFromAxisAngle", "(", "new", "MathUtil", ".", "Vector3", "(", "1", ",", "0", ",", "0", ")", ",", "Math", ".", "PI", "/", "2", ")", ";", "}", "else", "{", "this", ".", "filterToWorldQ", ".", "setFromAxisAngle", "(", "new", "MathUtil", ".", "Vector3", "(", "1", ",", "0", ",", "0", ")", ",", "-", "Math", ".", "PI", "/", "2", ")", ";", "}", "this", ".", "inverseWorldToScreenQ", "=", "new", "MathUtil", ".", "Quaternion", "(", ")", ";", "this", ".", "worldToScreenQ", "=", "new", "MathUtil", ".", "Quaternion", "(", ")", ";", "this", ".", "originalPoseAdjustQ", "=", "new", "MathUtil", ".", "Quaternion", "(", ")", ";", "this", ".", "originalPoseAdjustQ", ".", "setFromAxisAngle", "(", "new", "MathUtil", ".", "Vector3", "(", "0", ",", "0", ",", "1", ")", ",", "-", "window", ".", "orientation", "*", "Math", ".", "PI", "/", "180", ")", ";", "this", ".", "setScreenTransform_", "(", ")", ";", "if", "(", "Util", ".", "isLandscapeMode", "(", ")", ")", "{", "this", ".", "filterToWorldQ", ".", "multiply", "(", "this", ".", "inverseWorldToScreenQ", ")", ";", "}", "this", ".", "resetQ", "=", "new", "MathUtil", ".", "Quaternion", "(", ")", ";", "this", ".", "orientationOut_", "=", "new", "Float32Array", "(", "4", ")", ";", "this", ".", "start", "(", ")", ";", "}" ]
The pose sensor, implemented using DeviceMotion APIs. @param {number} kFilter @param {number} predictionTime @param {boolean} yawOnly @param {boolean} isDebug
[ "The", "pose", "sensor", "implemented", "using", "DeviceMotion", "APIs", "." ]
de59375309e637edbd3fd5e5213eac602930bb2b
https://github.com/immersive-web/cardboard-vr-display/blob/de59375309e637edbd3fd5e5213eac602930bb2b/src/sensor-fusion/fusion-pose-sensor.js#L28-L76
train
immersive-web/cardboard-vr-display
src/device-info.js
DeviceInfo
function DeviceInfo(deviceParams, additionalViewers) { this.viewer = Viewers.CardboardV2; this.updateDeviceParams(deviceParams); this.distortion = new Distortion(this.viewer.distortionCoefficients); for (var i = 0; i < additionalViewers.length; i++) { var viewer = additionalViewers[i]; Viewers[viewer.id] = new CardboardViewer(viewer); } }
javascript
function DeviceInfo(deviceParams, additionalViewers) { this.viewer = Viewers.CardboardV2; this.updateDeviceParams(deviceParams); this.distortion = new Distortion(this.viewer.distortionCoefficients); for (var i = 0; i < additionalViewers.length; i++) { var viewer = additionalViewers[i]; Viewers[viewer.id] = new CardboardViewer(viewer); } }
[ "function", "DeviceInfo", "(", "deviceParams", ",", "additionalViewers", ")", "{", "this", ".", "viewer", "=", "Viewers", ".", "CardboardV2", ";", "this", ".", "updateDeviceParams", "(", "deviceParams", ")", ";", "this", ".", "distortion", "=", "new", "Distortion", "(", "this", ".", "viewer", ".", "distortionCoefficients", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "additionalViewers", ".", "length", ";", "i", "++", ")", "{", "var", "viewer", "=", "additionalViewers", "[", "i", "]", ";", "Viewers", "[", "viewer", ".", "id", "]", "=", "new", "CardboardViewer", "(", "viewer", ")", ";", "}", "}" ]
Manages information about the device and the viewer. deviceParams indicates the parameters of the device to use (generally obtained from dpdb.getDeviceParams()). Can be null to mean no device params were found.
[ "Manages", "information", "about", "the", "device", "and", "the", "viewer", "." ]
de59375309e637edbd3fd5e5213eac602930bb2b
https://github.com/immersive-web/cardboard-vr-display/blob/de59375309e637edbd3fd5e5213eac602930bb2b/src/device-info.js#L84-L92
train
immersive-web/cardboard-vr-display
src/cardboard-distorter.js
CardboardDistorter
function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) { this.gl = gl; this.cardboardUI = cardboardUI; this.bufferScale = bufferScale; this.dirtySubmitFrameBindings = dirtySubmitFrameBindings; this.ctxAttribs = gl.getContextAttributes(); this.meshWidth = 20; this.meshHeight = 20; this.bufferWidth = gl.drawingBufferWidth; this.bufferHeight = gl.drawingBufferHeight; // Patching support this.realBindFramebuffer = gl.bindFramebuffer; this.realEnable = gl.enable; this.realDisable = gl.disable; this.realColorMask = gl.colorMask; this.realClearColor = gl.clearColor; this.realViewport = gl.viewport; if (!Util.isIOS()) { this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width'); this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height'); } this.isPatched = false; // State tracking this.lastBoundFramebuffer = null; this.cullFace = false; this.depthTest = false; this.blend = false; this.scissorTest = false; this.stencilTest = false; this.viewport = [0, 0, 0, 0]; this.colorMask = [true, true, true, true]; this.clearColor = [0, 0, 0, 0]; this.attribs = { position: 0, texCoord: 1 }; this.program = Util.linkProgram(gl, distortionVS, distortionFS, this.attribs); this.uniforms = Util.getProgramUniforms(gl, this.program); this.viewportOffsetScale = new Float32Array(8); this.setTextureBounds(); this.vertexBuffer = gl.createBuffer(); this.indexBuffer = gl.createBuffer(); this.indexCount = 0; this.renderTarget = gl.createTexture(); this.framebuffer = gl.createFramebuffer(); this.depthStencilBuffer = null; this.depthBuffer = null; this.stencilBuffer = null; if (this.ctxAttribs.depth && this.ctxAttribs.stencil) { this.depthStencilBuffer = gl.createRenderbuffer(); } else if (this.ctxAttribs.depth) { this.depthBuffer = gl.createRenderbuffer(); } else if (this.ctxAttribs.stencil) { this.stencilBuffer = gl.createRenderbuffer(); } this.patch(); this.onResize(); }
javascript
function CardboardDistorter(gl, cardboardUI, bufferScale, dirtySubmitFrameBindings) { this.gl = gl; this.cardboardUI = cardboardUI; this.bufferScale = bufferScale; this.dirtySubmitFrameBindings = dirtySubmitFrameBindings; this.ctxAttribs = gl.getContextAttributes(); this.meshWidth = 20; this.meshHeight = 20; this.bufferWidth = gl.drawingBufferWidth; this.bufferHeight = gl.drawingBufferHeight; // Patching support this.realBindFramebuffer = gl.bindFramebuffer; this.realEnable = gl.enable; this.realDisable = gl.disable; this.realColorMask = gl.colorMask; this.realClearColor = gl.clearColor; this.realViewport = gl.viewport; if (!Util.isIOS()) { this.realCanvasWidth = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'width'); this.realCanvasHeight = Object.getOwnPropertyDescriptor(gl.canvas.__proto__, 'height'); } this.isPatched = false; // State tracking this.lastBoundFramebuffer = null; this.cullFace = false; this.depthTest = false; this.blend = false; this.scissorTest = false; this.stencilTest = false; this.viewport = [0, 0, 0, 0]; this.colorMask = [true, true, true, true]; this.clearColor = [0, 0, 0, 0]; this.attribs = { position: 0, texCoord: 1 }; this.program = Util.linkProgram(gl, distortionVS, distortionFS, this.attribs); this.uniforms = Util.getProgramUniforms(gl, this.program); this.viewportOffsetScale = new Float32Array(8); this.setTextureBounds(); this.vertexBuffer = gl.createBuffer(); this.indexBuffer = gl.createBuffer(); this.indexCount = 0; this.renderTarget = gl.createTexture(); this.framebuffer = gl.createFramebuffer(); this.depthStencilBuffer = null; this.depthBuffer = null; this.stencilBuffer = null; if (this.ctxAttribs.depth && this.ctxAttribs.stencil) { this.depthStencilBuffer = gl.createRenderbuffer(); } else if (this.ctxAttribs.depth) { this.depthBuffer = gl.createRenderbuffer(); } else if (this.ctxAttribs.stencil) { this.stencilBuffer = gl.createRenderbuffer(); } this.patch(); this.onResize(); }
[ "function", "CardboardDistorter", "(", "gl", ",", "cardboardUI", ",", "bufferScale", ",", "dirtySubmitFrameBindings", ")", "{", "this", ".", "gl", "=", "gl", ";", "this", ".", "cardboardUI", "=", "cardboardUI", ";", "this", ".", "bufferScale", "=", "bufferScale", ";", "this", ".", "dirtySubmitFrameBindings", "=", "dirtySubmitFrameBindings", ";", "this", ".", "ctxAttribs", "=", "gl", ".", "getContextAttributes", "(", ")", ";", "this", ".", "meshWidth", "=", "20", ";", "this", ".", "meshHeight", "=", "20", ";", "this", ".", "bufferWidth", "=", "gl", ".", "drawingBufferWidth", ";", "this", ".", "bufferHeight", "=", "gl", ".", "drawingBufferHeight", ";", "this", ".", "realBindFramebuffer", "=", "gl", ".", "bindFramebuffer", ";", "this", ".", "realEnable", "=", "gl", ".", "enable", ";", "this", ".", "realDisable", "=", "gl", ".", "disable", ";", "this", ".", "realColorMask", "=", "gl", ".", "colorMask", ";", "this", ".", "realClearColor", "=", "gl", ".", "clearColor", ";", "this", ".", "realViewport", "=", "gl", ".", "viewport", ";", "if", "(", "!", "Util", ".", "isIOS", "(", ")", ")", "{", "this", ".", "realCanvasWidth", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "gl", ".", "canvas", ".", "__proto__", ",", "'width'", ")", ";", "this", ".", "realCanvasHeight", "=", "Object", ".", "getOwnPropertyDescriptor", "(", "gl", ".", "canvas", ".", "__proto__", ",", "'height'", ")", ";", "}", "this", ".", "isPatched", "=", "false", ";", "this", ".", "lastBoundFramebuffer", "=", "null", ";", "this", ".", "cullFace", "=", "false", ";", "this", ".", "depthTest", "=", "false", ";", "this", ".", "blend", "=", "false", ";", "this", ".", "scissorTest", "=", "false", ";", "this", ".", "stencilTest", "=", "false", ";", "this", ".", "viewport", "=", "[", "0", ",", "0", ",", "0", ",", "0", "]", ";", "this", ".", "colorMask", "=", "[", "true", ",", "true", ",", "true", ",", "true", "]", ";", "this", ".", "clearColor", "=", "[", "0", ",", "0", ",", "0", ",", "0", "]", ";", "this", ".", "attribs", "=", "{", "position", ":", "0", ",", "texCoord", ":", "1", "}", ";", "this", ".", "program", "=", "Util", ".", "linkProgram", "(", "gl", ",", "distortionVS", ",", "distortionFS", ",", "this", ".", "attribs", ")", ";", "this", ".", "uniforms", "=", "Util", ".", "getProgramUniforms", "(", "gl", ",", "this", ".", "program", ")", ";", "this", ".", "viewportOffsetScale", "=", "new", "Float32Array", "(", "8", ")", ";", "this", ".", "setTextureBounds", "(", ")", ";", "this", ".", "vertexBuffer", "=", "gl", ".", "createBuffer", "(", ")", ";", "this", ".", "indexBuffer", "=", "gl", ".", "createBuffer", "(", ")", ";", "this", ".", "indexCount", "=", "0", ";", "this", ".", "renderTarget", "=", "gl", ".", "createTexture", "(", ")", ";", "this", ".", "framebuffer", "=", "gl", ".", "createFramebuffer", "(", ")", ";", "this", ".", "depthStencilBuffer", "=", "null", ";", "this", ".", "depthBuffer", "=", "null", ";", "this", ".", "stencilBuffer", "=", "null", ";", "if", "(", "this", ".", "ctxAttribs", ".", "depth", "&&", "this", ".", "ctxAttribs", ".", "stencil", ")", "{", "this", ".", "depthStencilBuffer", "=", "gl", ".", "createRenderbuffer", "(", ")", ";", "}", "else", "if", "(", "this", ".", "ctxAttribs", ".", "depth", ")", "{", "this", ".", "depthBuffer", "=", "gl", ".", "createRenderbuffer", "(", ")", ";", "}", "else", "if", "(", "this", ".", "ctxAttribs", ".", "stencil", ")", "{", "this", ".", "stencilBuffer", "=", "gl", ".", "createRenderbuffer", "(", ")", ";", "}", "this", ".", "patch", "(", ")", ";", "this", ".", "onResize", "(", ")", ";", "}" ]
A mesh-based distorter. @param {WebGLRenderingContext} gl @param {CardboardUI?} cardboardUI; @param {number} bufferScale; @param {boolean} dirtySubmitFrameBindings;
[ "A", "mesh", "-", "based", "distorter", "." ]
de59375309e637edbd3fd5e5213eac602930bb2b
https://github.com/immersive-web/cardboard-vr-display/blob/de59375309e637edbd3fd5e5213eac602930bb2b/src/cardboard-distorter.js#L53-L125
train
immersive-web/cardboard-vr-display
src/sensor-fusion/pose-predictor.js
PosePredictor
function PosePredictor(predictionTimeS, isDebug) { this.predictionTimeS = predictionTimeS; this.isDebug = isDebug; // The quaternion corresponding to the previous state. this.previousQ = new MathUtil.Quaternion(); // Previous time a prediction occurred. this.previousTimestampS = null; // The delta quaternion that adjusts the current pose. this.deltaQ = new MathUtil.Quaternion(); // The output quaternion. this.outQ = new MathUtil.Quaternion(); }
javascript
function PosePredictor(predictionTimeS, isDebug) { this.predictionTimeS = predictionTimeS; this.isDebug = isDebug; // The quaternion corresponding to the previous state. this.previousQ = new MathUtil.Quaternion(); // Previous time a prediction occurred. this.previousTimestampS = null; // The delta quaternion that adjusts the current pose. this.deltaQ = new MathUtil.Quaternion(); // The output quaternion. this.outQ = new MathUtil.Quaternion(); }
[ "function", "PosePredictor", "(", "predictionTimeS", ",", "isDebug", ")", "{", "this", ".", "predictionTimeS", "=", "predictionTimeS", ";", "this", ".", "isDebug", "=", "isDebug", ";", "this", ".", "previousQ", "=", "new", "MathUtil", ".", "Quaternion", "(", ")", ";", "this", ".", "previousTimestampS", "=", "null", ";", "this", ".", "deltaQ", "=", "new", "MathUtil", ".", "Quaternion", "(", ")", ";", "this", ".", "outQ", "=", "new", "MathUtil", ".", "Quaternion", "(", ")", ";", "}" ]
Given an orientation and the gyroscope data, predicts the future orientation of the head. This makes rendering appear faster. Also see: http://msl.cs.uiuc.edu/~lavalle/papers/LavYerKatAnt14.pdf @param {Number} predictionTimeS time from head movement to the appearance of the corresponding image.
[ "Given", "an", "orientation", "and", "the", "gyroscope", "data", "predicts", "the", "future", "orientation", "of", "the", "head", ".", "This", "makes", "rendering", "appear", "faster", "." ]
de59375309e637edbd3fd5e5213eac602930bb2b
https://github.com/immersive-web/cardboard-vr-display/blob/de59375309e637edbd3fd5e5213eac602930bb2b/src/sensor-fusion/pose-predictor.js#L26-L39
train
immersive-web/cardboard-vr-display
src/cardboard-vr-display.js
CardboardVRDisplay
function CardboardVRDisplay(config) { var defaults = Util.extend({}, Options); config = Util.extend(defaults, config || {}); VRDisplay.call(this, { wakelock: config.MOBILE_WAKE_LOCK, }); this.config = config; this.displayName = 'Cardboard VRDisplay'; this.capabilities = new VRDisplayCapabilities({ hasPosition: false, hasOrientation: true, hasExternalDisplay: false, canPresent: true, maxLayers: 1 }); this.stageParameters = null; // "Private" members. this.bufferScale_ = this.config.BUFFER_SCALE; this.poseSensor_ = new PoseSensor(this.config); this.distorter_ = null; this.cardboardUI_ = null; this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this)); this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams(), config.ADDITIONAL_VIEWERS); this.viewerSelector_ = new ViewerSelector(config.DEFAULT_VIEWER); this.viewerSelector_.onChange(this.onViewerChanged_.bind(this)); // Set the correct initial viewer. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer()); if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) { this.rotateInstructions_ = new RotateInstructions(); } if (Util.isIOS()) { // Listen for resize events to workaround this awful Safari bug. window.addEventListener('resize', this.onResize_.bind(this)); } }
javascript
function CardboardVRDisplay(config) { var defaults = Util.extend({}, Options); config = Util.extend(defaults, config || {}); VRDisplay.call(this, { wakelock: config.MOBILE_WAKE_LOCK, }); this.config = config; this.displayName = 'Cardboard VRDisplay'; this.capabilities = new VRDisplayCapabilities({ hasPosition: false, hasOrientation: true, hasExternalDisplay: false, canPresent: true, maxLayers: 1 }); this.stageParameters = null; // "Private" members. this.bufferScale_ = this.config.BUFFER_SCALE; this.poseSensor_ = new PoseSensor(this.config); this.distorter_ = null; this.cardboardUI_ = null; this.dpdb_ = new Dpdb(this.config.DPDB_URL, this.onDeviceParamsUpdated_.bind(this)); this.deviceInfo_ = new DeviceInfo(this.dpdb_.getDeviceParams(), config.ADDITIONAL_VIEWERS); this.viewerSelector_ = new ViewerSelector(config.DEFAULT_VIEWER); this.viewerSelector_.onChange(this.onViewerChanged_.bind(this)); // Set the correct initial viewer. this.deviceInfo_.setViewer(this.viewerSelector_.getCurrentViewer()); if (!this.config.ROTATE_INSTRUCTIONS_DISABLED) { this.rotateInstructions_ = new RotateInstructions(); } if (Util.isIOS()) { // Listen for resize events to workaround this awful Safari bug. window.addEventListener('resize', this.onResize_.bind(this)); } }
[ "function", "CardboardVRDisplay", "(", "config", ")", "{", "var", "defaults", "=", "Util", ".", "extend", "(", "{", "}", ",", "Options", ")", ";", "config", "=", "Util", ".", "extend", "(", "defaults", ",", "config", "||", "{", "}", ")", ";", "VRDisplay", ".", "call", "(", "this", ",", "{", "wakelock", ":", "config", ".", "MOBILE_WAKE_LOCK", ",", "}", ")", ";", "this", ".", "config", "=", "config", ";", "this", ".", "displayName", "=", "'Cardboard VRDisplay'", ";", "this", ".", "capabilities", "=", "new", "VRDisplayCapabilities", "(", "{", "hasPosition", ":", "false", ",", "hasOrientation", ":", "true", ",", "hasExternalDisplay", ":", "false", ",", "canPresent", ":", "true", ",", "maxLayers", ":", "1", "}", ")", ";", "this", ".", "stageParameters", "=", "null", ";", "this", ".", "bufferScale_", "=", "this", ".", "config", ".", "BUFFER_SCALE", ";", "this", ".", "poseSensor_", "=", "new", "PoseSensor", "(", "this", ".", "config", ")", ";", "this", ".", "distorter_", "=", "null", ";", "this", ".", "cardboardUI_", "=", "null", ";", "this", ".", "dpdb_", "=", "new", "Dpdb", "(", "this", ".", "config", ".", "DPDB_URL", ",", "this", ".", "onDeviceParamsUpdated_", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "deviceInfo_", "=", "new", "DeviceInfo", "(", "this", ".", "dpdb_", ".", "getDeviceParams", "(", ")", ",", "config", ".", "ADDITIONAL_VIEWERS", ")", ";", "this", ".", "viewerSelector_", "=", "new", "ViewerSelector", "(", "config", ".", "DEFAULT_VIEWER", ")", ";", "this", ".", "viewerSelector_", ".", "onChange", "(", "this", ".", "onViewerChanged_", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "deviceInfo_", ".", "setViewer", "(", "this", ".", "viewerSelector_", ".", "getCurrentViewer", "(", ")", ")", ";", "if", "(", "!", "this", ".", "config", ".", "ROTATE_INSTRUCTIONS_DISABLED", ")", "{", "this", ".", "rotateInstructions_", "=", "new", "RotateInstructions", "(", ")", ";", "}", "if", "(", "Util", ".", "isIOS", "(", ")", ")", "{", "window", ".", "addEventListener", "(", "'resize'", ",", "this", ".", "onResize_", ".", "bind", "(", "this", ")", ")", ";", "}", "}" ]
VRDisplay based on mobile device parameters and DeviceMotion APIs.
[ "VRDisplay", "based", "on", "mobile", "device", "parameters", "and", "DeviceMotion", "APIs", "." ]
de59375309e637edbd3fd5e5213eac602930bb2b
https://github.com/immersive-web/cardboard-vr-display/blob/de59375309e637edbd3fd5e5213eac602930bb2b/src/cardboard-vr-display.js#L35-L81
train
immersive-web/cardboard-vr-display
src/viewer-selector.js
ViewerSelector
function ViewerSelector(defaultViewer) { // Try to load the selected key from local storage. try { this.selectedKey = localStorage.getItem(VIEWER_KEY); } catch (error) { console.error('Failed to load viewer profile: %s', error); } //If none exists, or if localstorage is unavailable, use the default key. if (!this.selectedKey) { this.selectedKey = defaultViewer || DEFAULT_VIEWER; } this.dialog = this.createDialog_(DeviceInfo.Viewers); this.root = null; this.onChangeCallbacks_ = []; }
javascript
function ViewerSelector(defaultViewer) { // Try to load the selected key from local storage. try { this.selectedKey = localStorage.getItem(VIEWER_KEY); } catch (error) { console.error('Failed to load viewer profile: %s', error); } //If none exists, or if localstorage is unavailable, use the default key. if (!this.selectedKey) { this.selectedKey = defaultViewer || DEFAULT_VIEWER; } this.dialog = this.createDialog_(DeviceInfo.Viewers); this.root = null; this.onChangeCallbacks_ = []; }
[ "function", "ViewerSelector", "(", "defaultViewer", ")", "{", "try", "{", "this", ".", "selectedKey", "=", "localStorage", ".", "getItem", "(", "VIEWER_KEY", ")", ";", "}", "catch", "(", "error", ")", "{", "console", ".", "error", "(", "'Failed to load viewer profile: %s'", ",", "error", ")", ";", "}", "if", "(", "!", "this", ".", "selectedKey", ")", "{", "this", ".", "selectedKey", "=", "defaultViewer", "||", "DEFAULT_VIEWER", ";", "}", "this", ".", "dialog", "=", "this", ".", "createDialog_", "(", "DeviceInfo", ".", "Viewers", ")", ";", "this", ".", "root", "=", "null", ";", "this", ".", "onChangeCallbacks_", "=", "[", "]", ";", "}" ]
Creates a viewer selector with the options specified. Supports being shown and hidden. Generates events when viewer parameters change. Also supports saving the currently selected index in localStorage.
[ "Creates", "a", "viewer", "selector", "with", "the", "options", "specified", ".", "Supports", "being", "shown", "and", "hidden", ".", "Generates", "events", "when", "viewer", "parameters", "change", ".", "Also", "supports", "saving", "the", "currently", "selected", "index", "in", "localStorage", "." ]
de59375309e637edbd3fd5e5213eac602930bb2b
https://github.com/immersive-web/cardboard-vr-display/blob/de59375309e637edbd3fd5e5213eac602930bb2b/src/viewer-selector.js#L28-L44
train
immersive-web/cardboard-vr-display
src/sensor-fusion/complementary-filter.js
ComplementaryFilter
function ComplementaryFilter(kFilter, isDebug) { this.kFilter = kFilter; this.isDebug = isDebug; // Raw sensor measurements. this.currentAccelMeasurement = new SensorSample(); this.currentGyroMeasurement = new SensorSample(); this.previousGyroMeasurement = new SensorSample(); // Set default look direction to be in the correct direction. if (Util.isIOS()) { this.filterQ = new MathUtil.Quaternion(-1, 0, 0, 1); } else { this.filterQ = new MathUtil.Quaternion(1, 0, 0, 1); } this.previousFilterQ = new MathUtil.Quaternion(); this.previousFilterQ.copy(this.filterQ); // Orientation based on the accelerometer. this.accelQ = new MathUtil.Quaternion(); // Whether or not the orientation has been initialized. this.isOrientationInitialized = false; // Running estimate of gravity based on the current orientation. this.estimatedGravity = new MathUtil.Vector3(); // Measured gravity based on accelerometer. this.measuredGravity = new MathUtil.Vector3(); // Debug only quaternion of gyro-based orientation. this.gyroIntegralQ = new MathUtil.Quaternion(); }
javascript
function ComplementaryFilter(kFilter, isDebug) { this.kFilter = kFilter; this.isDebug = isDebug; // Raw sensor measurements. this.currentAccelMeasurement = new SensorSample(); this.currentGyroMeasurement = new SensorSample(); this.previousGyroMeasurement = new SensorSample(); // Set default look direction to be in the correct direction. if (Util.isIOS()) { this.filterQ = new MathUtil.Quaternion(-1, 0, 0, 1); } else { this.filterQ = new MathUtil.Quaternion(1, 0, 0, 1); } this.previousFilterQ = new MathUtil.Quaternion(); this.previousFilterQ.copy(this.filterQ); // Orientation based on the accelerometer. this.accelQ = new MathUtil.Quaternion(); // Whether or not the orientation has been initialized. this.isOrientationInitialized = false; // Running estimate of gravity based on the current orientation. this.estimatedGravity = new MathUtil.Vector3(); // Measured gravity based on accelerometer. this.measuredGravity = new MathUtil.Vector3(); // Debug only quaternion of gyro-based orientation. this.gyroIntegralQ = new MathUtil.Quaternion(); }
[ "function", "ComplementaryFilter", "(", "kFilter", ",", "isDebug", ")", "{", "this", ".", "kFilter", "=", "kFilter", ";", "this", ".", "isDebug", "=", "isDebug", ";", "this", ".", "currentAccelMeasurement", "=", "new", "SensorSample", "(", ")", ";", "this", ".", "currentGyroMeasurement", "=", "new", "SensorSample", "(", ")", ";", "this", ".", "previousGyroMeasurement", "=", "new", "SensorSample", "(", ")", ";", "if", "(", "Util", ".", "isIOS", "(", ")", ")", "{", "this", ".", "filterQ", "=", "new", "MathUtil", ".", "Quaternion", "(", "-", "1", ",", "0", ",", "0", ",", "1", ")", ";", "}", "else", "{", "this", ".", "filterQ", "=", "new", "MathUtil", ".", "Quaternion", "(", "1", ",", "0", ",", "0", ",", "1", ")", ";", "}", "this", ".", "previousFilterQ", "=", "new", "MathUtil", ".", "Quaternion", "(", ")", ";", "this", ".", "previousFilterQ", ".", "copy", "(", "this", ".", "filterQ", ")", ";", "this", ".", "accelQ", "=", "new", "MathUtil", ".", "Quaternion", "(", ")", ";", "this", ".", "isOrientationInitialized", "=", "false", ";", "this", ".", "estimatedGravity", "=", "new", "MathUtil", ".", "Vector3", "(", ")", ";", "this", ".", "measuredGravity", "=", "new", "MathUtil", ".", "Vector3", "(", ")", ";", "this", ".", "gyroIntegralQ", "=", "new", "MathUtil", ".", "Quaternion", "(", ")", ";", "}" ]
An implementation of a simple complementary filter, which fuses gyroscope and accelerometer data from the 'devicemotion' event. Accelerometer data is very noisy, but stable over the long term. Gyroscope data is smooth, but tends to drift over the long term. This fusion is relatively simple: 1. Get orientation estimates from accelerometer by applying a low-pass filter on that data. 2. Get orientation estimates from gyroscope by integrating over time. 3. Combine the two estimates, weighing (1) in the long term, but (2) for the short term.
[ "An", "implementation", "of", "a", "simple", "complementary", "filter", "which", "fuses", "gyroscope", "and", "accelerometer", "data", "from", "the", "devicemotion", "event", "." ]
de59375309e637edbd3fd5e5213eac602930bb2b
https://github.com/immersive-web/cardboard-vr-display/blob/de59375309e637edbd3fd5e5213eac602930bb2b/src/sensor-fusion/complementary-filter.js#L34-L63
train
DevExpress/testcafe-browser-tools
src/api/get-installations.js
addInstallation
async function addInstallation (installations, name, instPath) { var fileExists = await exists(instPath); if (fileExists) { Object.keys(ALIASES).some(alias => { var { nameRe, cmd, macOpenCmdTemplate, path } = ALIASES[alias]; if (nameRe.test(name)) { installations[alias] = { path: path || instPath, cmd, macOpenCmdTemplate }; return true; } return false; }); } }
javascript
async function addInstallation (installations, name, instPath) { var fileExists = await exists(instPath); if (fileExists) { Object.keys(ALIASES).some(alias => { var { nameRe, cmd, macOpenCmdTemplate, path } = ALIASES[alias]; if (nameRe.test(name)) { installations[alias] = { path: path || instPath, cmd, macOpenCmdTemplate }; return true; } return false; }); } }
[ "async", "function", "addInstallation", "(", "installations", ",", "name", ",", "instPath", ")", "{", "var", "fileExists", "=", "await", "exists", "(", "instPath", ")", ";", "if", "(", "fileExists", ")", "{", "Object", ".", "keys", "(", "ALIASES", ")", ".", "some", "(", "alias", "=>", "{", "var", "{", "nameRe", ",", "cmd", ",", "macOpenCmdTemplate", ",", "path", "}", "=", "ALIASES", "[", "alias", "]", ";", "if", "(", "nameRe", ".", "test", "(", "name", ")", ")", "{", "installations", "[", "alias", "]", "=", "{", "path", ":", "path", "||", "instPath", ",", "cmd", ",", "macOpenCmdTemplate", "}", ";", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "}", "}" ]
Find installations for different platforms
[ "Find", "installations", "for", "different", "platforms" ]
db7242b7a97b1ea02973fa2cac160d0a351d0893
https://github.com/DevExpress/testcafe-browser-tools/blob/db7242b7a97b1ea02973fa2cac160d0a351d0893/src/api/get-installations.js#L14-L29
train
ProseMirror/prosemirror-menu
src/menu.js
setClass
function setClass(dom, cls, on) { if (on) dom.classList.add(cls) else dom.classList.remove(cls) }
javascript
function setClass(dom, cls, on) { if (on) dom.classList.add(cls) else dom.classList.remove(cls) }
[ "function", "setClass", "(", "dom", ",", "cls", ",", "on", ")", "{", "if", "(", "on", ")", "dom", ".", "classList", ".", "add", "(", "cls", ")", "else", "dom", ".", "classList", ".", "remove", "(", "cls", ")", "}" ]
Work around classList.toggle being broken in IE11
[ "Work", "around", "classList", ".", "toggle", "being", "broken", "in", "IE11" ]
5c8668dae081dd358c75fa31a62b5035e15b2eb2
https://github.com/ProseMirror/prosemirror-menu/blob/5c8668dae081dd358c75fa31a62b5035e15b2eb2/src/menu.js#L458-L461
train
ProseMirror/prosemirror-menu
src/menubar.js
selectionIsInverted
function selectionIsInverted(selection) { if (selection.anchorNode == selection.focusNode) return selection.anchorOffset > selection.focusOffset return selection.anchorNode.compareDocumentPosition(selection.focusNode) == Node.DOCUMENT_POSITION_FOLLOWING }
javascript
function selectionIsInverted(selection) { if (selection.anchorNode == selection.focusNode) return selection.anchorOffset > selection.focusOffset return selection.anchorNode.compareDocumentPosition(selection.focusNode) == Node.DOCUMENT_POSITION_FOLLOWING }
[ "function", "selectionIsInverted", "(", "selection", ")", "{", "if", "(", "selection", ".", "anchorNode", "==", "selection", ".", "focusNode", ")", "return", "selection", ".", "anchorOffset", ">", "selection", ".", "focusOffset", "return", "selection", ".", "anchorNode", ".", "compareDocumentPosition", "(", "selection", ".", "focusNode", ")", "==", "Node", ".", "DOCUMENT_POSITION_FOLLOWING", "}" ]
Not precise, but close enough
[ "Not", "precise", "but", "close", "enough" ]
5c8668dae081dd358c75fa31a62b5035e15b2eb2
https://github.com/ProseMirror/prosemirror-menu/blob/5c8668dae081dd358c75fa31a62b5035e15b2eb2/src/menubar.js#L140-L143
train
ioBroker/ioBroker.web
www/lib/js/materialize.js
Select
function Select(el, options) { _classCallCheck(this, Select); // Don't init if browser default version var _this16 = _possibleConstructorReturn(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, Select, el, options)); if (_this16.$el.hasClass('browser-default')) { return _possibleConstructorReturn(_this16); } _this16.el.M_Select = _this16; /** * Options for the select * @member Select#options */ _this16.options = $.extend({}, Select.defaults, options); _this16.isMultiple = _this16.$el.prop('multiple'); // Setup _this16.el.tabIndex = -1; _this16._keysSelected = {}; _this16._valueDict = {}; // Maps key to original and generated option element. _this16._setupDropdown(); _this16._setupEventHandlers(); return _this16; }
javascript
function Select(el, options) { _classCallCheck(this, Select); // Don't init if browser default version var _this16 = _possibleConstructorReturn(this, (Select.__proto__ || Object.getPrototypeOf(Select)).call(this, Select, el, options)); if (_this16.$el.hasClass('browser-default')) { return _possibleConstructorReturn(_this16); } _this16.el.M_Select = _this16; /** * Options for the select * @member Select#options */ _this16.options = $.extend({}, Select.defaults, options); _this16.isMultiple = _this16.$el.prop('multiple'); // Setup _this16.el.tabIndex = -1; _this16._keysSelected = {}; _this16._valueDict = {}; // Maps key to original and generated option element. _this16._setupDropdown(); _this16._setupEventHandlers(); return _this16; }
[ "function", "Select", "(", "el", ",", "options", ")", "{", "_classCallCheck", "(", "this", ",", "Select", ")", ";", "var", "_this16", "=", "_possibleConstructorReturn", "(", "this", ",", "(", "Select", ".", "__proto__", "||", "Object", ".", "getPrototypeOf", "(", "Select", ")", ")", ".", "call", "(", "this", ",", "Select", ",", "el", ",", "options", ")", ")", ";", "if", "(", "_this16", ".", "$el", ".", "hasClass", "(", "'browser-default'", ")", ")", "{", "return", "_possibleConstructorReturn", "(", "_this16", ")", ";", "}", "_this16", ".", "el", ".", "M_Select", "=", "_this16", ";", "_this16", ".", "options", "=", "$", ".", "extend", "(", "{", "}", ",", "Select", ".", "defaults", ",", "options", ")", ";", "_this16", ".", "isMultiple", "=", "_this16", ".", "$el", ".", "prop", "(", "'multiple'", ")", ";", "_this16", ".", "el", ".", "tabIndex", "=", "-", "1", ";", "_this16", ".", "_keysSelected", "=", "{", "}", ";", "_this16", ".", "_valueDict", "=", "{", "}", ";", "_this16", ".", "_setupDropdown", "(", ")", ";", "_this16", ".", "_setupEventHandlers", "(", ")", ";", "return", "_this16", ";", "}" ]
Construct Select instance @constructor @param {Element} el @param {Object} options
[ "Construct", "Select", "instance" ]
b2b4e086659d0a8c0662d64804e7380fa30f8338
https://github.com/ioBroker/ioBroker.web/blob/b2b4e086659d0a8c0662d64804e7380fa30f8338/www/lib/js/materialize.js#L3656-L3684
train
LukaszWatroba/v-accordion
dist/v-accordion.js
vPaneController
function vPaneController ($scope) { var ctrl = this; ctrl.isExpanded = function isExpanded () { return $scope.isExpanded; }; ctrl.toggle = function toggle () { if (!$scope.isAnimating && !$scope.isDisabled) { $scope.accordionCtrl.toggle($scope); } }; ctrl.expand = function expand () { if (!$scope.isAnimating && !$scope.isDisabled) { $scope.accordionCtrl.expand($scope); } }; ctrl.collapse = function collapse () { if (!$scope.isAnimating && !$scope.isDisabled) { $scope.accordionCtrl.collapse($scope); } }; ctrl.focusPane = function focusPane () { $scope.isFocused = true; }; ctrl.blurPane = function blurPane () { $scope.isFocused = false; }; $scope.internalControl = { toggle: ctrl.toggle, expand: ctrl.expand, collapse: ctrl.collapse, isExpanded: ctrl.isExpanded }; }
javascript
function vPaneController ($scope) { var ctrl = this; ctrl.isExpanded = function isExpanded () { return $scope.isExpanded; }; ctrl.toggle = function toggle () { if (!$scope.isAnimating && !$scope.isDisabled) { $scope.accordionCtrl.toggle($scope); } }; ctrl.expand = function expand () { if (!$scope.isAnimating && !$scope.isDisabled) { $scope.accordionCtrl.expand($scope); } }; ctrl.collapse = function collapse () { if (!$scope.isAnimating && !$scope.isDisabled) { $scope.accordionCtrl.collapse($scope); } }; ctrl.focusPane = function focusPane () { $scope.isFocused = true; }; ctrl.blurPane = function blurPane () { $scope.isFocused = false; }; $scope.internalControl = { toggle: ctrl.toggle, expand: ctrl.expand, collapse: ctrl.collapse, isExpanded: ctrl.isExpanded }; }
[ "function", "vPaneController", "(", "$scope", ")", "{", "var", "ctrl", "=", "this", ";", "ctrl", ".", "isExpanded", "=", "function", "isExpanded", "(", ")", "{", "return", "$scope", ".", "isExpanded", ";", "}", ";", "ctrl", ".", "toggle", "=", "function", "toggle", "(", ")", "{", "if", "(", "!", "$scope", ".", "isAnimating", "&&", "!", "$scope", ".", "isDisabled", ")", "{", "$scope", ".", "accordionCtrl", ".", "toggle", "(", "$scope", ")", ";", "}", "}", ";", "ctrl", ".", "expand", "=", "function", "expand", "(", ")", "{", "if", "(", "!", "$scope", ".", "isAnimating", "&&", "!", "$scope", ".", "isDisabled", ")", "{", "$scope", ".", "accordionCtrl", ".", "expand", "(", "$scope", ")", ";", "}", "}", ";", "ctrl", ".", "collapse", "=", "function", "collapse", "(", ")", "{", "if", "(", "!", "$scope", ".", "isAnimating", "&&", "!", "$scope", ".", "isDisabled", ")", "{", "$scope", ".", "accordionCtrl", ".", "collapse", "(", "$scope", ")", ";", "}", "}", ";", "ctrl", ".", "focusPane", "=", "function", "focusPane", "(", ")", "{", "$scope", ".", "isFocused", "=", "true", ";", "}", ";", "ctrl", ".", "blurPane", "=", "function", "blurPane", "(", ")", "{", "$scope", ".", "isFocused", "=", "false", ";", "}", ";", "$scope", ".", "internalControl", "=", "{", "toggle", ":", "ctrl", ".", "toggle", ",", "expand", ":", "ctrl", ".", "expand", ",", "collapse", ":", "ctrl", ".", "collapse", ",", "isExpanded", ":", "ctrl", ".", "isExpanded", "}", ";", "}" ]
vPane directive controller
[ "vPane", "directive", "controller" ]
eb95f31b784ec91dae3a42bdfd192a4487eb1c0e
https://github.com/LukaszWatroba/v-accordion/blob/eb95f31b784ec91dae3a42bdfd192a4487eb1c0e/dist/v-accordion.js#L506-L545
train
weaveworks/ui-components
src/components/TimeTravel/TimeTravel.js
maxDurationMsPerTimelinePx
function maxDurationMsPerTimelinePx(earliestTimestamp) { const durationMsLowerBound = minDurationMsPerTimelinePx(); const durationMsUpperBound = moment.duration(3, 'days').asMilliseconds(); const durationMs = availableTimelineDurationMs(earliestTimestamp) / 400.0; return clamp(durationMs, durationMsLowerBound, durationMsUpperBound); }
javascript
function maxDurationMsPerTimelinePx(earliestTimestamp) { const durationMsLowerBound = minDurationMsPerTimelinePx(); const durationMsUpperBound = moment.duration(3, 'days').asMilliseconds(); const durationMs = availableTimelineDurationMs(earliestTimestamp) / 400.0; return clamp(durationMs, durationMsLowerBound, durationMsUpperBound); }
[ "function", "maxDurationMsPerTimelinePx", "(", "earliestTimestamp", ")", "{", "const", "durationMsLowerBound", "=", "minDurationMsPerTimelinePx", "(", ")", ";", "const", "durationMsUpperBound", "=", "moment", ".", "duration", "(", "3", ",", "'days'", ")", ".", "asMilliseconds", "(", ")", ";", "const", "durationMs", "=", "availableTimelineDurationMs", "(", "earliestTimestamp", ")", "/", "400.0", ";", "return", "clamp", "(", "durationMs", ",", "durationMsLowerBound", ",", "durationMsUpperBound", ")", ";", "}" ]
Maximum level we can zoom out is such that the available range takes 400px. The 3 days per pixel upper bound on that scale is to prevent ugly rendering in extreme cases.
[ "Maximum", "level", "we", "can", "zoom", "out", "is", "such", "that", "the", "available", "range", "takes", "400px", ".", "The", "3", "days", "per", "pixel", "upper", "bound", "on", "that", "scale", "is", "to", "prevent", "ugly", "rendering", "in", "extreme", "cases", "." ]
2496b5f2d769a5aac64867206d6a045fedcb5f0c
https://github.com/weaveworks/ui-components/blob/2496b5f2d769a5aac64867206d6a045fedcb5f0c/src/components/TimeTravel/TimeTravel.js#L56-L61
train
weaveworks/ui-components
docs/js/routes.js
isSubComponent
function isSubComponent(resource) { const [dir, module] = resource.split('/').filter(n => n !== '.'); return dir !== module; }
javascript
function isSubComponent(resource) { const [dir, module] = resource.split('/').filter(n => n !== '.'); return dir !== module; }
[ "function", "isSubComponent", "(", "resource", ")", "{", "const", "[", "dir", ",", "module", "]", "=", "resource", ".", "split", "(", "'/'", ")", ".", "filter", "(", "n", "=>", "n", "!==", "'.'", ")", ";", "return", "dir", "!==", "module", ";", "}" ]
Don't render an example panel if the component is not the top-level component.
[ "Don", "t", "render", "an", "example", "panel", "if", "the", "component", "is", "not", "the", "top", "-", "level", "component", "." ]
2496b5f2d769a5aac64867206d6a045fedcb5f0c
https://github.com/weaveworks/ui-components/blob/2496b5f2d769a5aac64867206d6a045fedcb5f0c/docs/js/routes.js#L37-L40
train
ensdomains/ensjs
index.js
ENS
function ENS (provider, address, Web3js) { if (Web3js !== undefined) { Web3 = Web3js; } if (!!/^0\./.exec(Web3.version || (new Web3(provider)).version.api)) { return utils.construct(ENS_0, [provider, address]); } else { return utils.construct(ENS_1, [provider, address]); } }
javascript
function ENS (provider, address, Web3js) { if (Web3js !== undefined) { Web3 = Web3js; } if (!!/^0\./.exec(Web3.version || (new Web3(provider)).version.api)) { return utils.construct(ENS_0, [provider, address]); } else { return utils.construct(ENS_1, [provider, address]); } }
[ "function", "ENS", "(", "provider", ",", "address", ",", "Web3js", ")", "{", "if", "(", "Web3js", "!==", "undefined", ")", "{", "Web3", "=", "Web3js", ";", "}", "if", "(", "!", "!", "/", "^0\\.", "/", ".", "exec", "(", "Web3", ".", "version", "||", "(", "new", "Web3", "(", "provider", ")", ")", ".", "version", ".", "api", ")", ")", "{", "return", "utils", ".", "construct", "(", "ENS_0", ",", "[", "provider", ",", "address", "]", ")", ";", "}", "else", "{", "return", "utils", ".", "construct", "(", "ENS_1", ",", "[", "provider", ",", "address", "]", ")", ";", "}", "}" ]
Wrapper function that returns a version of ENS that is compatible with the provided version of Web3
[ "Wrapper", "function", "that", "returns", "a", "version", "of", "ENS", "that", "is", "compatible", "with", "the", "provided", "version", "of", "Web3" ]
ae6293041661ff4807f42e3057013f223cfbe99d
https://github.com/ensdomains/ensjs/blob/ae6293041661ff4807f42e3057013f223cfbe99d/index.js#L56-L65
train
angular/jasminewd
index.js
initJasmineWd
function initJasmineWd(scheduler, webdriver) { if (jasmine.JasmineWdInitialized) { throw Error('JasmineWd already initialized when init() was called'); } jasmine.JasmineWdInitialized = true; // Pull information from webdriver instance if (webdriver) { WebElement = webdriver.WebElement || WebElement; idleEventName = ( webdriver.promise && webdriver.promise.ControlFlow && webdriver.promise.ControlFlow.EventType && webdriver.promise.ControlFlow.EventType.IDLE ) || idleEventname; } // Default to mock scheduler if (!scheduler) { scheduler = { execute: function(fn) { return Promise.resolve().then(fn); } }; } // Figure out how we're getting new promises var newPromise; if (typeof scheduler.promise == 'function') { newPromise = scheduler.promise.bind(scheduler); } else if (webdriver && webdriver.promise && webdriver.promise.ControlFlow && (scheduler instanceof webdriver.promise.ControlFlow) && (webdriver.promise.USE_PROMISE_MANAGER !== false)) { newPromise = function(resolver) { return new webdriver.promise.Promise(resolver, scheduler); }; } else { newPromise = function(resolver) { return new Promise(resolver); }; } // Wrap functions global.it = wrapInScheduler(scheduler, newPromise, global.it, 'it'); global.fit = wrapInScheduler(scheduler, newPromise, global.fit, 'fit'); global.beforeEach = wrapInScheduler(scheduler, newPromise, global.beforeEach, 'beforeEach'); global.afterEach = wrapInScheduler(scheduler, newPromise, global.afterEach, 'afterEach'); global.beforeAll = wrapInScheduler(scheduler, newPromise, global.beforeAll, 'beforeAll'); global.afterAll = wrapInScheduler(scheduler, newPromise, global.afterAll, 'afterAll'); // Reset API if (scheduler.reset) { // On timeout, the flow should be reset. This will prevent webdriver tasks // from overflowing into the next test and causing it to fail or timeout // as well. This is done in the reporter instead of an afterEach block // to ensure that it runs after any afterEach() blocks with webdriver tasks // get to complete first. jasmine.getEnv().addReporter(new OnTimeoutReporter(function() { console.warn('A Jasmine spec timed out. Resetting the WebDriver Control Flow.'); scheduler.reset(); })); } }
javascript
function initJasmineWd(scheduler, webdriver) { if (jasmine.JasmineWdInitialized) { throw Error('JasmineWd already initialized when init() was called'); } jasmine.JasmineWdInitialized = true; // Pull information from webdriver instance if (webdriver) { WebElement = webdriver.WebElement || WebElement; idleEventName = ( webdriver.promise && webdriver.promise.ControlFlow && webdriver.promise.ControlFlow.EventType && webdriver.promise.ControlFlow.EventType.IDLE ) || idleEventname; } // Default to mock scheduler if (!scheduler) { scheduler = { execute: function(fn) { return Promise.resolve().then(fn); } }; } // Figure out how we're getting new promises var newPromise; if (typeof scheduler.promise == 'function') { newPromise = scheduler.promise.bind(scheduler); } else if (webdriver && webdriver.promise && webdriver.promise.ControlFlow && (scheduler instanceof webdriver.promise.ControlFlow) && (webdriver.promise.USE_PROMISE_MANAGER !== false)) { newPromise = function(resolver) { return new webdriver.promise.Promise(resolver, scheduler); }; } else { newPromise = function(resolver) { return new Promise(resolver); }; } // Wrap functions global.it = wrapInScheduler(scheduler, newPromise, global.it, 'it'); global.fit = wrapInScheduler(scheduler, newPromise, global.fit, 'fit'); global.beforeEach = wrapInScheduler(scheduler, newPromise, global.beforeEach, 'beforeEach'); global.afterEach = wrapInScheduler(scheduler, newPromise, global.afterEach, 'afterEach'); global.beforeAll = wrapInScheduler(scheduler, newPromise, global.beforeAll, 'beforeAll'); global.afterAll = wrapInScheduler(scheduler, newPromise, global.afterAll, 'afterAll'); // Reset API if (scheduler.reset) { // On timeout, the flow should be reset. This will prevent webdriver tasks // from overflowing into the next test and causing it to fail or timeout // as well. This is done in the reporter instead of an afterEach block // to ensure that it runs after any afterEach() blocks with webdriver tasks // get to complete first. jasmine.getEnv().addReporter(new OnTimeoutReporter(function() { console.warn('A Jasmine spec timed out. Resetting the WebDriver Control Flow.'); scheduler.reset(); })); } }
[ "function", "initJasmineWd", "(", "scheduler", ",", "webdriver", ")", "{", "if", "(", "jasmine", ".", "JasmineWdInitialized", ")", "{", "throw", "Error", "(", "'JasmineWd already initialized when init() was called'", ")", ";", "}", "jasmine", ".", "JasmineWdInitialized", "=", "true", ";", "if", "(", "webdriver", ")", "{", "WebElement", "=", "webdriver", ".", "WebElement", "||", "WebElement", ";", "idleEventName", "=", "(", "webdriver", ".", "promise", "&&", "webdriver", ".", "promise", ".", "ControlFlow", "&&", "webdriver", ".", "promise", ".", "ControlFlow", ".", "EventType", "&&", "webdriver", ".", "promise", ".", "ControlFlow", ".", "EventType", ".", "IDLE", ")", "||", "idleEventname", ";", "}", "if", "(", "!", "scheduler", ")", "{", "scheduler", "=", "{", "execute", ":", "function", "(", "fn", ")", "{", "return", "Promise", ".", "resolve", "(", ")", ".", "then", "(", "fn", ")", ";", "}", "}", ";", "}", "var", "newPromise", ";", "if", "(", "typeof", "scheduler", ".", "promise", "==", "'function'", ")", "{", "newPromise", "=", "scheduler", ".", "promise", ".", "bind", "(", "scheduler", ")", ";", "}", "else", "if", "(", "webdriver", "&&", "webdriver", ".", "promise", "&&", "webdriver", ".", "promise", ".", "ControlFlow", "&&", "(", "scheduler", "instanceof", "webdriver", ".", "promise", ".", "ControlFlow", ")", "&&", "(", "webdriver", ".", "promise", ".", "USE_PROMISE_MANAGER", "!==", "false", ")", ")", "{", "newPromise", "=", "function", "(", "resolver", ")", "{", "return", "new", "webdriver", ".", "promise", ".", "Promise", "(", "resolver", ",", "scheduler", ")", ";", "}", ";", "}", "else", "{", "newPromise", "=", "function", "(", "resolver", ")", "{", "return", "new", "Promise", "(", "resolver", ")", ";", "}", ";", "}", "global", ".", "it", "=", "wrapInScheduler", "(", "scheduler", ",", "newPromise", ",", "global", ".", "it", ",", "'it'", ")", ";", "global", ".", "fit", "=", "wrapInScheduler", "(", "scheduler", ",", "newPromise", ",", "global", ".", "fit", ",", "'fit'", ")", ";", "global", ".", "beforeEach", "=", "wrapInScheduler", "(", "scheduler", ",", "newPromise", ",", "global", ".", "beforeEach", ",", "'beforeEach'", ")", ";", "global", ".", "afterEach", "=", "wrapInScheduler", "(", "scheduler", ",", "newPromise", ",", "global", ".", "afterEach", ",", "'afterEach'", ")", ";", "global", ".", "beforeAll", "=", "wrapInScheduler", "(", "scheduler", ",", "newPromise", ",", "global", ".", "beforeAll", ",", "'beforeAll'", ")", ";", "global", ".", "afterAll", "=", "wrapInScheduler", "(", "scheduler", ",", "newPromise", ",", "global", ".", "afterAll", ",", "'afterAll'", ")", ";", "if", "(", "scheduler", ".", "reset", ")", "{", "jasmine", ".", "getEnv", "(", ")", ".", "addReporter", "(", "new", "OnTimeoutReporter", "(", "function", "(", ")", "{", "console", ".", "warn", "(", "'A Jasmine spec timed out. Resetting the WebDriver Control Flow.'", ")", ";", "scheduler", ".", "reset", "(", ")", ";", "}", ")", ")", ";", "}", "}" ]
Initialize the JasmineWd adapter with a particlar scheduler, generally a webdriver control flow. @param {Object=} scheduler The scheduler to wrap tests in. See scheduler.md for details. Defaults to a mock scheduler that calls functions immediately. @param {Object=} webdriver The result of `require('selenium-webdriver')`. Passed in here rather than required by jasminewd directly so that jasminewd can't end up up with a different version of `selenium-webdriver` than your tests use. If not specified, jasminewd will still work, but it won't check for `WebElement` instances in expect() statements and could cause control flow problems if your tests are using an old version of `selenium-webdriver` (e.g. version 2.53.0).
[ "Initialize", "the", "JasmineWd", "adapter", "with", "a", "particlar", "scheduler", "generally", "a", "webdriver", "control", "flow", "." ]
236b0d211ef7b8510629dcbc7d2a18afaabd2f10
https://github.com/angular/jasminewd/blob/236b0d211ef7b8510629dcbc7d2a18afaabd2f10/index.js#L178-L239
train
angular/jasminewd
index.js
compareDone
function compareDone(pass) { var message = ''; if (!pass) { if (!result.message) { args.unshift(expectation.isNot); args.unshift(name); message = expectation.util.buildFailureMessage.apply(null, args); } else { if (Object.prototype.toString.apply(result.message) === '[object Function]') { message = result.message(expectation.isNot); } else { message = result.message; } } } if (expected.length == 1) { expected = expected[0]; } var res = { matcherName: name, passed: pass, message: message, actual: actual, expected: expected, error: matchError }; expectation.addExpectationResult(pass, res); }
javascript
function compareDone(pass) { var message = ''; if (!pass) { if (!result.message) { args.unshift(expectation.isNot); args.unshift(name); message = expectation.util.buildFailureMessage.apply(null, args); } else { if (Object.prototype.toString.apply(result.message) === '[object Function]') { message = result.message(expectation.isNot); } else { message = result.message; } } } if (expected.length == 1) { expected = expected[0]; } var res = { matcherName: name, passed: pass, message: message, actual: actual, expected: expected, error: matchError }; expectation.addExpectationResult(pass, res); }
[ "function", "compareDone", "(", "pass", ")", "{", "var", "message", "=", "''", ";", "if", "(", "!", "pass", ")", "{", "if", "(", "!", "result", ".", "message", ")", "{", "args", ".", "unshift", "(", "expectation", ".", "isNot", ")", ";", "args", ".", "unshift", "(", "name", ")", ";", "message", "=", "expectation", ".", "util", ".", "buildFailureMessage", ".", "apply", "(", "null", ",", "args", ")", ";", "}", "else", "{", "if", "(", "Object", ".", "prototype", ".", "toString", ".", "apply", "(", "result", ".", "message", ")", "===", "'[object Function]'", ")", "{", "message", "=", "result", ".", "message", "(", "expectation", ".", "isNot", ")", ";", "}", "else", "{", "message", "=", "result", ".", "message", ";", "}", "}", "}", "if", "(", "expected", ".", "length", "==", "1", ")", "{", "expected", "=", "expected", "[", "0", "]", ";", "}", "var", "res", "=", "{", "matcherName", ":", "name", ",", "passed", ":", "pass", ",", "message", ":", "message", ",", "actual", ":", "actual", ",", "expected", ":", "expected", ",", "error", ":", "matchError", "}", ";", "expectation", ".", "addExpectationResult", "(", "pass", ",", "res", ")", ";", "}" ]
compareDone always returns undefined
[ "compareDone", "always", "returns", "undefined" ]
236b0d211ef7b8510629dcbc7d2a18afaabd2f10
https://github.com/angular/jasminewd/blob/236b0d211ef7b8510629dcbc7d2a18afaabd2f10/index.js#L289-L318
train
ten1seven/jRespond
js/jRespond.js
function() { var w = 0; // IE if (typeof( window.innerWidth ) != 'number') { if (!(document.documentElement.clientWidth === 0)) { // strict mode w = document.documentElement.clientWidth; } else { // quirks mode w = document.body.clientWidth; } } else { // w3c w = window.innerWidth; } return w; }
javascript
function() { var w = 0; // IE if (typeof( window.innerWidth ) != 'number') { if (!(document.documentElement.clientWidth === 0)) { // strict mode w = document.documentElement.clientWidth; } else { // quirks mode w = document.body.clientWidth; } } else { // w3c w = window.innerWidth; } return w; }
[ "function", "(", ")", "{", "var", "w", "=", "0", ";", "if", "(", "typeof", "(", "window", ".", "innerWidth", ")", "!=", "'number'", ")", "{", "if", "(", "!", "(", "document", ".", "documentElement", ".", "clientWidth", "===", "0", ")", ")", "{", "w", "=", "document", ".", "documentElement", ".", "clientWidth", ";", "}", "else", "{", "w", "=", "document", ".", "body", ".", "clientWidth", ";", "}", "}", "else", "{", "w", "=", "window", ".", "innerWidth", ";", "}", "return", "w", ";", "}" ]
cross browser window width
[ "cross", "browser", "window", "width" ]
2e5112fceea57d8a707271ee34b8fb36e9eacd48
https://github.com/ten1seven/jRespond/blob/2e5112fceea57d8a707271ee34b8fb36e9eacd48/js/jRespond.js#L48-L71
train
ten1seven/jRespond
js/jRespond.js
function(elm) { if (elm.length === undefined) { addToStack(elm); } else { for (var i = 0; i < elm.length; i++) { addToStack(elm[i]); } } }
javascript
function(elm) { if (elm.length === undefined) { addToStack(elm); } else { for (var i = 0; i < elm.length; i++) { addToStack(elm[i]); } } }
[ "function", "(", "elm", ")", "{", "if", "(", "elm", ".", "length", "===", "undefined", ")", "{", "addToStack", "(", "elm", ")", ";", "}", "else", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "elm", ".", "length", ";", "i", "++", ")", "{", "addToStack", "(", "elm", "[", "i", "]", ")", ";", "}", "}", "}" ]
determine input type
[ "determine", "input", "type" ]
2e5112fceea57d8a707271ee34b8fb36e9eacd48
https://github.com/ten1seven/jRespond/blob/2e5112fceea57d8a707271ee34b8fb36e9eacd48/js/jRespond.js#L74-L82
train
ten1seven/jRespond
js/jRespond.js
function(elm) { var brkpt = elm['breakpoint']; var entr = elm['enter'] || undefined; // add function to stack mediaListeners.push(elm); // add corresponding entry to mediaInit mediaInit.push(false); if (testForCurr(brkpt)) { if (entr !== undefined) { entr.call(null, {entering : curr, exiting : prev}); } mediaInit[(mediaListeners.length - 1)] = true; } }
javascript
function(elm) { var brkpt = elm['breakpoint']; var entr = elm['enter'] || undefined; // add function to stack mediaListeners.push(elm); // add corresponding entry to mediaInit mediaInit.push(false); if (testForCurr(brkpt)) { if (entr !== undefined) { entr.call(null, {entering : curr, exiting : prev}); } mediaInit[(mediaListeners.length - 1)] = true; } }
[ "function", "(", "elm", ")", "{", "var", "brkpt", "=", "elm", "[", "'breakpoint'", "]", ";", "var", "entr", "=", "elm", "[", "'enter'", "]", "||", "undefined", ";", "mediaListeners", ".", "push", "(", "elm", ")", ";", "mediaInit", ".", "push", "(", "false", ")", ";", "if", "(", "testForCurr", "(", "brkpt", ")", ")", "{", "if", "(", "entr", "!==", "undefined", ")", "{", "entr", ".", "call", "(", "null", ",", "{", "entering", ":", "curr", ",", "exiting", ":", "prev", "}", ")", ";", "}", "mediaInit", "[", "(", "mediaListeners", ".", "length", "-", "1", ")", "]", "=", "true", ";", "}", "}" ]
send media to the mediaListeners array
[ "send", "media", "to", "the", "mediaListeners", "array" ]
2e5112fceea57d8a707271ee34b8fb36e9eacd48
https://github.com/ten1seven/jRespond/blob/2e5112fceea57d8a707271ee34b8fb36e9eacd48/js/jRespond.js#L85-L101
train
ten1seven/jRespond
js/jRespond.js
function() { var enterArray = []; var exitArray = []; for (var i = 0; i < mediaListeners.length; i++) { var brkpt = mediaListeners[i]['breakpoint']; var entr = mediaListeners[i]['enter'] || undefined; var exit = mediaListeners[i]['exit'] || undefined; if (brkpt === '*') { if (entr !== undefined) { enterArray.push(entr); } if (exit !== undefined) { exitArray.push(exit); } } else if (testForCurr(brkpt)) { if (entr !== undefined && !mediaInit[i]) { enterArray.push(entr); } mediaInit[i] = true; } else { if (exit !== undefined && mediaInit[i]) { exitArray.push(exit); } mediaInit[i] = false; } } var eventObject = { entering : curr, exiting : prev }; // loop through exit functions to call for (var j = 0; j < exitArray.length; j++) { exitArray[j].call(null, eventObject); } // then loop through enter functions to call for (var k = 0; k < enterArray.length; k++) { enterArray[k].call(null, eventObject); } }
javascript
function() { var enterArray = []; var exitArray = []; for (var i = 0; i < mediaListeners.length; i++) { var brkpt = mediaListeners[i]['breakpoint']; var entr = mediaListeners[i]['enter'] || undefined; var exit = mediaListeners[i]['exit'] || undefined; if (brkpt === '*') { if (entr !== undefined) { enterArray.push(entr); } if (exit !== undefined) { exitArray.push(exit); } } else if (testForCurr(brkpt)) { if (entr !== undefined && !mediaInit[i]) { enterArray.push(entr); } mediaInit[i] = true; } else { if (exit !== undefined && mediaInit[i]) { exitArray.push(exit); } mediaInit[i] = false; } } var eventObject = { entering : curr, exiting : prev }; // loop through exit functions to call for (var j = 0; j < exitArray.length; j++) { exitArray[j].call(null, eventObject); } // then loop through enter functions to call for (var k = 0; k < enterArray.length; k++) { enterArray[k].call(null, eventObject); } }
[ "function", "(", ")", "{", "var", "enterArray", "=", "[", "]", ";", "var", "exitArray", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "mediaListeners", ".", "length", ";", "i", "++", ")", "{", "var", "brkpt", "=", "mediaListeners", "[", "i", "]", "[", "'breakpoint'", "]", ";", "var", "entr", "=", "mediaListeners", "[", "i", "]", "[", "'enter'", "]", "||", "undefined", ";", "var", "exit", "=", "mediaListeners", "[", "i", "]", "[", "'exit'", "]", "||", "undefined", ";", "if", "(", "brkpt", "===", "'*'", ")", "{", "if", "(", "entr", "!==", "undefined", ")", "{", "enterArray", ".", "push", "(", "entr", ")", ";", "}", "if", "(", "exit", "!==", "undefined", ")", "{", "exitArray", ".", "push", "(", "exit", ")", ";", "}", "}", "else", "if", "(", "testForCurr", "(", "brkpt", ")", ")", "{", "if", "(", "entr", "!==", "undefined", "&&", "!", "mediaInit", "[", "i", "]", ")", "{", "enterArray", ".", "push", "(", "entr", ")", ";", "}", "mediaInit", "[", "i", "]", "=", "true", ";", "}", "else", "{", "if", "(", "exit", "!==", "undefined", "&&", "mediaInit", "[", "i", "]", ")", "{", "exitArray", ".", "push", "(", "exit", ")", ";", "}", "mediaInit", "[", "i", "]", "=", "false", ";", "}", "}", "var", "eventObject", "=", "{", "entering", ":", "curr", ",", "exiting", ":", "prev", "}", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "exitArray", ".", "length", ";", "j", "++", ")", "{", "exitArray", "[", "j", "]", ".", "call", "(", "null", ",", "eventObject", ")", ";", "}", "for", "(", "var", "k", "=", "0", ";", "k", "<", "enterArray", ".", "length", ";", "k", "++", ")", "{", "enterArray", "[", "k", "]", ".", "call", "(", "null", ",", "eventObject", ")", ";", "}", "}" ]
loops through all registered functions and determines what should be fired
[ "loops", "through", "all", "registered", "functions", "and", "determines", "what", "should", "be", "fired" ]
2e5112fceea57d8a707271ee34b8fb36e9eacd48
https://github.com/ten1seven/jRespond/blob/2e5112fceea57d8a707271ee34b8fb36e9eacd48/js/jRespond.js#L104-L148
train
ten1seven/jRespond
js/jRespond.js
function(width) { var foundBrkpt = false; // look for existing breakpoint based on width for (var i = 0; i < mediaBreakpoints.length; i++) { // if registered breakpoint found, break out of loop if (width >= mediaBreakpoints[i]['enter'] && width <= mediaBreakpoints[i]['exit']) { foundBrkpt = true; break; } } // if breakpoint is found and it's not the current one if (foundBrkpt && curr !== mediaBreakpoints[i]['label']) { prev = curr; curr = mediaBreakpoints[i]['label']; // run the loop cycleThrough(); // or if no breakpoint applies } else if (!foundBrkpt && curr !== '') { curr = ''; // run the loop cycleThrough(); } }
javascript
function(width) { var foundBrkpt = false; // look for existing breakpoint based on width for (var i = 0; i < mediaBreakpoints.length; i++) { // if registered breakpoint found, break out of loop if (width >= mediaBreakpoints[i]['enter'] && width <= mediaBreakpoints[i]['exit']) { foundBrkpt = true; break; } } // if breakpoint is found and it's not the current one if (foundBrkpt && curr !== mediaBreakpoints[i]['label']) { prev = curr; curr = mediaBreakpoints[i]['label']; // run the loop cycleThrough(); // or if no breakpoint applies } else if (!foundBrkpt && curr !== '') { curr = ''; // run the loop cycleThrough(); } }
[ "function", "(", "width", ")", "{", "var", "foundBrkpt", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "mediaBreakpoints", ".", "length", ";", "i", "++", ")", "{", "if", "(", "width", ">=", "mediaBreakpoints", "[", "i", "]", "[", "'enter'", "]", "&&", "width", "<=", "mediaBreakpoints", "[", "i", "]", "[", "'exit'", "]", ")", "{", "foundBrkpt", "=", "true", ";", "break", ";", "}", "}", "if", "(", "foundBrkpt", "&&", "curr", "!==", "mediaBreakpoints", "[", "i", "]", "[", "'label'", "]", ")", "{", "prev", "=", "curr", ";", "curr", "=", "mediaBreakpoints", "[", "i", "]", "[", "'label'", "]", ";", "cycleThrough", "(", ")", ";", "}", "else", "if", "(", "!", "foundBrkpt", "&&", "curr", "!==", "''", ")", "{", "curr", "=", "''", ";", "cycleThrough", "(", ")", ";", "}", "}" ]
checks for the correct breakpoint against the mediaBreakpoints list
[ "checks", "for", "the", "correct", "breakpoint", "against", "the", "mediaBreakpoints", "list" ]
2e5112fceea57d8a707271ee34b8fb36e9eacd48
https://github.com/ten1seven/jRespond/blob/2e5112fceea57d8a707271ee34b8fb36e9eacd48/js/jRespond.js#L151-L182
train
ten1seven/jRespond
js/jRespond.js
function() { // get current width var w = winWidth(); // if there is a change speed up the timer and fire the returnBreakpoint function if (w !== resizeW) { resizeTmrSpd = resizeTmrFast; returnBreakpoint(w); // otherwise keep on keepin' on } else { resizeTmrSpd = resizeTmrSlow; } resizeW = w; // calls itself on a setTimeout setTimeout(checkResize, resizeTmrSpd); }
javascript
function() { // get current width var w = winWidth(); // if there is a change speed up the timer and fire the returnBreakpoint function if (w !== resizeW) { resizeTmrSpd = resizeTmrFast; returnBreakpoint(w); // otherwise keep on keepin' on } else { resizeTmrSpd = resizeTmrSlow; } resizeW = w; // calls itself on a setTimeout setTimeout(checkResize, resizeTmrSpd); }
[ "function", "(", ")", "{", "var", "w", "=", "winWidth", "(", ")", ";", "if", "(", "w", "!==", "resizeW", ")", "{", "resizeTmrSpd", "=", "resizeTmrFast", ";", "returnBreakpoint", "(", "w", ")", ";", "}", "else", "{", "resizeTmrSpd", "=", "resizeTmrSlow", ";", "}", "resizeW", "=", "w", ";", "setTimeout", "(", "checkResize", ",", "resizeTmrSpd", ")", ";", "}" ]
self-calling function that checks the browser width and delegates if it detects a change
[ "self", "-", "calling", "function", "that", "checks", "the", "browser", "width", "and", "delegates", "if", "it", "detects", "a", "change" ]
2e5112fceea57d8a707271ee34b8fb36e9eacd48
https://github.com/ten1seven/jRespond/blob/2e5112fceea57d8a707271ee34b8fb36e9eacd48/js/jRespond.js#L206-L226
train
broccolijs/broccoli-funnel
index.js
isNotAPattern
function isNotAPattern(pattern) { let set = new Minimatch(pattern).set; if (set.length > 1) { return false; } for (let j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') { return false; } } return true; }
javascript
function isNotAPattern(pattern) { let set = new Minimatch(pattern).set; if (set.length > 1) { return false; } for (let j = 0; j < set[0].length; j++) { if (typeof set[0][j] !== 'string') { return false; } } return true; }
[ "function", "isNotAPattern", "(", "pattern", ")", "{", "let", "set", "=", "new", "Minimatch", "(", "pattern", ")", ".", "set", ";", "if", "(", "set", ".", "length", ">", "1", ")", "{", "return", "false", ";", "}", "for", "(", "let", "j", "=", "0", ";", "j", "<", "set", "[", "0", "]", ".", "length", ";", "j", "++", ")", "{", "if", "(", "typeof", "set", "[", "0", "]", "[", "j", "]", "!==", "'string'", ")", "{", "return", "false", ";", "}", "}", "return", "true", ";", "}" ]
copied mostly from node-glob cc @isaacs
[ "copied", "mostly", "from", "node", "-", "glob", "cc" ]
50ea34e9a5549dcff2d3c077029b542ed3698e8c
https://github.com/broccolijs/broccoli-funnel/blob/50ea34e9a5549dcff2d3c077029b542ed3698e8c/index.js#L36-L49
train
akoenig/angular-deckgrid
angular-deckgrid.js
Deckgrid
function Deckgrid (scope, element) { var self = this, watcher, mql; this.$$elem = element; this.$$watchers = []; this.$$scope = scope; this.$$scope.columns = []; // // The layout configuration will be parsed from // the pseudo "before element." There you have to save all // the column configurations. // this.$$scope.layout = this.$$getLayout(); this.$$createColumns(); // // Register model change. // watcher = this.$$scope.$watchCollection('model', this.$$onModelChange.bind(this)); this.$$watchers.push(watcher); // // Register media query change events. // angular.forEach(self.$$getMediaQueries(), function onIteration (rule) { var handler = self.$$onMediaQueryChange.bind(self); function onDestroy () { rule.removeListener(handler); } rule.addListener(handler); self.$$watchers.push(onDestroy); }); mql = $window.matchMedia('(orientation: portrait)'); mql.addListener(self.$$onMediaQueryChange.bind(self)); }
javascript
function Deckgrid (scope, element) { var self = this, watcher, mql; this.$$elem = element; this.$$watchers = []; this.$$scope = scope; this.$$scope.columns = []; // // The layout configuration will be parsed from // the pseudo "before element." There you have to save all // the column configurations. // this.$$scope.layout = this.$$getLayout(); this.$$createColumns(); // // Register model change. // watcher = this.$$scope.$watchCollection('model', this.$$onModelChange.bind(this)); this.$$watchers.push(watcher); // // Register media query change events. // angular.forEach(self.$$getMediaQueries(), function onIteration (rule) { var handler = self.$$onMediaQueryChange.bind(self); function onDestroy () { rule.removeListener(handler); } rule.addListener(handler); self.$$watchers.push(onDestroy); }); mql = $window.matchMedia('(orientation: portrait)'); mql.addListener(self.$$onMediaQueryChange.bind(self)); }
[ "function", "Deckgrid", "(", "scope", ",", "element", ")", "{", "var", "self", "=", "this", ",", "watcher", ",", "mql", ";", "this", ".", "$$elem", "=", "element", ";", "this", ".", "$$watchers", "=", "[", "]", ";", "this", ".", "$$scope", "=", "scope", ";", "this", ".", "$$scope", ".", "columns", "=", "[", "]", ";", "this", ".", "$$scope", ".", "layout", "=", "this", ".", "$$getLayout", "(", ")", ";", "this", ".", "$$createColumns", "(", ")", ";", "watcher", "=", "this", ".", "$$scope", ".", "$watchCollection", "(", "'model'", ",", "this", ".", "$$onModelChange", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "$$watchers", ".", "push", "(", "watcher", ")", ";", "angular", ".", "forEach", "(", "self", ".", "$$getMediaQueries", "(", ")", ",", "function", "onIteration", "(", "rule", ")", "{", "var", "handler", "=", "self", ".", "$$onMediaQueryChange", ".", "bind", "(", "self", ")", ";", "function", "onDestroy", "(", ")", "{", "rule", ".", "removeListener", "(", "handler", ")", ";", "}", "rule", ".", "addListener", "(", "handler", ")", ";", "self", ".", "$$watchers", ".", "push", "(", "onDestroy", ")", ";", "}", ")", ";", "mql", "=", "$window", ".", "matchMedia", "(", "'(orientation: portrait)'", ")", ";", "mql", ".", "addListener", "(", "self", ".", "$$onMediaQueryChange", ".", "bind", "(", "self", ")", ")", ";", "}" ]
The deckgrid directive.
[ "The", "deckgrid", "directive", "." ]
7d58a6ae59604a27a6a9b6ec39a192afdb5a7c9f
https://github.com/akoenig/angular-deckgrid/blob/7d58a6ae59604a27a6a9b6ec39a192afdb5a7c9f/angular-deckgrid.js#L175-L220
train
nodeca/mincer
lib/mincer/assets/processed.js
buildRequiredAssets
function buildRequiredAssets(self, context) { var paths = context.__requiredPaths__.concat([ self.pathname ]), assets = resolveDependencies(self, paths), stubs = resolveDependencies(self, context.__stubbedAssets__); if (stubs.length > 0) { // exclude stubbed assets if any assets = _.filter(assets, function (path) { return stubs.indexOf(path) === -1; }); } prop(self, '__requiredAssets__', assets); }
javascript
function buildRequiredAssets(self, context) { var paths = context.__requiredPaths__.concat([ self.pathname ]), assets = resolveDependencies(self, paths), stubs = resolveDependencies(self, context.__stubbedAssets__); if (stubs.length > 0) { // exclude stubbed assets if any assets = _.filter(assets, function (path) { return stubs.indexOf(path) === -1; }); } prop(self, '__requiredAssets__', assets); }
[ "function", "buildRequiredAssets", "(", "self", ",", "context", ")", "{", "var", "paths", "=", "context", ".", "__requiredPaths__", ".", "concat", "(", "[", "self", ".", "pathname", "]", ")", ",", "assets", "=", "resolveDependencies", "(", "self", ",", "paths", ")", ",", "stubs", "=", "resolveDependencies", "(", "self", ",", "context", ".", "__stubbedAssets__", ")", ";", "if", "(", "stubs", ".", "length", ">", "0", ")", "{", "assets", "=", "_", ".", "filter", "(", "assets", ",", "function", "(", "path", ")", "{", "return", "stubs", ".", "indexOf", "(", "path", ")", "===", "-", "1", ";", "}", ")", ";", "}", "prop", "(", "self", ",", "'__requiredAssets__'", ",", "assets", ")", ";", "}" ]
build all required assets
[ "build", "all", "required", "assets" ]
a44368093bf11545712378f19c1a0139eafe13e4
https://github.com/nodeca/mincer/blob/a44368093bf11545712378f19c1a0139eafe13e4/lib/mincer/assets/processed.js#L70-L83
train
nodeca/mincer
lib/mincer/assets/processed.js
computeDependencyDigest
function computeDependencyDigest(self) { return _.reduce(self.requiredAssets, function (digest, asset) { return digest.update(asset.digest); }, self.environment.digest).digest('hex'); }
javascript
function computeDependencyDigest(self) { return _.reduce(self.requiredAssets, function (digest, asset) { return digest.update(asset.digest); }, self.environment.digest).digest('hex'); }
[ "function", "computeDependencyDigest", "(", "self", ")", "{", "return", "_", ".", "reduce", "(", "self", ".", "requiredAssets", ",", "function", "(", "digest", ",", "asset", ")", "{", "return", "digest", ".", "update", "(", "asset", ".", "digest", ")", ";", "}", ",", "self", ".", "environment", ".", "digest", ")", ".", "digest", "(", "'hex'", ")", ";", "}" ]
return digest based on digests of all dependencies
[ "return", "digest", "based", "on", "digests", "of", "all", "dependencies" ]
a44368093bf11545712378f19c1a0139eafe13e4
https://github.com/nodeca/mincer/blob/a44368093bf11545712378f19c1a0139eafe13e4/lib/mincer/assets/processed.js#L120-L124
train
nodeca/mincer
lib/mincer/engines/sass_engine.js
sassError
function sassError(ctx /*, options*/) { if (ctx.line && ctx.message) { // libsass 3.x error object return new Error('Line ' + ctx.line + ': ' + ctx.message); } if (typeof ctx === 'string') { // libsass error string format: path:line: error: message var error = _.zipObject( [ 'path', 'line', 'level', 'message' ], ctx.split(':', 4).map(function (str) { return str.trim(); }) ); if (error.line && error.level && error.message) { return new Error('Line ' + error.line + ': ' + error.message); } } return new Error(ctx); }
javascript
function sassError(ctx /*, options*/) { if (ctx.line && ctx.message) { // libsass 3.x error object return new Error('Line ' + ctx.line + ': ' + ctx.message); } if (typeof ctx === 'string') { // libsass error string format: path:line: error: message var error = _.zipObject( [ 'path', 'line', 'level', 'message' ], ctx.split(':', 4).map(function (str) { return str.trim(); }) ); if (error.line && error.level && error.message) { return new Error('Line ' + error.line + ': ' + error.message); } } return new Error(ctx); }
[ "function", "sassError", "(", "ctx", ")", "{", "if", "(", "ctx", ".", "line", "&&", "ctx", ".", "message", ")", "{", "return", "new", "Error", "(", "'Line '", "+", "ctx", ".", "line", "+", "': '", "+", "ctx", ".", "message", ")", ";", "}", "if", "(", "typeof", "ctx", "===", "'string'", ")", "{", "var", "error", "=", "_", ".", "zipObject", "(", "[", "'path'", ",", "'line'", ",", "'level'", ",", "'message'", "]", ",", "ctx", ".", "split", "(", "':'", ",", "4", ")", ".", "map", "(", "function", "(", "str", ")", "{", "return", "str", ".", "trim", "(", ")", ";", "}", ")", ")", ";", "if", "(", "error", ".", "line", "&&", "error", ".", "level", "&&", "error", ".", "message", ")", "{", "return", "new", "Error", "(", "'Line '", "+", "error", ".", "line", "+", "': '", "+", "error", ".", "message", ")", ";", "}", "}", "return", "new", "Error", "(", "ctx", ")", ";", "}" ]
helper to generate human-friendly errors. adapted version from less_engine.js
[ "helper", "to", "generate", "human", "-", "friendly", "errors", ".", "adapted", "version", "from", "less_engine", ".", "js" ]
a44368093bf11545712378f19c1a0139eafe13e4
https://github.com/nodeca/mincer/blob/a44368093bf11545712378f19c1a0139eafe13e4/lib/mincer/engines/sass_engine.js#L78-L93
train
nodeca/mincer
lib/mincer/engines/sass_engine.js
importArgumentRelativeToSearchPaths
function importArgumentRelativeToSearchPaths(importer, importArgument, searchPaths) { var importAbsolutePath = path.resolve(path.dirname(importer), importArgument); var importSearchPath = _.find(searchPaths, function (path) { return importAbsolutePath.indexOf(path) === 0; }); if (importSearchPath) { return path.relative(importSearchPath, importAbsolutePath); } }
javascript
function importArgumentRelativeToSearchPaths(importer, importArgument, searchPaths) { var importAbsolutePath = path.resolve(path.dirname(importer), importArgument); var importSearchPath = _.find(searchPaths, function (path) { return importAbsolutePath.indexOf(path) === 0; }); if (importSearchPath) { return path.relative(importSearchPath, importAbsolutePath); } }
[ "function", "importArgumentRelativeToSearchPaths", "(", "importer", ",", "importArgument", ",", "searchPaths", ")", "{", "var", "importAbsolutePath", "=", "path", ".", "resolve", "(", "path", ".", "dirname", "(", "importer", ")", ",", "importArgument", ")", ";", "var", "importSearchPath", "=", "_", ".", "find", "(", "searchPaths", ",", "function", "(", "path", ")", "{", "return", "importAbsolutePath", ".", "indexOf", "(", "path", ")", "===", "0", ";", "}", ")", ";", "if", "(", "importSearchPath", ")", "{", "return", "path", ".", "relative", "(", "importSearchPath", ",", "importAbsolutePath", ")", ";", "}", "}" ]
Returns the argument of the @import() call relative to the asset search paths.
[ "Returns", "the", "argument", "of", "the" ]
a44368093bf11545712378f19c1a0139eafe13e4
https://github.com/nodeca/mincer/blob/a44368093bf11545712378f19c1a0139eafe13e4/lib/mincer/engines/sass_engine.js#L141-L149
train
blakeembrey/array-flatten
array-flatten.js
flattenDepth
function flattenDepth (array, depth) { if (!Array.isArray(array)) { throw new TypeError('Expected value to be an array') } return flattenFromDepth(array, depth) }
javascript
function flattenDepth (array, depth) { if (!Array.isArray(array)) { throw new TypeError('Expected value to be an array') } return flattenFromDepth(array, depth) }
[ "function", "flattenDepth", "(", "array", ",", "depth", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "array", ")", ")", "{", "throw", "new", "TypeError", "(", "'Expected value to be an array'", ")", "}", "return", "flattenFromDepth", "(", "array", ",", "depth", ")", "}" ]
Flatten an array-like structure with depth. @param {Array} array @param {number} depth @return {Array}
[ "Flatten", "an", "array", "-", "like", "structure", "with", "depth", "." ]
04b45e7a5a9fb7e7946a1321287a09e84f1d352d
https://github.com/blakeembrey/array-flatten/blob/04b45e7a5a9fb7e7946a1321287a09e84f1d352d/array-flatten.js#L42-L48
train
blakeembrey/array-flatten
array-flatten.js
flattenDown
function flattenDown (array, result) { for (var i = 0; i < array.length; i++) { var value = array[i] if (Array.isArray(value)) { flattenDown(value, result) } else { result.push(value) } } return result }
javascript
function flattenDown (array, result) { for (var i = 0; i < array.length; i++) { var value = array[i] if (Array.isArray(value)) { flattenDown(value, result) } else { result.push(value) } } return result }
[ "function", "flattenDown", "(", "array", ",", "result", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "var", "value", "=", "array", "[", "i", "]", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "flattenDown", "(", "value", ",", "result", ")", "}", "else", "{", "result", ".", "push", "(", "value", ")", "}", "}", "return", "result", "}" ]
Flatten an array indefinitely. @param {Array} array @param {Array} result @return {Array}
[ "Flatten", "an", "array", "indefinitely", "." ]
04b45e7a5a9fb7e7946a1321287a09e84f1d352d
https://github.com/blakeembrey/array-flatten/blob/04b45e7a5a9fb7e7946a1321287a09e84f1d352d/array-flatten.js#L72-L84
train
blakeembrey/array-flatten
array-flatten.js
flattenDownDepth
function flattenDownDepth (array, result, depth) { depth-- for (var i = 0; i < array.length; i++) { var value = array[i] if (depth > -1 && Array.isArray(value)) { flattenDownDepth(value, result, depth) } else { result.push(value) } } return result }
javascript
function flattenDownDepth (array, result, depth) { depth-- for (var i = 0; i < array.length; i++) { var value = array[i] if (depth > -1 && Array.isArray(value)) { flattenDownDepth(value, result, depth) } else { result.push(value) } } return result }
[ "function", "flattenDownDepth", "(", "array", ",", "result", ",", "depth", ")", "{", "depth", "--", "for", "(", "var", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "var", "value", "=", "array", "[", "i", "]", "if", "(", "depth", ">", "-", "1", "&&", "Array", ".", "isArray", "(", "value", ")", ")", "{", "flattenDownDepth", "(", "value", ",", "result", ",", "depth", ")", "}", "else", "{", "result", ".", "push", "(", "value", ")", "}", "}", "return", "result", "}" ]
Flatten an array with depth. @param {Array} array @param {Array} result @param {number} depth @return {Array}
[ "Flatten", "an", "array", "with", "depth", "." ]
04b45e7a5a9fb7e7946a1321287a09e84f1d352d
https://github.com/blakeembrey/array-flatten/blob/04b45e7a5a9fb7e7946a1321287a09e84f1d352d/array-flatten.js#L94-L108
train
nodeca/mincer
lib/mincer/base.js
matches_filter
function matches_filter(filters, logicalPath, filename) { if (filters.length === 0) { return true; } return _.some(filters, function (filter) { if (_.isRegExp(filter)) { return filter.test(logicalPath); } if (_.isFunction(filter)) { return filter(logicalPath, filename); } // prepare string to become RegExp. // mimics shell's globbing filter = filter.toString().replace(/\*\*|\*|\?|\\.|\./g, function (m) { if (m[0] === '*') { return m === '**' ? '.+?' : '[^/]+?'; } if (m[0] === '?') { return '[^/]?'; } if (m[0] === '.') { return '\\.'; } // handle `\\.` part return m; }); // prepare RegExp filter = new RegExp('^' + filter + '$'); return filter.test(logicalPath); }); }
javascript
function matches_filter(filters, logicalPath, filename) { if (filters.length === 0) { return true; } return _.some(filters, function (filter) { if (_.isRegExp(filter)) { return filter.test(logicalPath); } if (_.isFunction(filter)) { return filter(logicalPath, filename); } // prepare string to become RegExp. // mimics shell's globbing filter = filter.toString().replace(/\*\*|\*|\?|\\.|\./g, function (m) { if (m[0] === '*') { return m === '**' ? '.+?' : '[^/]+?'; } if (m[0] === '?') { return '[^/]?'; } if (m[0] === '.') { return '\\.'; } // handle `\\.` part return m; }); // prepare RegExp filter = new RegExp('^' + filter + '$'); return filter.test(logicalPath); }); }
[ "function", "matches_filter", "(", "filters", ",", "logicalPath", ",", "filename", ")", "{", "if", "(", "filters", ".", "length", "===", "0", ")", "{", "return", "true", ";", "}", "return", "_", ".", "some", "(", "filters", ",", "function", "(", "filter", ")", "{", "if", "(", "_", ".", "isRegExp", "(", "filter", ")", ")", "{", "return", "filter", ".", "test", "(", "logicalPath", ")", ";", "}", "if", "(", "_", ".", "isFunction", "(", "filter", ")", ")", "{", "return", "filter", "(", "logicalPath", ",", "filename", ")", ";", "}", "filter", "=", "filter", ".", "toString", "(", ")", ".", "replace", "(", "/", "\\*\\*|\\*|\\?|\\\\.|\\.", "/", "g", ",", "function", "(", "m", ")", "{", "if", "(", "m", "[", "0", "]", "===", "'*'", ")", "{", "return", "m", "===", "'**'", "?", "'.+?'", ":", "'[^/]+?'", ";", "}", "if", "(", "m", "[", "0", "]", "===", "'?'", ")", "{", "return", "'[^/]?'", ";", "}", "if", "(", "m", "[", "0", "]", "===", "'.'", ")", "{", "return", "'\\\\.'", ";", "}", "\\\\", "}", ")", ";", "return", "m", ";", "filter", "=", "new", "RegExp", "(", "'^'", "+", "filter", "+", "'$'", ")", ";", "}", ")", ";", "}" ]
Returns true if there were no filters, or `filename` matches at least one
[ "Returns", "true", "if", "there", "were", "no", "filters", "or", "filename", "matches", "at", "least", "one" ]
a44368093bf11545712378f19c1a0139eafe13e4
https://github.com/nodeca/mincer/blob/a44368093bf11545712378f19c1a0139eafe13e4/lib/mincer/base.js#L414-L451
train
nodeca/mincer
lib/mincer/base.js
logical_path_for_filename
function logical_path_for_filename(self, filename, filters) { var logical_path = self.attributesFor(filename).logicalPath; if (matches_filter(filters, logical_path, filename)) { return logical_path; } // If filename is an index file, retest with alias if (path.basename(filename).split('.').shift() === 'index') { logical_path = logical_path.replace(/\/index\./, '.'); if (matches_filter(filters, logical_path, filename)) { return logical_path; } } }
javascript
function logical_path_for_filename(self, filename, filters) { var logical_path = self.attributesFor(filename).logicalPath; if (matches_filter(filters, logical_path, filename)) { return logical_path; } // If filename is an index file, retest with alias if (path.basename(filename).split('.').shift() === 'index') { logical_path = logical_path.replace(/\/index\./, '.'); if (matches_filter(filters, logical_path, filename)) { return logical_path; } } }
[ "function", "logical_path_for_filename", "(", "self", ",", "filename", ",", "filters", ")", "{", "var", "logical_path", "=", "self", ".", "attributesFor", "(", "filename", ")", ".", "logicalPath", ";", "if", "(", "matches_filter", "(", "filters", ",", "logical_path", ",", "filename", ")", ")", "{", "return", "logical_path", ";", "}", "if", "(", "path", ".", "basename", "(", "filename", ")", ".", "split", "(", "'.'", ")", ".", "shift", "(", ")", "===", "'index'", ")", "{", "logical_path", "=", "logical_path", ".", "replace", "(", "/", "\\/index\\.", "/", ",", "'.'", ")", ";", "if", "(", "matches_filter", "(", "filters", ",", "logical_path", ",", "filename", ")", ")", "{", "return", "logical_path", ";", "}", "}", "}" ]
Returns logicalPath for `filename` if it matches given filters
[ "Returns", "logicalPath", "for", "filename", "if", "it", "matches", "given", "filters" ]
a44368093bf11545712378f19c1a0139eafe13e4
https://github.com/nodeca/mincer/blob/a44368093bf11545712378f19c1a0139eafe13e4/lib/mincer/base.js#L455-L469
train
nodeca/mincer
examples/server.js
rewrite_extension
function rewrite_extension(source, ext) { var source_ext = path.extname(source); return (source_ext === ext) ? source : (source + ext); }
javascript
function rewrite_extension(source, ext) { var source_ext = path.extname(source); return (source_ext === ext) ? source : (source + ext); }
[ "function", "rewrite_extension", "(", "source", ",", "ext", ")", "{", "var", "source_ext", "=", "path", ".", "extname", "(", "source", ")", ";", "return", "(", "source_ext", "===", "ext", ")", "?", "source", ":", "(", "source", "+", "ext", ")", ";", "}" ]
dummy helper that injects extension
[ "dummy", "helper", "that", "injects", "extension" ]
a44368093bf11545712378f19c1a0139eafe13e4
https://github.com/nodeca/mincer/blob/a44368093bf11545712378f19c1a0139eafe13e4/examples/server.js#L68-L71
train
nodeca/mincer
lib/mincer/helpers/configuring.js
configuration
function configuration(self, name) { if (!self.__configurations__[name]) { throw new Error('Unknown configuration: ' + name); } return self.__configurations__[name]; }
javascript
function configuration(self, name) { if (!self.__configurations__[name]) { throw new Error('Unknown configuration: ' + name); } return self.__configurations__[name]; }
[ "function", "configuration", "(", "self", ",", "name", ")", "{", "if", "(", "!", "self", ".", "__configurations__", "[", "name", "]", ")", "{", "throw", "new", "Error", "(", "'Unknown configuration: '", "+", "name", ")", ";", "}", "return", "self", ".", "__configurations__", "[", "name", "]", ";", "}" ]
unified access to a config hash by name
[ "unified", "access", "to", "a", "config", "hash", "by", "name" ]
a44368093bf11545712378f19c1a0139eafe13e4
https://github.com/nodeca/mincer/blob/a44368093bf11545712378f19c1a0139eafe13e4/lib/mincer/helpers/configuring.js#L57-L63
train
nodeca/mincer
lib/mincer/assets/asset.js
stub_getter
function stub_getter(name) { getter(Asset.prototype, name, function () { // this should never happen, as Asset is an abstract class and not // supposed to be used directly. subclasses must override this getters throw new Error(this.constructor.name + '#' + name + ' getter is not implemented.'); }); }
javascript
function stub_getter(name) { getter(Asset.prototype, name, function () { // this should never happen, as Asset is an abstract class and not // supposed to be used directly. subclasses must override this getters throw new Error(this.constructor.name + '#' + name + ' getter is not implemented.'); }); }
[ "function", "stub_getter", "(", "name", ")", "{", "getter", "(", "Asset", ".", "prototype", ",", "name", ",", "function", "(", ")", "{", "throw", "new", "Error", "(", "this", ".", "constructor", ".", "name", "+", "'#'", "+", "name", "+", "' getter is not implemented.'", ")", ";", "}", ")", ";", "}" ]
helper to sub-out getters of Asset.prototype
[ "helper", "to", "sub", "-", "out", "getters", "of", "Asset", ".", "prototype" ]
a44368093bf11545712378f19c1a0139eafe13e4
https://github.com/nodeca/mincer/blob/a44368093bf11545712378f19c1a0139eafe13e4/lib/mincer/assets/asset.js#L72-L78
train
nodeca/mincer
lib/mincer/server.js
end
function end(res, code) { if (code >= 400) { // check res object contains connect/express request and next structure if (res.req && res.req.next) { var error = new Error(http.STATUS_CODES[code]); error.status = code; return res.req.next(error); } // write human-friendly error message res.writeHead(code); res.end('[' + code + '] ' + http.STATUS_CODES[code]); return; } // just end with no body for 304 responses and such res.writeHead(code); res.end(); }
javascript
function end(res, code) { if (code >= 400) { // check res object contains connect/express request and next structure if (res.req && res.req.next) { var error = new Error(http.STATUS_CODES[code]); error.status = code; return res.req.next(error); } // write human-friendly error message res.writeHead(code); res.end('[' + code + '] ' + http.STATUS_CODES[code]); return; } // just end with no body for 304 responses and such res.writeHead(code); res.end(); }
[ "function", "end", "(", "res", ",", "code", ")", "{", "if", "(", "code", ">=", "400", ")", "{", "if", "(", "res", ".", "req", "&&", "res", ".", "req", ".", "next", ")", "{", "var", "error", "=", "new", "Error", "(", "http", ".", "STATUS_CODES", "[", "code", "]", ")", ";", "error", ".", "status", "=", "code", ";", "return", "res", ".", "req", ".", "next", "(", "error", ")", ";", "}", "res", ".", "writeHead", "(", "code", ")", ";", "res", ".", "end", "(", "'['", "+", "code", "+", "'] '", "+", "http", ".", "STATUS_CODES", "[", "code", "]", ")", ";", "return", ";", "}", "res", ".", "writeHead", "(", "code", ")", ";", "res", ".", "end", "(", ")", ";", "}" ]
Helper to write the code and end response
[ "Helper", "to", "write", "the", "code", "and", "end", "response" ]
a44368093bf11545712378f19c1a0139eafe13e4
https://github.com/nodeca/mincer/blob/a44368093bf11545712378f19c1a0139eafe13e4/lib/mincer/server.js#L82-L100
train
nodeca/mincer
lib/mincer/server.js
log_event
function log_event(req, code, message, elapsed) { return { code: code, message: message, elapsed: elapsed, request: req, url: req.originalUrl || req.url, method: req.method, headers: req.headers, httpVersion: req.httpVersion, remoteAddress: req.connection.remoteAddress }; }
javascript
function log_event(req, code, message, elapsed) { return { code: code, message: message, elapsed: elapsed, request: req, url: req.originalUrl || req.url, method: req.method, headers: req.headers, httpVersion: req.httpVersion, remoteAddress: req.connection.remoteAddress }; }
[ "function", "log_event", "(", "req", ",", "code", ",", "message", ",", "elapsed", ")", "{", "return", "{", "code", ":", "code", ",", "message", ":", "message", ",", "elapsed", ":", "elapsed", ",", "request", ":", "req", ",", "url", ":", "req", ".", "originalUrl", "||", "req", ".", "url", ",", "method", ":", "req", ".", "method", ",", "headers", ":", "req", ".", "headers", ",", "httpVersion", ":", "req", ".", "httpVersion", ",", "remoteAddress", ":", "req", ".", "connection", ".", "remoteAddress", "}", ";", "}" ]
Returns log event structure.
[ "Returns", "log", "event", "structure", "." ]
a44368093bf11545712378f19c1a0139eafe13e4
https://github.com/nodeca/mincer/blob/a44368093bf11545712378f19c1a0139eafe13e4/lib/mincer/server.js#L124-L136
train
Microsoft/taco-team-build
lib/ttb-cache.js
getModuleVersionFromConfig
function getModuleVersionFromConfig(config) { if (config.moduleVersion === undefined && config.nodePackageName == CORDOVA) { // If no version is set, try to get the version from taco.json // This check is specific to the Cordova module if (utilities.fileExistsSync(path.join(config.projectPath, 'taco.json'))) { var version = require(path.join(config.projectPath, 'taco.json'))['cordova-cli']; if (version) { console.log('Cordova version set to ' + version + ' based on the contents of taco.json'); return version; } } } return config.moduleVersion || process.env[makeDefaultEnvironmentVariable(config.nodePackageName)]; }
javascript
function getModuleVersionFromConfig(config) { if (config.moduleVersion === undefined && config.nodePackageName == CORDOVA) { // If no version is set, try to get the version from taco.json // This check is specific to the Cordova module if (utilities.fileExistsSync(path.join(config.projectPath, 'taco.json'))) { var version = require(path.join(config.projectPath, 'taco.json'))['cordova-cli']; if (version) { console.log('Cordova version set to ' + version + ' based on the contents of taco.json'); return version; } } } return config.moduleVersion || process.env[makeDefaultEnvironmentVariable(config.nodePackageName)]; }
[ "function", "getModuleVersionFromConfig", "(", "config", ")", "{", "if", "(", "config", ".", "moduleVersion", "===", "undefined", "&&", "config", ".", "nodePackageName", "==", "CORDOVA", ")", "{", "if", "(", "utilities", ".", "fileExistsSync", "(", "path", ".", "join", "(", "config", ".", "projectPath", ",", "'taco.json'", ")", ")", ")", "{", "var", "version", "=", "require", "(", "path", ".", "join", "(", "config", ".", "projectPath", ",", "'taco.json'", ")", ")", "[", "'cordova-cli'", "]", ";", "if", "(", "version", ")", "{", "console", ".", "log", "(", "'Cordova version set to '", "+", "version", "+", "' based on the contents of taco.json'", ")", ";", "return", "version", ";", "}", "}", "}", "return", "config", ".", "moduleVersion", "||", "process", ".", "env", "[", "makeDefaultEnvironmentVariable", "(", "config", ".", "nodePackageName", ")", "]", ";", "}" ]
Extracts the module version from a configuration
[ "Extracts", "the", "module", "version", "from", "a", "configuration" ]
c9f0f678efd42e1a7f6f953a30ab13213d4f8dae
https://github.com/Microsoft/taco-team-build/blob/c9f0f678efd42e1a7f6f953a30ab13213d4f8dae/lib/ttb-cache.js#L23-L38
train
Microsoft/taco-team-build
lib/ttb-cache.js
cacheModule
function cacheModule(config) { config = utilities.parseConfig(config); var moduleCache = utilities.getCachePath(); console.log('Module cache at ' + moduleCache); var version = getModuleVersionFromConfig(config); var pkgStr = config.nodePackageName + (version ? '@' + version : ''); return utilities.getVersionForNpmPackage(pkgStr).then(function (versionString) { // Install correct cordova version if not available var packagePath = path.join(moduleCache, config.nodePackageName || CORDOVA); var versionPath = path.join(packagePath, version ? version : versionString); var targetModulePath = path.join(versionPath, 'node_modules', config.nodePackageName) if (!utilities.fileExistsSync(targetModulePath)) { // Fix: Check module is there not just root path if (!utilities.fileExistsSync(packagePath)) { fs.mkdirSync(packagePath); } if (!utilities.fileExistsSync(versionPath)) { fs.mkdirSync(versionPath); fs.mkdirSync(path.join(versionPath, 'node_modules')); // node_modules being present ensures correct install loc } console.log('Installing ' + pkgStr + ' to ' + versionPath + '. (This may take a few minutes.)'); var cmd = 'npm install --force ' + pkgStr + ' 2>&1'; return exec(cmd, { cwd: versionPath }) .then(utilities.handleExecReturn) .then(function () { return { version: version, path: targetModulePath }; }); } else { console.log(pkgStr + ' already installed.'); return Q({ version: version, path: targetModulePath }); } }); }
javascript
function cacheModule(config) { config = utilities.parseConfig(config); var moduleCache = utilities.getCachePath(); console.log('Module cache at ' + moduleCache); var version = getModuleVersionFromConfig(config); var pkgStr = config.nodePackageName + (version ? '@' + version : ''); return utilities.getVersionForNpmPackage(pkgStr).then(function (versionString) { // Install correct cordova version if not available var packagePath = path.join(moduleCache, config.nodePackageName || CORDOVA); var versionPath = path.join(packagePath, version ? version : versionString); var targetModulePath = path.join(versionPath, 'node_modules', config.nodePackageName) if (!utilities.fileExistsSync(targetModulePath)) { // Fix: Check module is there not just root path if (!utilities.fileExistsSync(packagePath)) { fs.mkdirSync(packagePath); } if (!utilities.fileExistsSync(versionPath)) { fs.mkdirSync(versionPath); fs.mkdirSync(path.join(versionPath, 'node_modules')); // node_modules being present ensures correct install loc } console.log('Installing ' + pkgStr + ' to ' + versionPath + '. (This may take a few minutes.)'); var cmd = 'npm install --force ' + pkgStr + ' 2>&1'; return exec(cmd, { cwd: versionPath }) .then(utilities.handleExecReturn) .then(function () { return { version: version, path: targetModulePath }; }); } else { console.log(pkgStr + ' already installed.'); return Q({ version: version, path: targetModulePath }); } }); }
[ "function", "cacheModule", "(", "config", ")", "{", "config", "=", "utilities", ".", "parseConfig", "(", "config", ")", ";", "var", "moduleCache", "=", "utilities", ".", "getCachePath", "(", ")", ";", "console", ".", "log", "(", "'Module cache at '", "+", "moduleCache", ")", ";", "var", "version", "=", "getModuleVersionFromConfig", "(", "config", ")", ";", "var", "pkgStr", "=", "config", ".", "nodePackageName", "+", "(", "version", "?", "'@'", "+", "version", ":", "''", ")", ";", "return", "utilities", ".", "getVersionForNpmPackage", "(", "pkgStr", ")", ".", "then", "(", "function", "(", "versionString", ")", "{", "var", "packagePath", "=", "path", ".", "join", "(", "moduleCache", ",", "config", ".", "nodePackageName", "||", "CORDOVA", ")", ";", "var", "versionPath", "=", "path", ".", "join", "(", "packagePath", ",", "version", "?", "version", ":", "versionString", ")", ";", "var", "targetModulePath", "=", "path", ".", "join", "(", "versionPath", ",", "'node_modules'", ",", "config", ".", "nodePackageName", ")", "if", "(", "!", "utilities", ".", "fileExistsSync", "(", "targetModulePath", ")", ")", "{", "if", "(", "!", "utilities", ".", "fileExistsSync", "(", "packagePath", ")", ")", "{", "fs", ".", "mkdirSync", "(", "packagePath", ")", ";", "}", "if", "(", "!", "utilities", ".", "fileExistsSync", "(", "versionPath", ")", ")", "{", "fs", ".", "mkdirSync", "(", "versionPath", ")", ";", "fs", ".", "mkdirSync", "(", "path", ".", "join", "(", "versionPath", ",", "'node_modules'", ")", ")", ";", "}", "console", ".", "log", "(", "'Installing '", "+", "pkgStr", "+", "' to '", "+", "versionPath", "+", "'. (This may take a few minutes.)'", ")", ";", "var", "cmd", "=", "'npm install --force '", "+", "pkgStr", "+", "' 2>&1'", ";", "return", "exec", "(", "cmd", ",", "{", "cwd", ":", "versionPath", "}", ")", ".", "then", "(", "utilities", ".", "handleExecReturn", ")", ".", "then", "(", "function", "(", ")", "{", "return", "{", "version", ":", "version", ",", "path", ":", "targetModulePath", "}", ";", "}", ")", ";", "}", "else", "{", "console", ".", "log", "(", "pkgStr", "+", "' already installed.'", ")", ";", "return", "Q", "(", "{", "version", ":", "version", ",", "path", ":", "targetModulePath", "}", ")", ";", "}", "}", ")", ";", "}" ]
Install module method
[ "Install", "module", "method" ]
c9f0f678efd42e1a7f6f953a30ab13213d4f8dae
https://github.com/Microsoft/taco-team-build/blob/c9f0f678efd42e1a7f6f953a30ab13213d4f8dae/lib/ttb-cache.js#L49-L90
train
Microsoft/taco-team-build
lib/ttb-cache.js
loadModule
function loadModule(modulePath) { // Setup environment if (loadedModule === undefined || loadedModulePath != modulePath) { loadedModule = require(modulePath); loadedModulePath = modulePath; return Q(loadedModule); } else { return Q(loadedModule); } }
javascript
function loadModule(modulePath) { // Setup environment if (loadedModule === undefined || loadedModulePath != modulePath) { loadedModule = require(modulePath); loadedModulePath = modulePath; return Q(loadedModule); } else { return Q(loadedModule); } }
[ "function", "loadModule", "(", "modulePath", ")", "{", "if", "(", "loadedModule", "===", "undefined", "||", "loadedModulePath", "!=", "modulePath", ")", "{", "loadedModule", "=", "require", "(", "modulePath", ")", ";", "loadedModulePath", "=", "modulePath", ";", "return", "Q", "(", "loadedModule", ")", ";", "}", "else", "{", "return", "Q", "(", "loadedModule", ")", ";", "}", "}" ]
Utility method that loads a previously cached module and returns a promise that resolves to that object
[ "Utility", "method", "that", "loads", "a", "previously", "cached", "module", "and", "returns", "a", "promise", "that", "resolves", "to", "that", "object" ]
c9f0f678efd42e1a7f6f953a30ab13213d4f8dae
https://github.com/Microsoft/taco-team-build/blob/c9f0f678efd42e1a7f6f953a30ab13213d4f8dae/lib/ttb-cache.js#L93-L103
train
Microsoft/taco-team-build
lib/ttb-util.js
getCallArgs
function getCallArgs(platforms, args, cordovaVersion) { // Processes single platform string (or array of length 1) and an array of args or an object of args per platform args = args || []; if (typeof (platforms) == 'string') { platforms = [platforms]; } // If only one platform is specified, check if the args is an object and use the args for this platform if so var options = args; if (platforms.length == 1 && !(args instanceof Array)) { options = args[platforms[0]]; } // 5.4.0 changes the way arguments are passed to build. Rather than just having an array // of options, it needs to be an object with an "argv" member for the arguments. // A change was added in 6.0.0 that required the new format to be more complete. // Workaround for now is to use the old way that 6.0.0 has a fallback for. if (semver.valid(cordovaVersion) && semver.gte(cordovaVersion, '5.4.0') && semver.lt(cordovaVersion, '6.0.0')) { return { platforms: platforms, options: { argv: options } }; } else { return { platforms: platforms, options: options }; } }
javascript
function getCallArgs(platforms, args, cordovaVersion) { // Processes single platform string (or array of length 1) and an array of args or an object of args per platform args = args || []; if (typeof (platforms) == 'string') { platforms = [platforms]; } // If only one platform is specified, check if the args is an object and use the args for this platform if so var options = args; if (platforms.length == 1 && !(args instanceof Array)) { options = args[platforms[0]]; } // 5.4.0 changes the way arguments are passed to build. Rather than just having an array // of options, it needs to be an object with an "argv" member for the arguments. // A change was added in 6.0.0 that required the new format to be more complete. // Workaround for now is to use the old way that 6.0.0 has a fallback for. if (semver.valid(cordovaVersion) && semver.gte(cordovaVersion, '5.4.0') && semver.lt(cordovaVersion, '6.0.0')) { return { platforms: platforms, options: { argv: options } }; } else { return { platforms: platforms, options: options }; } }
[ "function", "getCallArgs", "(", "platforms", ",", "args", ",", "cordovaVersion", ")", "{", "args", "=", "args", "||", "[", "]", ";", "if", "(", "typeof", "(", "platforms", ")", "==", "'string'", ")", "{", "platforms", "=", "[", "platforms", "]", ";", "}", "var", "options", "=", "args", ";", "if", "(", "platforms", ".", "length", "==", "1", "&&", "!", "(", "args", "instanceof", "Array", ")", ")", "{", "options", "=", "args", "[", "platforms", "[", "0", "]", "]", ";", "}", "if", "(", "semver", ".", "valid", "(", "cordovaVersion", ")", "&&", "semver", ".", "gte", "(", "cordovaVersion", ",", "'5.4.0'", ")", "&&", "semver", ".", "lt", "(", "cordovaVersion", ",", "'6.0.0'", ")", ")", "{", "return", "{", "platforms", ":", "platforms", ",", "options", ":", "{", "argv", ":", "options", "}", "}", ";", "}", "else", "{", "return", "{", "platforms", ":", "platforms", ",", "options", ":", "options", "}", ";", "}", "}" ]
Utility method that coverts args into a consistant input understood by cordova-lib
[ "Utility", "method", "that", "coverts", "args", "into", "a", "consistant", "input", "understood", "by", "cordova", "-", "lib" ]
c9f0f678efd42e1a7f6f953a30ab13213d4f8dae
https://github.com/Microsoft/taco-team-build/blob/c9f0f678efd42e1a7f6f953a30ab13213d4f8dae/lib/ttb-util.js#L87-L109
train
Microsoft/taco-team-build
lib/ttb-util.js
isCompatibleNpmPackage
function isCompatibleNpmPackage(pkgName) { if (pkgName !== 'cordova' && pkgName.indexOf('cordova@') !== 0) { return Q(NodeCompatibilityResult.Compatible); } // Get the version of npm and the version of cordova requested. If the // cordova version <= 5.3.3, and the Node version is 5.0.0, the build // is going to fail, but silently, so we need to be loud now. return getVersionForNpmPackage(pkgName).then(function (cordovaVersion) { if (!semver.valid(cordovaVersion)) { // Assume true, since we don't know what version this is and the npm install will probably fail anyway return Q(NodeCompatibilityResult.Compatible); } var nodeVersion = process.version; if (!semver.valid(nodeVersion)) { return Q(NodeCompatibilityResult.Compatible); } if (semver.lt(cordovaVersion, '5.4.0') && semver.gte(nodeVersion, '5.0.0')) { return Q(NodeCompatibilityResult.IncompatibleVersion5); } else if (process.platform == 'darwin' && semver.lt(cordovaVersion, '5.3.3') && semver.gte(nodeVersion, '4.0.0')) { return Q(NodeCompatibilityResult.IncompatibleVersion4Ios); } else { return Q(NodeCompatibilityResult.Compatible); } }); }
javascript
function isCompatibleNpmPackage(pkgName) { if (pkgName !== 'cordova' && pkgName.indexOf('cordova@') !== 0) { return Q(NodeCompatibilityResult.Compatible); } // Get the version of npm and the version of cordova requested. If the // cordova version <= 5.3.3, and the Node version is 5.0.0, the build // is going to fail, but silently, so we need to be loud now. return getVersionForNpmPackage(pkgName).then(function (cordovaVersion) { if (!semver.valid(cordovaVersion)) { // Assume true, since we don't know what version this is and the npm install will probably fail anyway return Q(NodeCompatibilityResult.Compatible); } var nodeVersion = process.version; if (!semver.valid(nodeVersion)) { return Q(NodeCompatibilityResult.Compatible); } if (semver.lt(cordovaVersion, '5.4.0') && semver.gte(nodeVersion, '5.0.0')) { return Q(NodeCompatibilityResult.IncompatibleVersion5); } else if (process.platform == 'darwin' && semver.lt(cordovaVersion, '5.3.3') && semver.gte(nodeVersion, '4.0.0')) { return Q(NodeCompatibilityResult.IncompatibleVersion4Ios); } else { return Q(NodeCompatibilityResult.Compatible); } }); }
[ "function", "isCompatibleNpmPackage", "(", "pkgName", ")", "{", "if", "(", "pkgName", "!==", "'cordova'", "&&", "pkgName", ".", "indexOf", "(", "'cordova@'", ")", "!==", "0", ")", "{", "return", "Q", "(", "NodeCompatibilityResult", ".", "Compatible", ")", ";", "}", "return", "getVersionForNpmPackage", "(", "pkgName", ")", ".", "then", "(", "function", "(", "cordovaVersion", ")", "{", "if", "(", "!", "semver", ".", "valid", "(", "cordovaVersion", ")", ")", "{", "return", "Q", "(", "NodeCompatibilityResult", ".", "Compatible", ")", ";", "}", "var", "nodeVersion", "=", "process", ".", "version", ";", "if", "(", "!", "semver", ".", "valid", "(", "nodeVersion", ")", ")", "{", "return", "Q", "(", "NodeCompatibilityResult", ".", "Compatible", ")", ";", "}", "if", "(", "semver", ".", "lt", "(", "cordovaVersion", ",", "'5.4.0'", ")", "&&", "semver", ".", "gte", "(", "nodeVersion", ",", "'5.0.0'", ")", ")", "{", "return", "Q", "(", "NodeCompatibilityResult", ".", "IncompatibleVersion5", ")", ";", "}", "else", "if", "(", "process", ".", "platform", "==", "'darwin'", "&&", "semver", ".", "lt", "(", "cordovaVersion", ",", "'5.3.3'", ")", "&&", "semver", ".", "gte", "(", "nodeVersion", ",", "'4.0.0'", ")", ")", "{", "return", "Q", "(", "NodeCompatibilityResult", ".", "IncompatibleVersion4Ios", ")", ";", "}", "else", "{", "return", "Q", "(", "NodeCompatibilityResult", ".", "Compatible", ")", ";", "}", "}", ")", ";", "}" ]
Returns a promise that resolves to whether or not the currently installed version of Node is compatible with the requested version of cordova.
[ "Returns", "a", "promise", "that", "resolves", "to", "whether", "or", "not", "the", "currently", "installed", "version", "of", "Node", "is", "compatible", "with", "the", "requested", "version", "of", "cordova", "." ]
c9f0f678efd42e1a7f6f953a30ab13213d4f8dae
https://github.com/Microsoft/taco-team-build/blob/c9f0f678efd42e1a7f6f953a30ab13213d4f8dae/lib/ttb-util.js#L133-L161
train
Microsoft/taco-team-build
taco-team-build.js
applyExecutionBitFix
function applyExecutionBitFix(platforms) { // Only bother if we're on OSX and are after platform add for iOS itself (still need to run for other platforms) if (process.platform !== "darwin" && process.platform !== 'linux') { return Q(); } // Disable -E flag for non-OSX platforms var regex_flag = process.platform == 'darwin' ? '-E' : ''; // Generate the script to set execute bits for installed platforms var script = ""; platforms.forEach(function (platform) { var platformCordovaDir = "platforms/" + platform + "/cordova"; if (utilities.fileExistsSync(platformCordovaDir)) { script += "find " + regex_flag + " " + platformCordovaDir + " -type f -regex \"[^.(LICENSE)]*\" -exec chmod +x {} +\n"; } }); var hooksCordovaDir = "hooks"; if (utilities.fileExistsSync(hooksCordovaDir)) { script += "find " + regex_flag + " " + hooksCordovaDir + " -type f -exec chmod +x {} +\n"; } script += "find " + regex_flag + " . -name '*.sh' -type f -exec chmod +x {} +\n"; // Run script return exec(script); }
javascript
function applyExecutionBitFix(platforms) { // Only bother if we're on OSX and are after platform add for iOS itself (still need to run for other platforms) if (process.platform !== "darwin" && process.platform !== 'linux') { return Q(); } // Disable -E flag for non-OSX platforms var regex_flag = process.platform == 'darwin' ? '-E' : ''; // Generate the script to set execute bits for installed platforms var script = ""; platforms.forEach(function (platform) { var platformCordovaDir = "platforms/" + platform + "/cordova"; if (utilities.fileExistsSync(platformCordovaDir)) { script += "find " + regex_flag + " " + platformCordovaDir + " -type f -regex \"[^.(LICENSE)]*\" -exec chmod +x {} +\n"; } }); var hooksCordovaDir = "hooks"; if (utilities.fileExistsSync(hooksCordovaDir)) { script += "find " + regex_flag + " " + hooksCordovaDir + " -type f -exec chmod +x {} +\n"; } script += "find " + regex_flag + " . -name '*.sh' -type f -exec chmod +x {} +\n"; // Run script return exec(script); }
[ "function", "applyExecutionBitFix", "(", "platforms", ")", "{", "if", "(", "process", ".", "platform", "!==", "\"darwin\"", "&&", "process", ".", "platform", "!==", "'linux'", ")", "{", "return", "Q", "(", ")", ";", "}", "var", "regex_flag", "=", "process", ".", "platform", "==", "'darwin'", "?", "'-E'", ":", "''", ";", "var", "script", "=", "\"\"", ";", "platforms", ".", "forEach", "(", "function", "(", "platform", ")", "{", "var", "platformCordovaDir", "=", "\"platforms/\"", "+", "platform", "+", "\"/cordova\"", ";", "if", "(", "utilities", ".", "fileExistsSync", "(", "platformCordovaDir", ")", ")", "{", "script", "+=", "\"find \"", "+", "regex_flag", "+", "\" \"", "+", "platformCordovaDir", "+", "\" -type f -regex \\\"[^.(LICENSE)]*\\\" -exec chmod +x {} +\\n\"", ";", "}", "}", ")", ";", "\\\"", "\\\"", "\\n", "var", "hooksCordovaDir", "=", "\"hooks\"", ";", "}" ]
It's possible that checking in the platforms folder on Windows and then checking out and building the project on OSX can cause the eXecution bit on the platform version files to be cleared, resulting in errors when performing project operations. This method restores it if needed. It will also set the excute bit on the hooks directory and all shell scripts in the project
[ "It", "s", "possible", "that", "checking", "in", "the", "platforms", "folder", "on", "Windows", "and", "then", "checking", "out", "and", "building", "the", "project", "on", "OSX", "can", "cause", "the", "eXecution", "bit", "on", "the", "platform", "version", "files", "to", "be", "cleared", "resulting", "in", "errors", "when", "performing", "project", "operations", ".", "This", "method", "restores", "it", "if", "needed", ".", "It", "will", "also", "set", "the", "excute", "bit", "on", "the", "hooks", "directory", "and", "all", "shell", "scripts", "in", "the", "project" ]
c9f0f678efd42e1a7f6f953a30ab13213d4f8dae
https://github.com/Microsoft/taco-team-build/blob/c9f0f678efd42e1a7f6f953a30ab13213d4f8dae/taco-team-build.js#L82-L110
train
Microsoft/taco-team-build
taco-team-build.js
prepareProject
function prepareProject(cordovaPlatforms, args, /* optional */ projectPath) { if (typeof (cordovaPlatforms) == "string") { cordovaPlatforms = [cordovaPlatforms]; } if (!projectPath) { projectPath = defaultConfig.projectPath; } var appendedVersion = cache.getModuleVersionFromConfig(defaultConfig); if (appendedVersion) { appendedVersion = '@' + appendedVersion; } else { appendedVersion = ''; } return utilities.isCompatibleNpmPackage(defaultConfig.nodePackageName + appendedVersion).then(function (compatibilityResult) { switch (compatibilityResult) { case utilities.NodeCompatibilityResult.IncompatibleVersion4Ios: throw new Error('This Cordova version does not support Node.js 4.0.0 for iOS builds. Either downgrade to an earlier version of Node.js or move to Cordova 5.3.3 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'); case utilities.NodeCompatibilityResult.IncompatibleVersion5: throw new Error('This Cordova version does not support Node.js 5.0.0 or later. Either downgrade to an earlier version of Node.js or move to Cordova 5.4.0 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'); } return setupCordova(); }).then(function (cordova) { return addSupportPluginIfRequested(cordova, defaultConfig); }).then(function (cordova) { // Add platforms if not done already var promise = _addPlatformsToProject(cordovaPlatforms, projectPath, cordova); //Build each platform with args in args object cordovaPlatforms.forEach(function (platform) { promise = promise.then(function () { // Build app with platform specific args if specified var callArgs = utilities.getCallArgs(platform, args); var argsString = _getArgsString(callArgs.options); console.log('Queueing prepare for platform ' + platform + ' w/options: ' + argsString); return cordova.raw.prepare(callArgs); }); }); return promise; }); }
javascript
function prepareProject(cordovaPlatforms, args, /* optional */ projectPath) { if (typeof (cordovaPlatforms) == "string") { cordovaPlatforms = [cordovaPlatforms]; } if (!projectPath) { projectPath = defaultConfig.projectPath; } var appendedVersion = cache.getModuleVersionFromConfig(defaultConfig); if (appendedVersion) { appendedVersion = '@' + appendedVersion; } else { appendedVersion = ''; } return utilities.isCompatibleNpmPackage(defaultConfig.nodePackageName + appendedVersion).then(function (compatibilityResult) { switch (compatibilityResult) { case utilities.NodeCompatibilityResult.IncompatibleVersion4Ios: throw new Error('This Cordova version does not support Node.js 4.0.0 for iOS builds. Either downgrade to an earlier version of Node.js or move to Cordova 5.3.3 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'); case utilities.NodeCompatibilityResult.IncompatibleVersion5: throw new Error('This Cordova version does not support Node.js 5.0.0 or later. Either downgrade to an earlier version of Node.js or move to Cordova 5.4.0 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'); } return setupCordova(); }).then(function (cordova) { return addSupportPluginIfRequested(cordova, defaultConfig); }).then(function (cordova) { // Add platforms if not done already var promise = _addPlatformsToProject(cordovaPlatforms, projectPath, cordova); //Build each platform with args in args object cordovaPlatforms.forEach(function (platform) { promise = promise.then(function () { // Build app with platform specific args if specified var callArgs = utilities.getCallArgs(platform, args); var argsString = _getArgsString(callArgs.options); console.log('Queueing prepare for platform ' + platform + ' w/options: ' + argsString); return cordova.raw.prepare(callArgs); }); }); return promise; }); }
[ "function", "prepareProject", "(", "cordovaPlatforms", ",", "args", ",", "projectPath", ")", "{", "if", "(", "typeof", "(", "cordovaPlatforms", ")", "==", "\"string\"", ")", "{", "cordovaPlatforms", "=", "[", "cordovaPlatforms", "]", ";", "}", "if", "(", "!", "projectPath", ")", "{", "projectPath", "=", "defaultConfig", ".", "projectPath", ";", "}", "var", "appendedVersion", "=", "cache", ".", "getModuleVersionFromConfig", "(", "defaultConfig", ")", ";", "if", "(", "appendedVersion", ")", "{", "appendedVersion", "=", "'@'", "+", "appendedVersion", ";", "}", "else", "{", "appendedVersion", "=", "''", ";", "}", "return", "utilities", ".", "isCompatibleNpmPackage", "(", "defaultConfig", ".", "nodePackageName", "+", "appendedVersion", ")", ".", "then", "(", "function", "(", "compatibilityResult", ")", "{", "switch", "(", "compatibilityResult", ")", "{", "case", "utilities", ".", "NodeCompatibilityResult", ".", "IncompatibleVersion4Ios", ":", "throw", "new", "Error", "(", "'This Cordova version does not support Node.js 4.0.0 for iOS builds. Either downgrade to an earlier version of Node.js or move to Cordova 5.3.3 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'", ")", ";", "case", "utilities", ".", "NodeCompatibilityResult", ".", "IncompatibleVersion5", ":", "throw", "new", "Error", "(", "'This Cordova version does not support Node.js 5.0.0 or later. Either downgrade to an earlier version of Node.js or move to Cordova 5.4.0 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'", ")", ";", "}", "return", "setupCordova", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", "cordova", ")", "{", "return", "addSupportPluginIfRequested", "(", "cordova", ",", "defaultConfig", ")", ";", "}", ")", ".", "then", "(", "function", "(", "cordova", ")", "{", "var", "promise", "=", "_addPlatformsToProject", "(", "cordovaPlatforms", ",", "projectPath", ",", "cordova", ")", ";", "cordovaPlatforms", ".", "forEach", "(", "function", "(", "platform", ")", "{", "promise", "=", "promise", ".", "then", "(", "function", "(", ")", "{", "var", "callArgs", "=", "utilities", ".", "getCallArgs", "(", "platform", ",", "args", ")", ";", "var", "argsString", "=", "_getArgsString", "(", "callArgs", ".", "options", ")", ";", "console", ".", "log", "(", "'Queueing prepare for platform '", "+", "platform", "+", "' w/options: '", "+", "argsString", ")", ";", "return", "cordova", ".", "raw", ".", "prepare", "(", "callArgs", ")", ";", "}", ")", ";", "}", ")", ";", "return", "promise", ";", "}", ")", ";", "}" ]
Method to prepare the platforms
[ "Method", "to", "prepare", "the", "platforms" ]
c9f0f678efd42e1a7f6f953a30ab13213d4f8dae
https://github.com/Microsoft/taco-team-build/blob/c9f0f678efd42e1a7f6f953a30ab13213d4f8dae/taco-team-build.js#L180-L223
train
Microsoft/taco-team-build
taco-team-build.js
buildProject
function buildProject(cordovaPlatforms, args, /* optional */ projectPath) { if (typeof (cordovaPlatforms) == 'string') { cordovaPlatforms = [cordovaPlatforms]; } if (!projectPath) { projectPath = defaultConfig.projectPath; } var appendedVersion = cache.getModuleVersionFromConfig(defaultConfig); if (appendedVersion) { appendedVersion = '@' + appendedVersion; } else { appendedVersion = ''; } var cordovaVersion = defaultConfig.moduleVersion; return utilities.isCompatibleNpmPackage(defaultConfig.nodePackageName + appendedVersion).then(function (compatibilityResult) { switch (compatibilityResult) { case utilities.NodeCompatibilityResult.IncompatibleVersion4Ios: throw new Error('This Cordova version does not support Node.js 4.0.0 for iOS builds. Either downgrade to an earlier version of Node.js or move to Cordova 5.3.3 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'); case utilities.NodeCompatibilityResult.IncompatibleVersion5: throw new Error('This Cordova version does not support Node.js 5.0.0 or later. Either downgrade to an earlier version of Node.js or move to Cordova 5.4.0 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'); } return utilities.getVersionForNpmPackage(defaultConfig.nodePackageName + appendedVersion); }).then(function (version) { cordovaVersion = version; return setupCordova(); }).then(function (cordova) { return applyExecutionBitFix(cordovaPlatforms).then(function () { return Q(cordova); }, function (err) { return Q(cordova); }); }).then(function (cordova) { return addSupportPluginIfRequested(cordova, defaultConfig); }).then(function (cordova) { // Add platforms if not done already var promise = _addPlatformsToProject(cordovaPlatforms, projectPath, cordova); //Build each platform with args in args object cordovaPlatforms.forEach(function (platform) { promise = promise.then(function () { // Build app with platform specific args if specified var callArgs = utilities.getCallArgs(platform, args, cordovaVersion); return ensureProjectXcode8Compatibility(projectPath, platform, callArgs); }).then(function() { var callArgs = utilities.getCallArgs(platform, args, cordovaVersion); var argsString = _getArgsString(callArgs.options); console.log('Queueing build for platform ' + platform + ' w/options: ' + argsString); return cordova.raw.build(callArgs); }); }); return promise; }); }
javascript
function buildProject(cordovaPlatforms, args, /* optional */ projectPath) { if (typeof (cordovaPlatforms) == 'string') { cordovaPlatforms = [cordovaPlatforms]; } if (!projectPath) { projectPath = defaultConfig.projectPath; } var appendedVersion = cache.getModuleVersionFromConfig(defaultConfig); if (appendedVersion) { appendedVersion = '@' + appendedVersion; } else { appendedVersion = ''; } var cordovaVersion = defaultConfig.moduleVersion; return utilities.isCompatibleNpmPackage(defaultConfig.nodePackageName + appendedVersion).then(function (compatibilityResult) { switch (compatibilityResult) { case utilities.NodeCompatibilityResult.IncompatibleVersion4Ios: throw new Error('This Cordova version does not support Node.js 4.0.0 for iOS builds. Either downgrade to an earlier version of Node.js or move to Cordova 5.3.3 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'); case utilities.NodeCompatibilityResult.IncompatibleVersion5: throw new Error('This Cordova version does not support Node.js 5.0.0 or later. Either downgrade to an earlier version of Node.js or move to Cordova 5.4.0 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'); } return utilities.getVersionForNpmPackage(defaultConfig.nodePackageName + appendedVersion); }).then(function (version) { cordovaVersion = version; return setupCordova(); }).then(function (cordova) { return applyExecutionBitFix(cordovaPlatforms).then(function () { return Q(cordova); }, function (err) { return Q(cordova); }); }).then(function (cordova) { return addSupportPluginIfRequested(cordova, defaultConfig); }).then(function (cordova) { // Add platforms if not done already var promise = _addPlatformsToProject(cordovaPlatforms, projectPath, cordova); //Build each platform with args in args object cordovaPlatforms.forEach(function (platform) { promise = promise.then(function () { // Build app with platform specific args if specified var callArgs = utilities.getCallArgs(platform, args, cordovaVersion); return ensureProjectXcode8Compatibility(projectPath, platform, callArgs); }).then(function() { var callArgs = utilities.getCallArgs(platform, args, cordovaVersion); var argsString = _getArgsString(callArgs.options); console.log('Queueing build for platform ' + platform + ' w/options: ' + argsString); return cordova.raw.build(callArgs); }); }); return promise; }); }
[ "function", "buildProject", "(", "cordovaPlatforms", ",", "args", ",", "projectPath", ")", "{", "if", "(", "typeof", "(", "cordovaPlatforms", ")", "==", "'string'", ")", "{", "cordovaPlatforms", "=", "[", "cordovaPlatforms", "]", ";", "}", "if", "(", "!", "projectPath", ")", "{", "projectPath", "=", "defaultConfig", ".", "projectPath", ";", "}", "var", "appendedVersion", "=", "cache", ".", "getModuleVersionFromConfig", "(", "defaultConfig", ")", ";", "if", "(", "appendedVersion", ")", "{", "appendedVersion", "=", "'@'", "+", "appendedVersion", ";", "}", "else", "{", "appendedVersion", "=", "''", ";", "}", "var", "cordovaVersion", "=", "defaultConfig", ".", "moduleVersion", ";", "return", "utilities", ".", "isCompatibleNpmPackage", "(", "defaultConfig", ".", "nodePackageName", "+", "appendedVersion", ")", ".", "then", "(", "function", "(", "compatibilityResult", ")", "{", "switch", "(", "compatibilityResult", ")", "{", "case", "utilities", ".", "NodeCompatibilityResult", ".", "IncompatibleVersion4Ios", ":", "throw", "new", "Error", "(", "'This Cordova version does not support Node.js 4.0.0 for iOS builds. Either downgrade to an earlier version of Node.js or move to Cordova 5.3.3 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'", ")", ";", "case", "utilities", ".", "NodeCompatibilityResult", ".", "IncompatibleVersion5", ":", "throw", "new", "Error", "(", "'This Cordova version does not support Node.js 5.0.0 or later. Either downgrade to an earlier version of Node.js or move to Cordova 5.4.0 or later. See http://go.microsoft.com/fwlink/?LinkID=618471'", ")", ";", "}", "return", "utilities", ".", "getVersionForNpmPackage", "(", "defaultConfig", ".", "nodePackageName", "+", "appendedVersion", ")", ";", "}", ")", ".", "then", "(", "function", "(", "version", ")", "{", "cordovaVersion", "=", "version", ";", "return", "setupCordova", "(", ")", ";", "}", ")", ".", "then", "(", "function", "(", "cordova", ")", "{", "return", "applyExecutionBitFix", "(", "cordovaPlatforms", ")", ".", "then", "(", "function", "(", ")", "{", "return", "Q", "(", "cordova", ")", ";", "}", ",", "function", "(", "err", ")", "{", "return", "Q", "(", "cordova", ")", ";", "}", ")", ";", "}", ")", ".", "then", "(", "function", "(", "cordova", ")", "{", "return", "addSupportPluginIfRequested", "(", "cordova", ",", "defaultConfig", ")", ";", "}", ")", ".", "then", "(", "function", "(", "cordova", ")", "{", "var", "promise", "=", "_addPlatformsToProject", "(", "cordovaPlatforms", ",", "projectPath", ",", "cordova", ")", ";", "cordovaPlatforms", ".", "forEach", "(", "function", "(", "platform", ")", "{", "promise", "=", "promise", ".", "then", "(", "function", "(", ")", "{", "var", "callArgs", "=", "utilities", ".", "getCallArgs", "(", "platform", ",", "args", ",", "cordovaVersion", ")", ";", "return", "ensureProjectXcode8Compatibility", "(", "projectPath", ",", "platform", ",", "callArgs", ")", ";", "}", ")", ".", "then", "(", "function", "(", ")", "{", "var", "callArgs", "=", "utilities", ".", "getCallArgs", "(", "platform", ",", "args", ",", "cordovaVersion", ")", ";", "var", "argsString", "=", "_getArgsString", "(", "callArgs", ".", "options", ")", ";", "console", ".", "log", "(", "'Queueing build for platform '", "+", "platform", "+", "' w/options: '", "+", "argsString", ")", ";", "return", "cordova", ".", "raw", ".", "build", "(", "callArgs", ")", ";", "}", ")", ";", "}", ")", ";", "return", "promise", ";", "}", ")", ";", "}" ]
Main build method
[ "Main", "build", "method" ]
c9f0f678efd42e1a7f6f953a30ab13213d4f8dae
https://github.com/Microsoft/taco-team-build/blob/c9f0f678efd42e1a7f6f953a30ab13213d4f8dae/taco-team-build.js#L226-L282
train
Microsoft/taco-team-build
taco-team-build.js
_addPlatformsToProject
function _addPlatformsToProject(cordovaPlatforms, projectPath, cordova) { var promise = Q(); cordovaPlatforms.forEach(function (platform) { if (!utilities.fileExistsSync(path.join(projectPath, 'platforms', platform))) { promise = promise.then(function () { return cordova.raw.platform('add', platform); }); } else { console.log('Platform ' + platform + ' already added.'); } }); return promise; }
javascript
function _addPlatformsToProject(cordovaPlatforms, projectPath, cordova) { var promise = Q(); cordovaPlatforms.forEach(function (platform) { if (!utilities.fileExistsSync(path.join(projectPath, 'platforms', platform))) { promise = promise.then(function () { return cordova.raw.platform('add', platform); }); } else { console.log('Platform ' + platform + ' already added.'); } }); return promise; }
[ "function", "_addPlatformsToProject", "(", "cordovaPlatforms", ",", "projectPath", ",", "cordova", ")", "{", "var", "promise", "=", "Q", "(", ")", ";", "cordovaPlatforms", ".", "forEach", "(", "function", "(", "platform", ")", "{", "if", "(", "!", "utilities", ".", "fileExistsSync", "(", "path", ".", "join", "(", "projectPath", ",", "'platforms'", ",", "platform", ")", ")", ")", "{", "promise", "=", "promise", ".", "then", "(", "function", "(", ")", "{", "return", "cordova", ".", "raw", ".", "platform", "(", "'add'", ",", "platform", ")", ";", "}", ")", ";", "}", "else", "{", "console", ".", "log", "(", "'Platform '", "+", "platform", "+", "' already added.'", ")", ";", "}", "}", ")", ";", "return", "promise", ";", "}" ]
Prep for build by adding platforms and setting environment variables
[ "Prep", "for", "build", "by", "adding", "platforms", "and", "setting", "environment", "variables" ]
c9f0f678efd42e1a7f6f953a30ab13213d4f8dae
https://github.com/Microsoft/taco-team-build/blob/c9f0f678efd42e1a7f6f953a30ab13213d4f8dae/taco-team-build.js#L293-L304
train
Microsoft/taco-team-build
taco-team-build.js
packageProject
function packageProject(cordovaPlatforms, args, /* optional */ projectPath) { if (typeof (cordovaPlatforms) == 'string') { cordovaPlatforms = [cordovaPlatforms]; } if (!projectPath) { projectPath = defaultConfig.projectPath; } return setupCordova().then(function (cordova) { var promise = Q(cordova); cordovaPlatforms.forEach(function (platform) { if (platform == 'ios') { promise = promise.then(function () { return _createIpa(projectPath, args); }); } else { console.log('Platform ' + platform + ' does not require a separate package step.'); } }); return promise; }); }
javascript
function packageProject(cordovaPlatforms, args, /* optional */ projectPath) { if (typeof (cordovaPlatforms) == 'string') { cordovaPlatforms = [cordovaPlatforms]; } if (!projectPath) { projectPath = defaultConfig.projectPath; } return setupCordova().then(function (cordova) { var promise = Q(cordova); cordovaPlatforms.forEach(function (platform) { if (platform == 'ios') { promise = promise.then(function () { return _createIpa(projectPath, args); }); } else { console.log('Platform ' + platform + ' does not require a separate package step.'); } }); return promise; }); }
[ "function", "packageProject", "(", "cordovaPlatforms", ",", "args", ",", "projectPath", ")", "{", "if", "(", "typeof", "(", "cordovaPlatforms", ")", "==", "'string'", ")", "{", "cordovaPlatforms", "=", "[", "cordovaPlatforms", "]", ";", "}", "if", "(", "!", "projectPath", ")", "{", "projectPath", "=", "defaultConfig", ".", "projectPath", ";", "}", "return", "setupCordova", "(", ")", ".", "then", "(", "function", "(", "cordova", ")", "{", "var", "promise", "=", "Q", "(", "cordova", ")", ";", "cordovaPlatforms", ".", "forEach", "(", "function", "(", "platform", ")", "{", "if", "(", "platform", "==", "'ios'", ")", "{", "promise", "=", "promise", ".", "then", "(", "function", "(", ")", "{", "return", "_createIpa", "(", "projectPath", ",", "args", ")", ";", "}", ")", ";", "}", "else", "{", "console", ".", "log", "(", "'Platform '", "+", "platform", "+", "' does not require a separate package step.'", ")", ";", "}", "}", ")", ";", "return", "promise", ";", "}", ")", ";", "}" ]
Package project method - Just for iOS currently
[ "Package", "project", "method", "-", "Just", "for", "iOS", "currently" ]
c9f0f678efd42e1a7f6f953a30ab13213d4f8dae
https://github.com/Microsoft/taco-team-build/blob/c9f0f678efd42e1a7f6f953a30ab13213d4f8dae/taco-team-build.js#L307-L327
train
Microsoft/taco-team-build
taco-team-build.js
_createIpa
function _createIpa(projectPath, args) { return utilities.getInstalledPlatformVersion(projectPath, 'ios').then(function (version) { if (semver.lt(version, '3.9.0')) { var deferred = Q.defer(); glob(projectPath + '/platforms/ios/build/device/*.app', function (err, matches) { if (err) { deferred.reject(err); } else { if (matches.length != 1) { console.warn('Skipping packaging. Expected one device .app - found ' + matches.length); } else { var cmdString = 'xcrun -sdk iphoneos PackageApplication \'' + matches[0] + '\' -o \'' + path.join(path.dirname(matches[0]), path.basename(matches[0], '.app')) + '.ipa\' '; // Add additional command line args passed var callArgs = utilities.getCallArgs('ios', args); callArgs.options.forEach(function (arg) { cmdString += ' ' + arg; }); console.log('Exec: ' + cmdString); return exec(cmdString) .then(utilities.handleExecReturn) .fail(function (err) { deferred.reject(err); }) .done(function () { deferred.resolve(); }); } } }); return deferred.promise; } else { console.log('Skipping packaging. Detected cordova-ios verison that auto-creates ipa.'); } }); }
javascript
function _createIpa(projectPath, args) { return utilities.getInstalledPlatformVersion(projectPath, 'ios').then(function (version) { if (semver.lt(version, '3.9.0')) { var deferred = Q.defer(); glob(projectPath + '/platforms/ios/build/device/*.app', function (err, matches) { if (err) { deferred.reject(err); } else { if (matches.length != 1) { console.warn('Skipping packaging. Expected one device .app - found ' + matches.length); } else { var cmdString = 'xcrun -sdk iphoneos PackageApplication \'' + matches[0] + '\' -o \'' + path.join(path.dirname(matches[0]), path.basename(matches[0], '.app')) + '.ipa\' '; // Add additional command line args passed var callArgs = utilities.getCallArgs('ios', args); callArgs.options.forEach(function (arg) { cmdString += ' ' + arg; }); console.log('Exec: ' + cmdString); return exec(cmdString) .then(utilities.handleExecReturn) .fail(function (err) { deferred.reject(err); }) .done(function () { deferred.resolve(); }); } } }); return deferred.promise; } else { console.log('Skipping packaging. Detected cordova-ios verison that auto-creates ipa.'); } }); }
[ "function", "_createIpa", "(", "projectPath", ",", "args", ")", "{", "return", "utilities", ".", "getInstalledPlatformVersion", "(", "projectPath", ",", "'ios'", ")", ".", "then", "(", "function", "(", "version", ")", "{", "if", "(", "semver", ".", "lt", "(", "version", ",", "'3.9.0'", ")", ")", "{", "var", "deferred", "=", "Q", ".", "defer", "(", ")", ";", "glob", "(", "projectPath", "+", "'/platforms/ios/build/device/*.app'", ",", "function", "(", "err", ",", "matches", ")", "{", "if", "(", "err", ")", "{", "deferred", ".", "reject", "(", "err", ")", ";", "}", "else", "{", "if", "(", "matches", ".", "length", "!=", "1", ")", "{", "console", ".", "warn", "(", "'Skipping packaging. Expected one device .app - found '", "+", "matches", ".", "length", ")", ";", "}", "else", "{", "var", "cmdString", "=", "'xcrun -sdk iphoneos PackageApplication \\''", "+", "\\'", "+", "matches", "[", "0", "]", "+", "'\\' -o \\''", "+", "\\'", ";", "\\'", "path", ".", "join", "(", "path", ".", "dirname", "(", "matches", "[", "0", "]", ")", ",", "path", ".", "basename", "(", "matches", "[", "0", "]", ",", "'.app'", ")", ")", "'.ipa\\' '", "\\'", "}", "}", "}", ")", ";", "var", "callArgs", "=", "utilities", ".", "getCallArgs", "(", "'ios'", ",", "args", ")", ";", "}", "else", "callArgs", ".", "options", ".", "forEach", "(", "function", "(", "arg", ")", "{", "cmdString", "+=", "' '", "+", "arg", ";", "}", ")", ";", "}", ")", ";", "}" ]
Find the .app folder and use exec to call xcrun with the appropriate set of args
[ "Find", "the", ".", "app", "folder", "and", "use", "exec", "to", "call", "xcrun", "with", "the", "appropriate", "set", "of", "args" ]
c9f0f678efd42e1a7f6f953a30ab13213d4f8dae
https://github.com/Microsoft/taco-team-build/blob/c9f0f678efd42e1a7f6f953a30ab13213d4f8dae/taco-team-build.js#L330-L369
train
Urigo/meteor-rxjs
dist/bundles/index.umd.js
Collection
function Collection(nameOrExisting, options) { if (nameOrExisting instanceof Mongo.Collection) { this._collection = nameOrExisting; } else { this._collection = new Mongo.Collection(nameOrExisting, options); } }
javascript
function Collection(nameOrExisting, options) { if (nameOrExisting instanceof Mongo.Collection) { this._collection = nameOrExisting; } else { this._collection = new Mongo.Collection(nameOrExisting, options); } }
[ "function", "Collection", "(", "nameOrExisting", ",", "options", ")", "{", "if", "(", "nameOrExisting", "instanceof", "Mongo", ".", "Collection", ")", "{", "this", ".", "_collection", "=", "nameOrExisting", ";", "}", "else", "{", "this", ".", "_collection", "=", "new", "Mongo", ".", "Collection", "(", "nameOrExisting", ",", "options", ")", ";", "}", "}" ]
Creates a new Mongo.Collection instance wrapped with Observable features. @param {String | Mongo.Collection} nameOrExisting - The name of the collection. If null, creates an unmanaged (unsynchronized) local collection. If provided an instance of existing collection, will create a wrapper for the existing Mongo.Collection. @param {ConstructorOptions} options - Creation options. @constructor
[ "Creates", "a", "new", "Mongo", ".", "Collection", "instance", "wrapped", "with", "Observable", "features", "." ]
3c9c453291b83c564a416096b2023d7f45257dec
https://github.com/Urigo/meteor-rxjs/blob/3c9c453291b83c564a416096b2023d7f45257dec/dist/bundles/index.umd.js#L261-L268
train
smooch/smooch-core-js
src/api/integrations.js
IntegrationType
function IntegrationType(required, optional = []) { //convert parameter string values to object this.required = required.map(transformProps); this.optional = optional.map(transformProps); }
javascript
function IntegrationType(required, optional = []) { //convert parameter string values to object this.required = required.map(transformProps); this.optional = optional.map(transformProps); }
[ "function", "IntegrationType", "(", "required", ",", "optional", "=", "[", "]", ")", "{", "this", ".", "required", "=", "required", ".", "map", "(", "transformProps", ")", ";", "this", ".", "optional", "=", "optional", ".", "map", "(", "transformProps", ")", ";", "}" ]
Integration API properties @typedef IntegrationProps
[ "Integration", "API", "properties" ]
81e35d4154d12ff5c94ad40179fb503b2bc2d0ce
https://github.com/smooch/smooch-core-js/blob/81e35d4154d12ff5c94ad40179fb503b2bc2d0ce/src/api/integrations.js#L20-L24
train
rolaveric/karma-systemjs
lib/adapter.js
function(filePaths, importRegexp, System) { var moduleNames = []; for (var filePath in filePaths) { if (filePaths.hasOwnProperty(filePath) && importRegexp.test(filePath)) { moduleNames.push(adapter.getModuleNameFromPath(filePath, System.baseURL, System)); } } return moduleNames; }
javascript
function(filePaths, importRegexp, System) { var moduleNames = []; for (var filePath in filePaths) { if (filePaths.hasOwnProperty(filePath) && importRegexp.test(filePath)) { moduleNames.push(adapter.getModuleNameFromPath(filePath, System.baseURL, System)); } } return moduleNames; }
[ "function", "(", "filePaths", ",", "importRegexp", ",", "System", ")", "{", "var", "moduleNames", "=", "[", "]", ";", "for", "(", "var", "filePath", "in", "filePaths", ")", "{", "if", "(", "filePaths", ".", "hasOwnProperty", "(", "filePath", ")", "&&", "importRegexp", ".", "test", "(", "filePath", ")", ")", "{", "moduleNames", ".", "push", "(", "adapter", ".", "getModuleNameFromPath", "(", "filePath", ",", "System", ".", "baseURL", ",", "System", ")", ")", ";", "}", "}", "return", "moduleNames", ";", "}" ]
Returns the modules names for files that match a given import RegExp. @param filePaths {object} @param importRegexp {object} @param System {object} @returns {string[]}
[ "Returns", "the", "modules", "names", "for", "files", "that", "match", "a", "given", "import", "RegExp", "." ]
579a83a7c80a16484353df53e4ba6cf73db43e96
https://github.com/rolaveric/karma-systemjs/blob/579a83a7c80a16484353df53e4ba6cf73db43e96/lib/adapter.js#L28-L36
train
rolaveric/karma-systemjs
lib/adapter.js
function(System, Promise, files, importRegexps, strictImportSequence) { if (strictImportSequence) { return adapter.sequentialImportFiles(System, Promise, files, importRegexps) } else { return adapter.parallelImportFiles(System, Promise, files, importRegexps) } }
javascript
function(System, Promise, files, importRegexps, strictImportSequence) { if (strictImportSequence) { return adapter.sequentialImportFiles(System, Promise, files, importRegexps) } else { return adapter.parallelImportFiles(System, Promise, files, importRegexps) } }
[ "function", "(", "System", ",", "Promise", ",", "files", ",", "importRegexps", ",", "strictImportSequence", ")", "{", "if", "(", "strictImportSequence", ")", "{", "return", "adapter", ".", "sequentialImportFiles", "(", "System", ",", "Promise", ",", "files", ",", "importRegexps", ")", "}", "else", "{", "return", "adapter", ".", "parallelImportFiles", "(", "System", ",", "Promise", ",", "files", ",", "importRegexps", ")", "}", "}" ]
Calls System.import on all the files that match one of the importPatterns. Returns a single promise which resolves once all imports are complete. @param System {object} @param Promise {object} @param files {object} key/value map of filePaths to change counters @param importRegexps {RegExp[]} @param [strictImportSequence=false] {boolean} If true, System.import calls are chained to preserve sequence. @returns {promise}
[ "Calls", "System", ".", "import", "on", "all", "the", "files", "that", "match", "one", "of", "the", "importPatterns", ".", "Returns", "a", "single", "promise", "which", "resolves", "once", "all", "imports", "are", "complete", "." ]
579a83a7c80a16484353df53e4ba6cf73db43e96
https://github.com/rolaveric/karma-systemjs/blob/579a83a7c80a16484353df53e4ba6cf73db43e96/lib/adapter.js#L103-L109
train
rolaveric/karma-systemjs
lib/adapter.js
function(karma, System, Promise) { // Fail fast if any of the dependencies are undefined if (!karma) { (console.error || console.log)('Error: Not setup properly. window.__karma__ is undefined'); return; } if (!System) { (console.error || console.log)('Error: Not setup properly. window.System is undefined'); return; } if (!Promise) { (console.error || console.log)('Error: Not setup properly. window.Promise is undefined'); return; } // Stop karma from starting automatically on load karma.loaded = function() { // Load SystemJS configuration from karma config // And update baseURL with '/base', where Karma serves files from if (karma.config.systemjs.config) { // SystemJS config is converted to a JSON string by the framework // https://github.com/rolaveric/karma-systemjs/issues/44 karma.config.systemjs.config = JSON.parse(karma.config.systemjs.config); karma.config.systemjs.config.baseURL = adapter.updateBaseURL(karma.config.systemjs.config.baseURL); System.config(karma.config.systemjs.config); // Exclude bundle configurations if useBundles option is not specified if (!karma.config.systemjs.useBundles) { System.bundles = []; } } else { System.config({baseURL: '/base/'}); } // Convert the 'importPatterns' into 'importRegexps' var importPatterns = karma.config.systemjs.importPatterns; var importRegexps = []; for (var x = 0; x < importPatterns.length; x++) { importRegexps.push(new RegExp(importPatterns[x])); } // Import each test suite using SystemJS var testSuitePromise; try { testSuitePromise = adapter.importFiles(System, Promise, karma.files, importRegexps, karma.config.systemjs.strictImportSequence); } catch (e) { karma.error(adapter.decorateErrorWithHints(e, System)); return; } // Once all imports are complete... testSuitePromise.then(function () { karma.start(); }, function (e) { karma.error(adapter.decorateErrorWithHints(e, System)); }); }; }
javascript
function(karma, System, Promise) { // Fail fast if any of the dependencies are undefined if (!karma) { (console.error || console.log)('Error: Not setup properly. window.__karma__ is undefined'); return; } if (!System) { (console.error || console.log)('Error: Not setup properly. window.System is undefined'); return; } if (!Promise) { (console.error || console.log)('Error: Not setup properly. window.Promise is undefined'); return; } // Stop karma from starting automatically on load karma.loaded = function() { // Load SystemJS configuration from karma config // And update baseURL with '/base', where Karma serves files from if (karma.config.systemjs.config) { // SystemJS config is converted to a JSON string by the framework // https://github.com/rolaveric/karma-systemjs/issues/44 karma.config.systemjs.config = JSON.parse(karma.config.systemjs.config); karma.config.systemjs.config.baseURL = adapter.updateBaseURL(karma.config.systemjs.config.baseURL); System.config(karma.config.systemjs.config); // Exclude bundle configurations if useBundles option is not specified if (!karma.config.systemjs.useBundles) { System.bundles = []; } } else { System.config({baseURL: '/base/'}); } // Convert the 'importPatterns' into 'importRegexps' var importPatterns = karma.config.systemjs.importPatterns; var importRegexps = []; for (var x = 0; x < importPatterns.length; x++) { importRegexps.push(new RegExp(importPatterns[x])); } // Import each test suite using SystemJS var testSuitePromise; try { testSuitePromise = adapter.importFiles(System, Promise, karma.files, importRegexps, karma.config.systemjs.strictImportSequence); } catch (e) { karma.error(adapter.decorateErrorWithHints(e, System)); return; } // Once all imports are complete... testSuitePromise.then(function () { karma.start(); }, function (e) { karma.error(adapter.decorateErrorWithHints(e, System)); }); }; }
[ "function", "(", "karma", ",", "System", ",", "Promise", ")", "{", "if", "(", "!", "karma", ")", "{", "(", "console", ".", "error", "||", "console", ".", "log", ")", "(", "'Error: Not setup properly. window.__karma__ is undefined'", ")", ";", "return", ";", "}", "if", "(", "!", "System", ")", "{", "(", "console", ".", "error", "||", "console", ".", "log", ")", "(", "'Error: Not setup properly. window.System is undefined'", ")", ";", "return", ";", "}", "if", "(", "!", "Promise", ")", "{", "(", "console", ".", "error", "||", "console", ".", "log", ")", "(", "'Error: Not setup properly. window.Promise is undefined'", ")", ";", "return", ";", "}", "karma", ".", "loaded", "=", "function", "(", ")", "{", "if", "(", "karma", ".", "config", ".", "systemjs", ".", "config", ")", "{", "karma", ".", "config", ".", "systemjs", ".", "config", "=", "JSON", ".", "parse", "(", "karma", ".", "config", ".", "systemjs", ".", "config", ")", ";", "karma", ".", "config", ".", "systemjs", ".", "config", ".", "baseURL", "=", "adapter", ".", "updateBaseURL", "(", "karma", ".", "config", ".", "systemjs", ".", "config", ".", "baseURL", ")", ";", "System", ".", "config", "(", "karma", ".", "config", ".", "systemjs", ".", "config", ")", ";", "if", "(", "!", "karma", ".", "config", ".", "systemjs", ".", "useBundles", ")", "{", "System", ".", "bundles", "=", "[", "]", ";", "}", "}", "else", "{", "System", ".", "config", "(", "{", "baseURL", ":", "'/base/'", "}", ")", ";", "}", "var", "importPatterns", "=", "karma", ".", "config", ".", "systemjs", ".", "importPatterns", ";", "var", "importRegexps", "=", "[", "]", ";", "for", "(", "var", "x", "=", "0", ";", "x", "<", "importPatterns", ".", "length", ";", "x", "++", ")", "{", "importRegexps", ".", "push", "(", "new", "RegExp", "(", "importPatterns", "[", "x", "]", ")", ")", ";", "}", "var", "testSuitePromise", ";", "try", "{", "testSuitePromise", "=", "adapter", ".", "importFiles", "(", "System", ",", "Promise", ",", "karma", ".", "files", ",", "importRegexps", ",", "karma", ".", "config", ".", "systemjs", ".", "strictImportSequence", ")", ";", "}", "catch", "(", "e", ")", "{", "karma", ".", "error", "(", "adapter", ".", "decorateErrorWithHints", "(", "e", ",", "System", ")", ")", ";", "return", ";", "}", "testSuitePromise", ".", "then", "(", "function", "(", ")", "{", "karma", ".", "start", "(", ")", ";", "}", ",", "function", "(", "e", ")", "{", "karma", ".", "error", "(", "adapter", ".", "decorateErrorWithHints", "(", "e", ",", "System", ")", ")", ";", "}", ")", ";", "}", ";", "}" ]
Has SystemJS load each test suite, then starts Karma @param karma {object} @param System {object} @param Promise {object}
[ "Has", "SystemJS", "load", "each", "test", "suite", "then", "starts", "Karma" ]
579a83a7c80a16484353df53e4ba6cf73db43e96
https://github.com/rolaveric/karma-systemjs/blob/579a83a7c80a16484353df53e4ba6cf73db43e96/lib/adapter.js#L135-L195
train
rolaveric/karma-systemjs
lib/adapter.js
function(err, System) { err = String(err); // Look for common issues in the error message, and try to add hints to them switch (true) { // Some people use ".es6" instead of ".js" for ES6 code case /^Error loading ".*\.es6" at .*\.es6\.js/.test(err): return err + '\nHint: If you use ".es6" as an extension, ' + 'add this to your SystemJS paths config: {"*.es6": "*.es6"}'; case /^TypeError: Illegal module name "\/base\//.test(err): return err + '\nHint: Is the working directory different when you run karma?' + '\nYou may need to change the baseURL of your SystemJS config inside your karma config.' + '\nIt\'s currently checking "' + System.baseURL + '"' + '\nNote: "/base/" is where karma serves files from.'; } return err; }
javascript
function(err, System) { err = String(err); // Look for common issues in the error message, and try to add hints to them switch (true) { // Some people use ".es6" instead of ".js" for ES6 code case /^Error loading ".*\.es6" at .*\.es6\.js/.test(err): return err + '\nHint: If you use ".es6" as an extension, ' + 'add this to your SystemJS paths config: {"*.es6": "*.es6"}'; case /^TypeError: Illegal module name "\/base\//.test(err): return err + '\nHint: Is the working directory different when you run karma?' + '\nYou may need to change the baseURL of your SystemJS config inside your karma config.' + '\nIt\'s currently checking "' + System.baseURL + '"' + '\nNote: "/base/" is where karma serves files from.'; } return err; }
[ "function", "(", "err", ",", "System", ")", "{", "err", "=", "String", "(", "err", ")", ";", "switch", "(", "true", ")", "{", "case", "/", "^Error loading \".*\\.es6\" at .*\\.es6\\.js", "/", ".", "test", "(", "err", ")", ":", "return", "err", "+", "'\\nHint: If you use \".es6\" as an extension, '", "+", "\\n", ";", "'add this to your SystemJS paths config: {\"*.es6\": \"*.es6\"}'", "}", "case", "/", "^TypeError: Illegal module name \"\\/base\\/", "/", ".", "test", "(", "err", ")", ":", "return", "err", "+", "'\\nHint: Is the working directory different when you run karma?'", "+", "\\n", "+", "'\\nYou may need to change the baseURL of your SystemJS config inside your karma config.'", "+", "\\n", "+", "'\\nIt\\'s currently checking \"'", "+", "\\n", ";", "}" ]
Checks errors to see if they match known issues, and tries to decorate them with hints on how to resolve them. @param err {string} @param System {object} @returns {string}
[ "Checks", "errors", "to", "see", "if", "they", "match", "known", "issues", "and", "tries", "to", "decorate", "them", "with", "hints", "on", "how", "to", "resolve", "them", "." ]
579a83a7c80a16484353df53e4ba6cf73db43e96
https://github.com/rolaveric/karma-systemjs/blob/579a83a7c80a16484353df53e4ba6cf73db43e96/lib/adapter.js#L204-L220
train
segmentio/analytics.js-integration
lib/index.js
Integration
function Integration(options) { if (options && options.addIntegration) { // plugin return options.addIntegration(Integration); } this.debug = debug('analytics:integration:' + slug(name)); var clonedOpts = {}; extend(true, clonedOpts, options); // deep clone options this.options = defaults(clonedOpts || {}, this.defaults); this._queue = []; this.once('ready', bind(this, this.flush)); Integration.emit('construct', this); this.ready = bind(this, this.ready); this._wrapInitialize(); this._wrapPage(); this._wrapTrack(); }
javascript
function Integration(options) { if (options && options.addIntegration) { // plugin return options.addIntegration(Integration); } this.debug = debug('analytics:integration:' + slug(name)); var clonedOpts = {}; extend(true, clonedOpts, options); // deep clone options this.options = defaults(clonedOpts || {}, this.defaults); this._queue = []; this.once('ready', bind(this, this.flush)); Integration.emit('construct', this); this.ready = bind(this, this.ready); this._wrapInitialize(); this._wrapPage(); this._wrapTrack(); }
[ "function", "Integration", "(", "options", ")", "{", "if", "(", "options", "&&", "options", ".", "addIntegration", ")", "{", "return", "options", ".", "addIntegration", "(", "Integration", ")", ";", "}", "this", ".", "debug", "=", "debug", "(", "'analytics:integration:'", "+", "slug", "(", "name", ")", ")", ";", "var", "clonedOpts", "=", "{", "}", ";", "extend", "(", "true", ",", "clonedOpts", ",", "options", ")", ";", "this", ".", "options", "=", "defaults", "(", "clonedOpts", "||", "{", "}", ",", "this", ".", "defaults", ")", ";", "this", ".", "_queue", "=", "[", "]", ";", "this", ".", "once", "(", "'ready'", ",", "bind", "(", "this", ",", "this", ".", "flush", ")", ")", ";", "Integration", ".", "emit", "(", "'construct'", ",", "this", ")", ";", "this", ".", "ready", "=", "bind", "(", "this", ",", "this", ".", "ready", ")", ";", "this", ".", "_wrapInitialize", "(", ")", ";", "this", ".", "_wrapPage", "(", ")", ";", "this", ".", "_wrapTrack", "(", ")", ";", "}" ]
Initialize a new `Integration`. @class @param {Object} options
[ "Initialize", "a", "new", "Integration", "." ]
9392b72c34ee2446e97e37b737966fde3fee58cb
https://github.com/segmentio/analytics.js-integration/blob/9392b72c34ee2446e97e37b737966fde3fee58cb/lib/index.js#L31-L48
train
segmentio/analytics.js-integration
lib/protos.js
isMixed
function isMixed(item) { if (!is.object(item)) return false; if (!is.string(item.key)) return false; if (!has.call(item, 'value')) return false; return true; }
javascript
function isMixed(item) { if (!is.object(item)) return false; if (!is.string(item.key)) return false; if (!has.call(item, 'value')) return false; return true; }
[ "function", "isMixed", "(", "item", ")", "{", "if", "(", "!", "is", ".", "object", "(", "item", ")", ")", "return", "false", ";", "if", "(", "!", "is", ".", "string", "(", "item", ".", "key", ")", ")", "return", "false", ";", "if", "(", "!", "has", ".", "call", "(", "item", ",", "'value'", ")", ")", "return", "false", ";", "return", "true", ";", "}" ]
Determine if item in mapping array is a valid "mixed" type value Must be an object with properties "key" (of type string) and "value" (of any type) @api private @param {*} item @return {Boolean}
[ "Determine", "if", "item", "in", "mapping", "array", "is", "a", "valid", "mixed", "type", "value" ]
9392b72c34ee2446e97e37b737966fde3fee58cb
https://github.com/segmentio/analytics.js-integration/blob/9392b72c34ee2446e97e37b737966fde3fee58cb/lib/protos.js#L398-L403
train
davidtheclark/scut
docs/dev/js/main.js
toggleCss
function toggleCss() { if (!cssOpen) { exampleCss.classList.remove(hiddenClass); showCssBtn.innerHTML = hideText; cssOpen = true; } else { exampleCss.classList.add(hiddenClass); exampleScss.scrollIntoView(); showCssBtn.innerHTML = showText; cssOpen = false; } }
javascript
function toggleCss() { if (!cssOpen) { exampleCss.classList.remove(hiddenClass); showCssBtn.innerHTML = hideText; cssOpen = true; } else { exampleCss.classList.add(hiddenClass); exampleScss.scrollIntoView(); showCssBtn.innerHTML = showText; cssOpen = false; } }
[ "function", "toggleCss", "(", ")", "{", "if", "(", "!", "cssOpen", ")", "{", "exampleCss", ".", "classList", ".", "remove", "(", "hiddenClass", ")", ";", "showCssBtn", ".", "innerHTML", "=", "hideText", ";", "cssOpen", "=", "true", ";", "}", "else", "{", "exampleCss", ".", "classList", ".", "add", "(", "hiddenClass", ")", ";", "exampleScss", ".", "scrollIntoView", "(", ")", ";", "showCssBtn", ".", "innerHTML", "=", "showText", ";", "cssOpen", "=", "false", ";", "}", "}" ]
make button work
[ "make", "button", "work" ]
3d6f8fb7a26af441c87bd6d4199a56b4cf4982d8
https://github.com/davidtheclark/scut/blob/3d6f8fb7a26af441c87bd6d4199a56b4cf4982d8/docs/dev/js/main.js#L22-L33
train
signalfx/signalfx-nodejs
lib/client/signalflow/websocket_message_parser.js
getSnowflakeIdFromUint8Array
function getSnowflakeIdFromUint8Array(Uint8Arr) { // packaged lib uses base64 not base64URL, so swap the different chars return base64js.fromByteArray(Uint8Arr).substring(0, 11).replace(/\+/g, '-').replace(/\//g, '_'); }
javascript
function getSnowflakeIdFromUint8Array(Uint8Arr) { // packaged lib uses base64 not base64URL, so swap the different chars return base64js.fromByteArray(Uint8Arr).substring(0, 11).replace(/\+/g, '-').replace(/\//g, '_'); }
[ "function", "getSnowflakeIdFromUint8Array", "(", "Uint8Arr", ")", "{", "return", "base64js", ".", "fromByteArray", "(", "Uint8Arr", ")", ".", "substring", "(", "0", ",", "11", ")", ".", "replace", "(", "/", "\\+", "/", "g", ",", "'-'", ")", ".", "replace", "(", "/", "\\/", "/", "g", ",", "'_'", ")", ";", "}" ]
Convert the given Uint8 array into a SignalFx Snowflake ID.
[ "Convert", "the", "given", "Uint8", "array", "into", "a", "SignalFx", "Snowflake", "ID", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/client/signalflow/websocket_message_parser.js#L200-L203
train
signalfx/signalfx-nodejs
lib/client/signalflow/websocket_message_parser.js
extractBinaryFields
function extractBinaryFields(target, spec, data) { var offset = 0; for (var x = 0; x < spec.length; x++) { var item = spec[x]; if (item.label) { if (item.type === 'string') { var bytes = new DataView(data.buffer, offset, item.size); var str = textDecoder.decode(bytes); target[item.label] = str.replace(/\0/g, ''); } else { target[item.label] = data['get' + item.type + (item.size * 8)](offset); } } offset += item.size; } return offset; }
javascript
function extractBinaryFields(target, spec, data) { var offset = 0; for (var x = 0; x < spec.length; x++) { var item = spec[x]; if (item.label) { if (item.type === 'string') { var bytes = new DataView(data.buffer, offset, item.size); var str = textDecoder.decode(bytes); target[item.label] = str.replace(/\0/g, ''); } else { target[item.label] = data['get' + item.type + (item.size * 8)](offset); } } offset += item.size; } return offset; }
[ "function", "extractBinaryFields", "(", "target", ",", "spec", ",", "data", ")", "{", "var", "offset", "=", "0", ";", "for", "(", "var", "x", "=", "0", ";", "x", "<", "spec", ".", "length", ";", "x", "++", ")", "{", "var", "item", "=", "spec", "[", "x", "]", ";", "if", "(", "item", ".", "label", ")", "{", "if", "(", "item", ".", "type", "===", "'string'", ")", "{", "var", "bytes", "=", "new", "DataView", "(", "data", ".", "buffer", ",", "offset", ",", "item", ".", "size", ")", ";", "var", "str", "=", "textDecoder", ".", "decode", "(", "bytes", ")", ";", "target", "[", "item", ".", "label", "]", "=", "str", ".", "replace", "(", "/", "\\0", "/", "g", ",", "''", ")", ";", "}", "else", "{", "target", "[", "item", ".", "label", "]", "=", "data", "[", "'get'", "+", "item", ".", "type", "+", "(", "item", ".", "size", "*", "8", ")", "]", "(", "offset", ")", ";", "}", "}", "offset", "+=", "item", ".", "size", ";", "}", "return", "offset", ";", "}" ]
Extract fields from the given DataView following a specific a binary format specification into the given target object.
[ "Extract", "fields", "from", "the", "given", "DataView", "following", "a", "specific", "a", "binary", "format", "specification", "into", "the", "given", "target", "object", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/client/signalflow/websocket_message_parser.js#L209-L227
train
signalfx/signalfx-nodejs
lib/client/signalflow/websocket_message_parser.js
parseBinaryMessage
function parseBinaryMessage(data, knownComputations) { var msg = {}; var header = new DataView(data, 0, binaryHeaderLength); var version = header.getUint8(0); extractBinaryFields(msg, binaryHeaderFormats[version], header); var type = binaryMessageTypes[msg.type]; if (type === undefined) { console.warn('Unknown binary message type ' + msg.type); return null; } msg.type = type; var bigNumberRequested = false; if (typeof knownComputations[msg.channel] !== 'undefined' && knownComputations[msg.channel].params) { bigNumberRequested = knownComputations[msg.channel].params.bigNumber; } var compressed = msg.flags & (1 << 0); var json = msg.flags & (1 << 1); if (compressed) { // Decompress the message body if necessary. data = new DataView(pako.ungzip(new Uint8Array(data, binaryHeaderLength)).buffer); } else { data = new DataView(data, binaryHeaderLength); } if (json) { var decoded = textDecoder.decode(data); var body = JSON.parse(decoded); Object.keys(body).forEach(function (k) { msg[k] = body[k]; }); return msg; } switch (msg['type']) { case 'data': return parseBinaryDataMessage(msg, data, bigNumberRequested); default: console.warn('Unsupported binary "' + msg['type'] + '" message'); return null; } }
javascript
function parseBinaryMessage(data, knownComputations) { var msg = {}; var header = new DataView(data, 0, binaryHeaderLength); var version = header.getUint8(0); extractBinaryFields(msg, binaryHeaderFormats[version], header); var type = binaryMessageTypes[msg.type]; if (type === undefined) { console.warn('Unknown binary message type ' + msg.type); return null; } msg.type = type; var bigNumberRequested = false; if (typeof knownComputations[msg.channel] !== 'undefined' && knownComputations[msg.channel].params) { bigNumberRequested = knownComputations[msg.channel].params.bigNumber; } var compressed = msg.flags & (1 << 0); var json = msg.flags & (1 << 1); if (compressed) { // Decompress the message body if necessary. data = new DataView(pako.ungzip(new Uint8Array(data, binaryHeaderLength)).buffer); } else { data = new DataView(data, binaryHeaderLength); } if (json) { var decoded = textDecoder.decode(data); var body = JSON.parse(decoded); Object.keys(body).forEach(function (k) { msg[k] = body[k]; }); return msg; } switch (msg['type']) { case 'data': return parseBinaryDataMessage(msg, data, bigNumberRequested); default: console.warn('Unsupported binary "' + msg['type'] + '" message'); return null; } }
[ "function", "parseBinaryMessage", "(", "data", ",", "knownComputations", ")", "{", "var", "msg", "=", "{", "}", ";", "var", "header", "=", "new", "DataView", "(", "data", ",", "0", ",", "binaryHeaderLength", ")", ";", "var", "version", "=", "header", ".", "getUint8", "(", "0", ")", ";", "extractBinaryFields", "(", "msg", ",", "binaryHeaderFormats", "[", "version", "]", ",", "header", ")", ";", "var", "type", "=", "binaryMessageTypes", "[", "msg", ".", "type", "]", ";", "if", "(", "type", "===", "undefined", ")", "{", "console", ".", "warn", "(", "'Unknown binary message type '", "+", "msg", ".", "type", ")", ";", "return", "null", ";", "}", "msg", ".", "type", "=", "type", ";", "var", "bigNumberRequested", "=", "false", ";", "if", "(", "typeof", "knownComputations", "[", "msg", ".", "channel", "]", "!==", "'undefined'", "&&", "knownComputations", "[", "msg", ".", "channel", "]", ".", "params", ")", "{", "bigNumberRequested", "=", "knownComputations", "[", "msg", ".", "channel", "]", ".", "params", ".", "bigNumber", ";", "}", "var", "compressed", "=", "msg", ".", "flags", "&", "(", "1", "<<", "0", ")", ";", "var", "json", "=", "msg", ".", "flags", "&", "(", "1", "<<", "1", ")", ";", "if", "(", "compressed", ")", "{", "data", "=", "new", "DataView", "(", "pako", ".", "ungzip", "(", "new", "Uint8Array", "(", "data", ",", "binaryHeaderLength", ")", ")", ".", "buffer", ")", ";", "}", "else", "{", "data", "=", "new", "DataView", "(", "data", ",", "binaryHeaderLength", ")", ";", "}", "if", "(", "json", ")", "{", "var", "decoded", "=", "textDecoder", ".", "decode", "(", "data", ")", ";", "var", "body", "=", "JSON", ".", "parse", "(", "decoded", ")", ";", "Object", ".", "keys", "(", "body", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "msg", "[", "k", "]", "=", "body", "[", "k", "]", ";", "}", ")", ";", "return", "msg", ";", "}", "switch", "(", "msg", "[", "'type'", "]", ")", "{", "case", "'data'", ":", "return", "parseBinaryDataMessage", "(", "msg", ",", "data", ",", "bigNumberRequested", ")", ";", "default", ":", "console", ".", "warn", "(", "'Unsupported binary \"'", "+", "msg", "[", "'type'", "]", "+", "'\" message'", ")", ";", "return", "null", ";", "}", "}" ]
Parse a binary WebSocket message. Binary messages have a 20-byte header (binaryHeaderLength), followed by a body. Depending on the flags set in the header, the body of the message may be compressed, so it needs to be decompressed before being parsed. Finally, depending on the message type and the 'json' flag, the body of the message may be a JSON string, or a binary format. As of now, only data batch messages encode their body in binary, as per the binaryDataMessageFormats defined above.
[ "Parse", "a", "binary", "WebSocket", "message", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/client/signalflow/websocket_message_parser.js#L241-L286
train
signalfx/signalfx-nodejs
lib/client/signalflow/websocket_message_parser.js
parseBinaryDataMessage
function parseBinaryDataMessage(msg, data, bigNumberRequested) { var offset = extractBinaryFields(msg, binaryDataMessageFormats[msg['version']], data); msg.logicalTimestampMs = (msg.timestampMs1 * hiMult) + msg.timestampMs2; delete msg.timestampMs1; delete msg.timestampMs2; if (typeof msg.maxDelayMs1 !== 'undefined' && typeof msg.maxDelayMs2 !== 'undefined') { msg.maxDelayMs = (msg.maxDelayMs1 * hiMult) + msg.maxDelayMs2; delete msg.maxDelayMs1; delete msg.maxDelayMs2; } var values = []; msg.data = values; for (var dataPointCount = 0; dataPointCount < msg.count; dataPointCount++) { var type = data.getUint8(offset); offset++; var tsidBytes = []; for (var tsidByteIndex = 0; tsidByteIndex < 8; tsidByteIndex++) { tsidBytes.push(data.getUint8(offset)); offset++; } var tsId = getSnowflakeIdFromUint8Array(tsidBytes); var val = null; if (type === 0) { // NULL_TYPE, nothing to do } else if (type === 1) { // LONG_TYPE // get MSB for twos complement to determine sign var isNegative = data.getUint32(offset) >>> 31 > 0; if (isNegative) { // twos complement manual handling, because we cannot do Int64. // must do >>> 0 to prevent bit flips from turning into signed integers. val = (new BigNumber(hiMult) .times(~data.getUint32(offset) >>> 0) .plus(~data.getUint32(offset + 4) >>> 0) .plus(1) .times(-1)); } else { val = (new BigNumber(data.getUint32(offset)) .times(hiMult) .plus(data.getUint32(offset + 4))); } if (!bigNumberRequested) { val = val.toNumber(); } } else if (type === 2) { // DOUBLE_TYPE val = data.getFloat64(offset); if (bigNumberRequested) { val = new BigNumber(val); } } else if (type === 3) { // INT_TYPE val = data.getUint32(offset + 4); if (bigNumberRequested) { val = new BigNumber(val); } } offset += 8; values.push({tsId: tsId, value: val}); } delete msg.count; return msg; }
javascript
function parseBinaryDataMessage(msg, data, bigNumberRequested) { var offset = extractBinaryFields(msg, binaryDataMessageFormats[msg['version']], data); msg.logicalTimestampMs = (msg.timestampMs1 * hiMult) + msg.timestampMs2; delete msg.timestampMs1; delete msg.timestampMs2; if (typeof msg.maxDelayMs1 !== 'undefined' && typeof msg.maxDelayMs2 !== 'undefined') { msg.maxDelayMs = (msg.maxDelayMs1 * hiMult) + msg.maxDelayMs2; delete msg.maxDelayMs1; delete msg.maxDelayMs2; } var values = []; msg.data = values; for (var dataPointCount = 0; dataPointCount < msg.count; dataPointCount++) { var type = data.getUint8(offset); offset++; var tsidBytes = []; for (var tsidByteIndex = 0; tsidByteIndex < 8; tsidByteIndex++) { tsidBytes.push(data.getUint8(offset)); offset++; } var tsId = getSnowflakeIdFromUint8Array(tsidBytes); var val = null; if (type === 0) { // NULL_TYPE, nothing to do } else if (type === 1) { // LONG_TYPE // get MSB for twos complement to determine sign var isNegative = data.getUint32(offset) >>> 31 > 0; if (isNegative) { // twos complement manual handling, because we cannot do Int64. // must do >>> 0 to prevent bit flips from turning into signed integers. val = (new BigNumber(hiMult) .times(~data.getUint32(offset) >>> 0) .plus(~data.getUint32(offset + 4) >>> 0) .plus(1) .times(-1)); } else { val = (new BigNumber(data.getUint32(offset)) .times(hiMult) .plus(data.getUint32(offset + 4))); } if (!bigNumberRequested) { val = val.toNumber(); } } else if (type === 2) { // DOUBLE_TYPE val = data.getFloat64(offset); if (bigNumberRequested) { val = new BigNumber(val); } } else if (type === 3) { // INT_TYPE val = data.getUint32(offset + 4); if (bigNumberRequested) { val = new BigNumber(val); } } offset += 8; values.push({tsId: tsId, value: val}); } delete msg.count; return msg; }
[ "function", "parseBinaryDataMessage", "(", "msg", ",", "data", ",", "bigNumberRequested", ")", "{", "var", "offset", "=", "extractBinaryFields", "(", "msg", ",", "binaryDataMessageFormats", "[", "msg", "[", "'version'", "]", "]", ",", "data", ")", ";", "msg", ".", "logicalTimestampMs", "=", "(", "msg", ".", "timestampMs1", "*", "hiMult", ")", "+", "msg", ".", "timestampMs2", ";", "delete", "msg", ".", "timestampMs1", ";", "delete", "msg", ".", "timestampMs2", ";", "if", "(", "typeof", "msg", ".", "maxDelayMs1", "!==", "'undefined'", "&&", "typeof", "msg", ".", "maxDelayMs2", "!==", "'undefined'", ")", "{", "msg", ".", "maxDelayMs", "=", "(", "msg", ".", "maxDelayMs1", "*", "hiMult", ")", "+", "msg", ".", "maxDelayMs2", ";", "delete", "msg", ".", "maxDelayMs1", ";", "delete", "msg", ".", "maxDelayMs2", ";", "}", "var", "values", "=", "[", "]", ";", "msg", ".", "data", "=", "values", ";", "for", "(", "var", "dataPointCount", "=", "0", ";", "dataPointCount", "<", "msg", ".", "count", ";", "dataPointCount", "++", ")", "{", "var", "type", "=", "data", ".", "getUint8", "(", "offset", ")", ";", "offset", "++", ";", "var", "tsidBytes", "=", "[", "]", ";", "for", "(", "var", "tsidByteIndex", "=", "0", ";", "tsidByteIndex", "<", "8", ";", "tsidByteIndex", "++", ")", "{", "tsidBytes", ".", "push", "(", "data", ".", "getUint8", "(", "offset", ")", ")", ";", "offset", "++", ";", "}", "var", "tsId", "=", "getSnowflakeIdFromUint8Array", "(", "tsidBytes", ")", ";", "var", "val", "=", "null", ";", "if", "(", "type", "===", "0", ")", "{", "}", "else", "if", "(", "type", "===", "1", ")", "{", "var", "isNegative", "=", "data", ".", "getUint32", "(", "offset", ")", ">>>", "31", ">", "0", ";", "if", "(", "isNegative", ")", "{", "val", "=", "(", "new", "BigNumber", "(", "hiMult", ")", ".", "times", "(", "~", "data", ".", "getUint32", "(", "offset", ")", ">>>", "0", ")", ".", "plus", "(", "~", "data", ".", "getUint32", "(", "offset", "+", "4", ")", ">>>", "0", ")", ".", "plus", "(", "1", ")", ".", "times", "(", "-", "1", ")", ")", ";", "}", "else", "{", "val", "=", "(", "new", "BigNumber", "(", "data", ".", "getUint32", "(", "offset", ")", ")", ".", "times", "(", "hiMult", ")", ".", "plus", "(", "data", ".", "getUint32", "(", "offset", "+", "4", ")", ")", ")", ";", "}", "if", "(", "!", "bigNumberRequested", ")", "{", "val", "=", "val", ".", "toNumber", "(", ")", ";", "}", "}", "else", "if", "(", "type", "===", "2", ")", "{", "val", "=", "data", ".", "getFloat64", "(", "offset", ")", ";", "if", "(", "bigNumberRequested", ")", "{", "val", "=", "new", "BigNumber", "(", "val", ")", ";", "}", "}", "else", "if", "(", "type", "===", "3", ")", "{", "val", "=", "data", ".", "getUint32", "(", "offset", "+", "4", ")", ";", "if", "(", "bigNumberRequested", ")", "{", "val", "=", "new", "BigNumber", "(", "val", ")", ";", "}", "}", "offset", "+=", "8", ";", "values", ".", "push", "(", "{", "tsId", ":", "tsId", ",", "value", ":", "val", "}", ")", ";", "}", "delete", "msg", ".", "count", ";", "return", "msg", ";", "}" ]
Parse a binary data message body. Parse the binary-encoded information and datapoints of a data batch message.
[ "Parse", "a", "binary", "data", "message", "body", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/client/signalflow/websocket_message_parser.js#L293-L365
train
signalfx/signalfx-nodejs
lib/client/signalflow/websocket_message_parser.js
function (msg, knownComputations) { if (msg.data && msg.data.byteLength) { // The presence of byteLength indicates data is an ArrayBuffer from a WebSocket data frame. return parseBinaryMessage(msg.data, knownComputations); } else if (msg.type) { // Otherwise it's JSON in a WebSocket text frame. return JSON.parse(msg.data); } else { console.warn('Unrecognized websocket message.'); return null; } }
javascript
function (msg, knownComputations) { if (msg.data && msg.data.byteLength) { // The presence of byteLength indicates data is an ArrayBuffer from a WebSocket data frame. return parseBinaryMessage(msg.data, knownComputations); } else if (msg.type) { // Otherwise it's JSON in a WebSocket text frame. return JSON.parse(msg.data); } else { console.warn('Unrecognized websocket message.'); return null; } }
[ "function", "(", "msg", ",", "knownComputations", ")", "{", "if", "(", "msg", ".", "data", "&&", "msg", ".", "data", ".", "byteLength", ")", "{", "return", "parseBinaryMessage", "(", "msg", ".", "data", ",", "knownComputations", ")", ";", "}", "else", "if", "(", "msg", ".", "type", ")", "{", "return", "JSON", ".", "parse", "(", "msg", ".", "data", ")", ";", "}", "else", "{", "console", ".", "warn", "(", "'Unrecognized websocket message.'", ")", ";", "return", "null", ";", "}", "}" ]
Parse the given received WebSocket message into its canonical Javascript representation.
[ "Parse", "the", "given", "received", "WebSocket", "message", "into", "its", "canonical", "Javascript", "representation", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/client/signalflow/websocket_message_parser.js#L374-L385
train
signalfx/signalfx-nodejs
lib/client/ingest/signal_fx_client.js
SignalFxClient
function SignalFxClient(apiToken, options) { var _this = this; this.apiToken = apiToken; var params = options || {}; this.ingestEndpoint = params.ingestEndpoint || conf.DEFAULT_INGEST_ENDPOINT; this.timeout = params.timeout || conf.DEFAULT_TIMEOUT; this.batchSize = Math.max(1, (params.batchSize ? params.batchSize : conf.DEFAULT_BATCH_SIZE)); this.userAgents = params.userAgents || null; this.globalDimensions = params.dimensions || {}; this.enableAmazonUniqueId = params.enableAmazonUniqueId || false; this.proxy = params.proxy || null; this.rawData = []; this.rawEvents = []; this.queue = []; this.loadAWSUniqueId = new Promise(function (resolve) { if (!_this.enableAmazonUniqueId) { resolve(); return; } else { if (_this.AWSUniqueId !== undefined && _this.AWSUniqueId !== '') { resolve(); return; } } _this._retrieveAWSUniqueId(function (isSuccess, AWSUniqueId) { if (isSuccess) { _this.AWSUniqueId = AWSUniqueId; _this.globalDimensions[_this.AWSUniqueId_DIMENTION_NAME] = AWSUniqueId; } else { _this.enableAmazonUniqueId = false; _this.AWSUniqueId = ''; delete _this.globalDimensions[_this.AWSUniqueId_DIMENTION_NAME]; } resolve(); }); }); }
javascript
function SignalFxClient(apiToken, options) { var _this = this; this.apiToken = apiToken; var params = options || {}; this.ingestEndpoint = params.ingestEndpoint || conf.DEFAULT_INGEST_ENDPOINT; this.timeout = params.timeout || conf.DEFAULT_TIMEOUT; this.batchSize = Math.max(1, (params.batchSize ? params.batchSize : conf.DEFAULT_BATCH_SIZE)); this.userAgents = params.userAgents || null; this.globalDimensions = params.dimensions || {}; this.enableAmazonUniqueId = params.enableAmazonUniqueId || false; this.proxy = params.proxy || null; this.rawData = []; this.rawEvents = []; this.queue = []; this.loadAWSUniqueId = new Promise(function (resolve) { if (!_this.enableAmazonUniqueId) { resolve(); return; } else { if (_this.AWSUniqueId !== undefined && _this.AWSUniqueId !== '') { resolve(); return; } } _this._retrieveAWSUniqueId(function (isSuccess, AWSUniqueId) { if (isSuccess) { _this.AWSUniqueId = AWSUniqueId; _this.globalDimensions[_this.AWSUniqueId_DIMENTION_NAME] = AWSUniqueId; } else { _this.enableAmazonUniqueId = false; _this.AWSUniqueId = ''; delete _this.globalDimensions[_this.AWSUniqueId_DIMENTION_NAME]; } resolve(); }); }); }
[ "function", "SignalFxClient", "(", "apiToken", ",", "options", ")", "{", "var", "_this", "=", "this", ";", "this", ".", "apiToken", "=", "apiToken", ";", "var", "params", "=", "options", "||", "{", "}", ";", "this", ".", "ingestEndpoint", "=", "params", ".", "ingestEndpoint", "||", "conf", ".", "DEFAULT_INGEST_ENDPOINT", ";", "this", ".", "timeout", "=", "params", ".", "timeout", "||", "conf", ".", "DEFAULT_TIMEOUT", ";", "this", ".", "batchSize", "=", "Math", ".", "max", "(", "1", ",", "(", "params", ".", "batchSize", "?", "params", ".", "batchSize", ":", "conf", ".", "DEFAULT_BATCH_SIZE", ")", ")", ";", "this", ".", "userAgents", "=", "params", ".", "userAgents", "||", "null", ";", "this", ".", "globalDimensions", "=", "params", ".", "dimensions", "||", "{", "}", ";", "this", ".", "enableAmazonUniqueId", "=", "params", ".", "enableAmazonUniqueId", "||", "false", ";", "this", ".", "proxy", "=", "params", ".", "proxy", "||", "null", ";", "this", ".", "rawData", "=", "[", "]", ";", "this", ".", "rawEvents", "=", "[", "]", ";", "this", ".", "queue", "=", "[", "]", ";", "this", ".", "loadAWSUniqueId", "=", "new", "Promise", "(", "function", "(", "resolve", ")", "{", "if", "(", "!", "_this", ".", "enableAmazonUniqueId", ")", "{", "resolve", "(", ")", ";", "return", ";", "}", "else", "{", "if", "(", "_this", ".", "AWSUniqueId", "!==", "undefined", "&&", "_this", ".", "AWSUniqueId", "!==", "''", ")", "{", "resolve", "(", ")", ";", "return", ";", "}", "}", "_this", ".", "_retrieveAWSUniqueId", "(", "function", "(", "isSuccess", ",", "AWSUniqueId", ")", "{", "if", "(", "isSuccess", ")", "{", "_this", ".", "AWSUniqueId", "=", "AWSUniqueId", ";", "_this", ".", "globalDimensions", "[", "_this", ".", "AWSUniqueId_DIMENTION_NAME", "]", "=", "AWSUniqueId", ";", "}", "else", "{", "_this", ".", "enableAmazonUniqueId", "=", "false", ";", "_this", ".", "AWSUniqueId", "=", "''", ";", "delete", "_this", ".", "globalDimensions", "[", "_this", ".", "AWSUniqueId_DIMENTION_NAME", "]", ";", "}", "resolve", "(", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
SignalFx API client. This class presents a programmatic interface to SignalFx's metadata and ingest APIs. At the time being, only ingest is supported; more will come later. @constructor @param apiToken @param options - { enableAmazonUniqueId: boolean, // "false by default" dimensions:"object", // dimensions for each datapoint and event ingestEndpoint:"string", timeout:"number", batchSize:"number", userAgents:"array", proxy:"string" //http://<USER>:<PASSWORD>@<HOST>:<PORT> }
[ "SignalFx", "API", "client", ".", "This", "class", "presents", "a", "programmatic", "interface", "to", "SignalFx", "s", "metadata", "and", "ingest", "APIs", ".", "At", "the", "time", "being", "only", "ingest", "is", "supported", ";", "more", "will", "come", "later", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/client/ingest/signal_fx_client.js#L32-L73
train
signalfx/signalfx-nodejs
lib/proto/signal_fx_protocol_buffers_pb2.js
Datum
function Datum(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Datum(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Datum", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Datum. @memberof com.signalfx.metrics.protobuf @interface IDatum @property {string|null} [strValue] Datum strValue @property {number|null} [doubleValue] Datum doubleValue @property {number|Long|null} [intValue] Datum intValue Constructs a new Datum. @memberof com.signalfx.metrics.protobuf @classdesc Represents a Datum. @implements IDatum @constructor @param {com.signalfx.metrics.protobuf.IDatum=} [properties] Properties to set
[ "Properties", "of", "a", "Datum", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/proto/signal_fx_protocol_buffers_pb2.js#L86-L91
train
signalfx/signalfx-nodejs
lib/proto/signal_fx_protocol_buffers_pb2.js
Dimension
function Dimension(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Dimension(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Dimension", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Dimension. @memberof com.signalfx.metrics.protobuf @interface IDimension @property {string|null} [key] Dimension key @property {string|null} [value] Dimension value Constructs a new Dimension. @memberof com.signalfx.metrics.protobuf @classdesc Represents a Dimension. @implements IDimension @constructor @param {com.signalfx.metrics.protobuf.IDimension=} [properties] Properties to set
[ "Properties", "of", "a", "Dimension", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/proto/signal_fx_protocol_buffers_pb2.js#L331-L336
train
signalfx/signalfx-nodejs
lib/proto/signal_fx_protocol_buffers_pb2.js
DataPoint
function DataPoint(properties) { this.dimensions = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function DataPoint(properties) { this.dimensions = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "DataPoint", "(", "properties", ")", "{", "this", ".", "dimensions", "=", "[", "]", ";", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a DataPoint. @memberof com.signalfx.metrics.protobuf @interface IDataPoint @property {string|null} [source] DataPoint source @property {string|null} [metric] DataPoint metric @property {number|Long|null} [timestamp] DataPoint timestamp @property {com.signalfx.metrics.protobuf.IDatum|null} [value] DataPoint value @property {com.signalfx.metrics.protobuf.MetricType|null} [metricType] DataPoint metricType @property {Array.<com.signalfx.metrics.protobuf.IDimension>|null} [dimensions] DataPoint dimensions Constructs a new DataPoint. @memberof com.signalfx.metrics.protobuf @classdesc Represents a DataPoint. @implements IDataPoint @constructor @param {com.signalfx.metrics.protobuf.IDataPoint=} [properties] Properties to set
[ "Properties", "of", "a", "DataPoint", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/proto/signal_fx_protocol_buffers_pb2.js#L545-L551
train
signalfx/signalfx-nodejs
lib/proto/signal_fx_protocol_buffers_pb2.js
DataPointUploadMessage
function DataPointUploadMessage(properties) { this.datapoints = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function DataPointUploadMessage(properties) { this.datapoints = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "DataPointUploadMessage", "(", "properties", ")", "{", "this", ".", "datapoints", "=", "[", "]", ";", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a DataPointUploadMessage. @memberof com.signalfx.metrics.protobuf @interface IDataPointUploadMessage @property {Array.<com.signalfx.metrics.protobuf.IDataPoint>|null} [datapoints] DataPointUploadMessage datapoints Constructs a new DataPointUploadMessage. @memberof com.signalfx.metrics.protobuf @classdesc Represents a DataPointUploadMessage. @implements IDataPointUploadMessage @constructor @param {com.signalfx.metrics.protobuf.IDataPointUploadMessage=} [properties] Properties to set
[ "Properties", "of", "a", "DataPointUploadMessage", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/proto/signal_fx_protocol_buffers_pb2.js#L902-L908
train
signalfx/signalfx-nodejs
lib/proto/signal_fx_protocol_buffers_pb2.js
PointValue
function PointValue(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function PointValue(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "PointValue", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a PointValue. @memberof com.signalfx.metrics.protobuf @interface IPointValue @property {number|Long|null} [timestamp] PointValue timestamp @property {com.signalfx.metrics.protobuf.IDatum|null} [value] PointValue value Constructs a new PointValue. @memberof com.signalfx.metrics.protobuf @classdesc Represents a PointValue. @implements IPointValue @constructor @param {com.signalfx.metrics.protobuf.IPointValue=} [properties] Properties to set
[ "Properties", "of", "a", "PointValue", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/proto/signal_fx_protocol_buffers_pb2.js#L1111-L1116
train
signalfx/signalfx-nodejs
lib/proto/signal_fx_protocol_buffers_pb2.js
Property
function Property(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Property(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Property", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a Property. @memberof com.signalfx.metrics.protobuf @interface IProperty @property {string|null} [key] Property key @property {com.signalfx.metrics.protobuf.IPropertyValue|null} [value] Property value Constructs a new Property. @memberof com.signalfx.metrics.protobuf @classdesc Represents a Property. @implements IProperty @constructor @param {com.signalfx.metrics.protobuf.IProperty=} [properties] Properties to set
[ "Properties", "of", "a", "Property", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/proto/signal_fx_protocol_buffers_pb2.js#L1364-L1369
train
signalfx/signalfx-nodejs
lib/proto/signal_fx_protocol_buffers_pb2.js
PropertyValue
function PropertyValue(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function PropertyValue(properties) { if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "PropertyValue", "(", "properties", ")", "{", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of a PropertyValue. @memberof com.signalfx.metrics.protobuf @interface IPropertyValue @property {string|null} [strValue] PropertyValue strValue @property {number|null} [doubleValue] PropertyValue doubleValue @property {number|Long|null} [intValue] PropertyValue intValue @property {boolean|null} [boolValue] PropertyValue boolValue Constructs a new PropertyValue. @memberof com.signalfx.metrics.protobuf @classdesc Represents a PropertyValue. @implements IPropertyValue @constructor @param {com.signalfx.metrics.protobuf.IPropertyValue=} [properties] Properties to set
[ "Properties", "of", "a", "PropertyValue", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/proto/signal_fx_protocol_buffers_pb2.js#L1581-L1586
train
signalfx/signalfx-nodejs
lib/proto/signal_fx_protocol_buffers_pb2.js
Event
function Event(properties) { this.dimensions = []; this.properties = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
javascript
function Event(properties) { this.dimensions = []; this.properties = []; if (properties) for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) if (properties[keys[i]] != null) this[keys[i]] = properties[keys[i]]; }
[ "function", "Event", "(", "properties", ")", "{", "this", ".", "dimensions", "=", "[", "]", ";", "this", ".", "properties", "=", "[", "]", ";", "if", "(", "properties", ")", "for", "(", "var", "keys", "=", "Object", ".", "keys", "(", "properties", ")", ",", "i", "=", "0", ";", "i", "<", "keys", ".", "length", ";", "++", "i", ")", "if", "(", "properties", "[", "keys", "[", "i", "]", "]", "!=", "null", ")", "this", "[", "keys", "[", "i", "]", "]", "=", "properties", "[", "keys", "[", "i", "]", "]", ";", "}" ]
Properties of an Event. @memberof com.signalfx.metrics.protobuf @interface IEvent @property {string} eventType Event eventType @property {Array.<com.signalfx.metrics.protobuf.IDimension>|null} [dimensions] Event dimensions @property {Array.<com.signalfx.metrics.protobuf.IProperty>|null} [properties] Event properties @property {com.signalfx.metrics.protobuf.EventCategory|null} [category] Event category @property {number|Long|null} [timestamp] Event timestamp Constructs a new Event. @memberof com.signalfx.metrics.protobuf @classdesc Represents an Event. @implements IEvent @constructor @param {com.signalfx.metrics.protobuf.IEvent=} [properties] Properties to set
[ "Properties", "of", "an", "Event", "." ]
88f14af02c9af8de54e3ff273b5c9d3ab32030de
https://github.com/signalfx/signalfx-nodejs/blob/88f14af02c9af8de54e3ff273b5c9d3ab32030de/lib/proto/signal_fx_protocol_buffers_pb2.js#L1850-L1857
train