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
fxa/uritemplate-js
bin/uritemplate.js
isUnreserved
function isUnreserved (chr) { return charHelper.isAlpha(chr) || charHelper.isDigit(chr) || chr === '-' || chr === '.' || chr === '_' || chr === '~'; }
javascript
function isUnreserved (chr) { return charHelper.isAlpha(chr) || charHelper.isDigit(chr) || chr === '-' || chr === '.' || chr === '_' || chr === '~'; }
[ "function", "isUnreserved", "(", "chr", ")", "{", "return", "charHelper", ".", "isAlpha", "(", "chr", ")", "||", "charHelper", ".", "isDigit", "(", "chr", ")", "||", "chr", "===", "'-'", "||", "chr", "===", "'.'", "||", "chr", "===", "'_'", "||", "chr", "===", "'~'", ";", "}" ]
Returns if chr is an unreserved character according 1.5 of rfc 6570 @param chr @return {Boolean}
[ "Returns", "if", "chr", "is", "an", "unreserved", "character", "according", "1", ".", "5", "of", "rfc", "6570" ]
d9c73932b42173c0f1bbafa88badc7a8e0cd6c06
https://github.com/fxa/uritemplate-js/blob/d9c73932b42173c0f1bbafa88badc7a8e0cd6c06/bin/uritemplate.js#L278-L280
train
fxa/uritemplate-js
bin/uritemplate.js
isReserved
function isReserved (chr) { return chr === ':' || chr === '/' || chr === '?' || chr === '#' || chr === '[' || chr === ']' || chr === '@' || chr === '!' || chr === '$' || chr === '&' || chr === '(' || chr === ')' || chr === '*' || chr === '+' || chr === ',' || chr === ';' || chr === '=' || chr === "'"; }
javascript
function isReserved (chr) { return chr === ':' || chr === '/' || chr === '?' || chr === '#' || chr === '[' || chr === ']' || chr === '@' || chr === '!' || chr === '$' || chr === '&' || chr === '(' || chr === ')' || chr === '*' || chr === '+' || chr === ',' || chr === ';' || chr === '=' || chr === "'"; }
[ "function", "isReserved", "(", "chr", ")", "{", "return", "chr", "===", "':'", "||", "chr", "===", "'/'", "||", "chr", "===", "'?'", "||", "chr", "===", "'#'", "||", "chr", "===", "'['", "||", "chr", "===", "']'", "||", "chr", "===", "'@'", "||", "chr", "===", "'!'", "||", "chr", "===", "'$'", "||", "chr", "===", "'&'", "||", "chr", "===", "'('", "||", "chr", "===", "')'", "||", "chr", "===", "'*'", "||", "chr", "===", "'+'", "||", "chr", "===", "','", "||", "chr", "===", "';'", "||", "chr", "===", "'='", "||", "chr", "===", "\"'\"", ";", "}" ]
Returns if chr is an reserved character according 1.5 of rfc 6570 or the percent character mentioned in 3.2.1. @param chr @return {Boolean}
[ "Returns", "if", "chr", "is", "an", "reserved", "character", "according", "1", ".", "5", "of", "rfc", "6570", "or", "the", "percent", "character", "mentioned", "in", "3", ".", "2", ".", "1", "." ]
d9c73932b42173c0f1bbafa88badc7a8e0cd6c06
https://github.com/fxa/uritemplate-js/blob/d9c73932b42173c0f1bbafa88badc7a8e0cd6c06/bin/uritemplate.js#L288-L291
train
gwtw/js-sorting
lib/gnome-sort.js
sort
function sort(array, compare, swap) { var pos = 1; while (pos < array.length) { if (compare(array, pos, pos - 1) >= 0) { pos++; } else { swap(array, pos, pos - 1); if (pos > 1) { pos--; } } } return array; }
javascript
function sort(array, compare, swap) { var pos = 1; while (pos < array.length) { if (compare(array, pos, pos - 1) >= 0) { pos++; } else { swap(array, pos, pos - 1); if (pos > 1) { pos--; } } } return array; }
[ "function", "sort", "(", "array", ",", "compare", ",", "swap", ")", "{", "var", "pos", "=", "1", ";", "while", "(", "pos", "<", "array", ".", "length", ")", "{", "if", "(", "compare", "(", "array", ",", "pos", ",", "pos", "-", "1", ")", ">=", "0", ")", "{", "pos", "++", ";", "}", "else", "{", "swap", "(", "array", ",", "pos", ",", "pos", "-", "1", ")", ";", "if", "(", "pos", ">", "1", ")", "{", "pos", "--", ";", "}", "}", "}", "return", "array", ";", "}" ]
Sorts an array using gnome sort. @param {Array} array The array to sort. @param {function} compare The compare function. @param {function} swap A function to call when the swap operation is performed. This can be used to listen in on internals of the algorithm. @returns The sorted array.
[ "Sorts", "an", "array", "using", "gnome", "sort", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/gnome-sort.js#L21-L36
train
rhapsodyjs/RhapsodyJS
lib/rhapsody/responseUtils.js
respond
function respond(res, code, data) { return res.status(code).send(data || http.STATUS_CODES[code]); }
javascript
function respond(res, code, data) { return res.status(code).send(data || http.STATUS_CODES[code]); }
[ "function", "respond", "(", "res", ",", "code", ",", "data", ")", "{", "return", "res", ".", "status", "(", "code", ")", ".", "send", "(", "data", "||", "http", ".", "STATUS_CODES", "[", "code", "]", ")", ";", "}" ]
Respond to a request sending the correct status code, message and data @param {ExpressResponse} res @param {Number} code @param {String} data
[ "Respond", "to", "a", "request", "sending", "the", "correct", "status", "code", "message", "and", "data" ]
49cd89d3f82841b2d8086811e63f59a34999b07f
https://github.com/rhapsodyjs/RhapsodyJS/blob/49cd89d3f82841b2d8086811e63f59a34999b07f/lib/rhapsody/responseUtils.js#L12-L14
train
gwtw/js-sorting
lib/insertion-sort.js
sort
function sort(array, compare) { for (var i = 1; i < array.length; i++) { var item = array[i]; var indexHole = i; while (indexHole > 0 && compare(array[indexHole - 1], item) > 0) { array[indexHole] = array[--indexHole]; } array[indexHole] = item; if (sortExternal.shiftObserver) { sortExternal.shiftObserver(i, indexHole); } } return array; }
javascript
function sort(array, compare) { for (var i = 1; i < array.length; i++) { var item = array[i]; var indexHole = i; while (indexHole > 0 && compare(array[indexHole - 1], item) > 0) { array[indexHole] = array[--indexHole]; } array[indexHole] = item; if (sortExternal.shiftObserver) { sortExternal.shiftObserver(i, indexHole); } } return array; }
[ "function", "sort", "(", "array", ",", "compare", ")", "{", "for", "(", "var", "i", "=", "1", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "var", "item", "=", "array", "[", "i", "]", ";", "var", "indexHole", "=", "i", ";", "while", "(", "indexHole", ">", "0", "&&", "compare", "(", "array", "[", "indexHole", "-", "1", "]", ",", "item", ")", ">", "0", ")", "{", "array", "[", "indexHole", "]", "=", "array", "[", "--", "indexHole", "]", ";", "}", "array", "[", "indexHole", "]", "=", "item", ";", "if", "(", "sortExternal", ".", "shiftObserver", ")", "{", "sortExternal", ".", "shiftObserver", "(", "i", ",", "indexHole", ")", ";", "}", "}", "return", "array", ";", "}" ]
Sorts an array using insertion sort. @param {Array} array The array to sort. @param {function} compare The compare function. @returns The sorted array.
[ "Sorts", "an", "array", "using", "insertion", "sort", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/insertion-sort.js#L18-L32
train
gwtw/js-sorting
lib/merge-sort-bottom-up.js
bottomUpMerge
function bottomUpMerge( array, leftPosition, chunkSize, workArray, compare) { var i; var rightPosition = leftPosition + chunkSize; var endPosition = Math.min(leftPosition + chunkSize * 2 - 1, array.length - 1); var leftIndex = leftPosition; var rightIndex = rightPosition; for (i = 0; i <= endPosition - leftPosition; i++) { if (leftIndex < rightPosition && (rightIndex > endPosition || compare(array[leftIndex], array[rightIndex]) <= 0)) { workArray[i] = array[leftIndex++]; } else { workArray[i] = array[rightIndex++]; } } for (i = leftPosition; i <= endPosition; i++) { array[i] = workArray[i - leftPosition]; } }
javascript
function bottomUpMerge( array, leftPosition, chunkSize, workArray, compare) { var i; var rightPosition = leftPosition + chunkSize; var endPosition = Math.min(leftPosition + chunkSize * 2 - 1, array.length - 1); var leftIndex = leftPosition; var rightIndex = rightPosition; for (i = 0; i <= endPosition - leftPosition; i++) { if (leftIndex < rightPosition && (rightIndex > endPosition || compare(array[leftIndex], array[rightIndex]) <= 0)) { workArray[i] = array[leftIndex++]; } else { workArray[i] = array[rightIndex++]; } } for (i = leftPosition; i <= endPosition; i++) { array[i] = workArray[i - leftPosition]; } }
[ "function", "bottomUpMerge", "(", "array", ",", "leftPosition", ",", "chunkSize", ",", "workArray", ",", "compare", ")", "{", "var", "i", ";", "var", "rightPosition", "=", "leftPosition", "+", "chunkSize", ";", "var", "endPosition", "=", "Math", ".", "min", "(", "leftPosition", "+", "chunkSize", "*", "2", "-", "1", ",", "array", ".", "length", "-", "1", ")", ";", "var", "leftIndex", "=", "leftPosition", ";", "var", "rightIndex", "=", "rightPosition", ";", "for", "(", "i", "=", "0", ";", "i", "<=", "endPosition", "-", "leftPosition", ";", "i", "++", ")", "{", "if", "(", "leftIndex", "<", "rightPosition", "&&", "(", "rightIndex", ">", "endPosition", "||", "compare", "(", "array", "[", "leftIndex", "]", ",", "array", "[", "rightIndex", "]", ")", "<=", "0", ")", ")", "{", "workArray", "[", "i", "]", "=", "array", "[", "leftIndex", "++", "]", ";", "}", "else", "{", "workArray", "[", "i", "]", "=", "array", "[", "rightIndex", "++", "]", ";", "}", "}", "for", "(", "i", "=", "leftPosition", ";", "i", "<=", "endPosition", ";", "i", "++", ")", "{", "array", "[", "i", "]", "=", "workArray", "[", "i", "-", "leftPosition", "]", ";", "}", "}" ]
Merge a portion of the array. @param {Array} array The array to merge. @param {number} leftPosition The starting index of the array to merge. @param {number} chunkSize The size of the portion of the array to merge. @param {Array} workArray A work array the size of the array argument, this parameter is for performance reasons so many arrays aren't created by the algorithm. @param {function} compare The compare function. @returns The sorted array.
[ "Merge", "a", "portion", "of", "the", "array", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/merge-sort-bottom-up.js#L20-L42
train
gwtw/js-sorting
lib/merge-sort-bottom-up.js
sort
function sort(array, compare) { var workArray = new Array(array.length); var chunkSize = 1; while (chunkSize < array.length) { var i = 0; while (i < array.length - chunkSize) { bottomUpMerge(array, i, chunkSize, workArray, compare); i += chunkSize * 2; } chunkSize *= 2; } return array; }
javascript
function sort(array, compare) { var workArray = new Array(array.length); var chunkSize = 1; while (chunkSize < array.length) { var i = 0; while (i < array.length - chunkSize) { bottomUpMerge(array, i, chunkSize, workArray, compare); i += chunkSize * 2; } chunkSize *= 2; } return array; }
[ "function", "sort", "(", "array", ",", "compare", ")", "{", "var", "workArray", "=", "new", "Array", "(", "array", ".", "length", ")", ";", "var", "chunkSize", "=", "1", ";", "while", "(", "chunkSize", "<", "array", ".", "length", ")", "{", "var", "i", "=", "0", ";", "while", "(", "i", "<", "array", ".", "length", "-", "chunkSize", ")", "{", "bottomUpMerge", "(", "array", ",", "i", ",", "chunkSize", ",", "workArray", ",", "compare", ")", ";", "i", "+=", "chunkSize", "*", "2", ";", "}", "chunkSize", "*=", "2", ";", "}", "return", "array", ";", "}" ]
Sorts an array using bottom up merge sort. @param {Array} array The array to sort. @param {function} compare The compare function. @returns The sorted array.
[ "Sorts", "an", "array", "using", "bottom", "up", "merge", "sort", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/merge-sort-bottom-up.js#L50-L62
train
rhapsodyjs/RhapsodyJS
lib/rhapsody/mvc/model.js
createRelationships
function createRelationships(rhapsodyApp) { var relationshipModel, relationshipName, relationship, relatedModel; this.relationships = this.relationships || {}; for(relationshipName in this.relationships) { relationship = this.relationships[relationshipName]; //If it's a valid relationship if(this.serverModel[relationship.type]) { relatedModel = rhapsodyApp.requireModel(relationship['with']); //If the user sets the relationship model, pass it //otherwise, just pass false and JugglingDB will generate it relationshipModel = rhapsodyApp.requireModel(relationship.through); //If the related model actually exists if(relatedModel) { //Creates the relationship with JugglingDB API if(relationship.type === 'hasAndBelongsToMany') { this.serverModel.hasAndBelongsToMany(relationshipName, { model: relatedModel, through: relationshipModel }); } else { this.serverModel[relationship.type](relatedModel, { as: relationshipName, foreignKey: relationship.foreignKey }); } } else { utils.Logger.error('Relationship error', '"' + relationship['with'] + '" related with "' + this.name + '" does not exist.'); } } else { utils.Logger.error('Relationship error', relationship.type + ' in "' + this.name + '" is not a valid relationship'); } } }
javascript
function createRelationships(rhapsodyApp) { var relationshipModel, relationshipName, relationship, relatedModel; this.relationships = this.relationships || {}; for(relationshipName in this.relationships) { relationship = this.relationships[relationshipName]; //If it's a valid relationship if(this.serverModel[relationship.type]) { relatedModel = rhapsodyApp.requireModel(relationship['with']); //If the user sets the relationship model, pass it //otherwise, just pass false and JugglingDB will generate it relationshipModel = rhapsodyApp.requireModel(relationship.through); //If the related model actually exists if(relatedModel) { //Creates the relationship with JugglingDB API if(relationship.type === 'hasAndBelongsToMany') { this.serverModel.hasAndBelongsToMany(relationshipName, { model: relatedModel, through: relationshipModel }); } else { this.serverModel[relationship.type](relatedModel, { as: relationshipName, foreignKey: relationship.foreignKey }); } } else { utils.Logger.error('Relationship error', '"' + relationship['with'] + '" related with "' + this.name + '" does not exist.'); } } else { utils.Logger.error('Relationship error', relationship.type + ' in "' + this.name + '" is not a valid relationship'); } } }
[ "function", "createRelationships", "(", "rhapsodyApp", ")", "{", "var", "relationshipModel", ",", "relationshipName", ",", "relationship", ",", "relatedModel", ";", "this", ".", "relationships", "=", "this", ".", "relationships", "||", "{", "}", ";", "for", "(", "relationshipName", "in", "this", ".", "relationships", ")", "{", "relationship", "=", "this", ".", "relationships", "[", "relationshipName", "]", ";", "if", "(", "this", ".", "serverModel", "[", "relationship", ".", "type", "]", ")", "{", "relatedModel", "=", "rhapsodyApp", ".", "requireModel", "(", "relationship", "[", "'with'", "]", ")", ";", "relationshipModel", "=", "rhapsodyApp", ".", "requireModel", "(", "relationship", ".", "through", ")", ";", "if", "(", "relatedModel", ")", "{", "if", "(", "relationship", ".", "type", "===", "'hasAndBelongsToMany'", ")", "{", "this", ".", "serverModel", ".", "hasAndBelongsToMany", "(", "relationshipName", ",", "{", "model", ":", "relatedModel", ",", "through", ":", "relationshipModel", "}", ")", ";", "}", "else", "{", "this", ".", "serverModel", "[", "relationship", ".", "type", "]", "(", "relatedModel", ",", "{", "as", ":", "relationshipName", ",", "foreignKey", ":", "relationship", ".", "foreignKey", "}", ")", ";", "}", "}", "else", "{", "utils", ".", "Logger", ".", "error", "(", "'Relationship error'", ",", "'\"'", "+", "relationship", "[", "'with'", "]", "+", "'\" related with \"'", "+", "this", ".", "name", "+", "'\" does not exist.'", ")", ";", "}", "}", "else", "{", "utils", ".", "Logger", ".", "error", "(", "'Relationship error'", ",", "relationship", ".", "type", "+", "' in \"'", "+", "this", ".", "name", "+", "'\" is not a valid relationship'", ")", ";", "}", "}", "}" ]
Generate all the relationships of the model @param {Rhapsody} rhapsodyApp
[ "Generate", "all", "the", "relationships", "of", "the", "model" ]
49cd89d3f82841b2d8086811e63f59a34999b07f
https://github.com/rhapsodyjs/RhapsodyJS/blob/49cd89d3f82841b2d8086811e63f59a34999b07f/lib/rhapsody/mvc/model.js#L48-L93
train
subschema/subschema
src/Dom.js
ownerDocument
function ownerDocument(componentOrElement) { var elem = ReactDOM.findDOMNode(componentOrElement); return elem && elem.ownerDocument || document; }
javascript
function ownerDocument(componentOrElement) { var elem = ReactDOM.findDOMNode(componentOrElement); return elem && elem.ownerDocument || document; }
[ "function", "ownerDocument", "(", "componentOrElement", ")", "{", "var", "elem", "=", "ReactDOM", ".", "findDOMNode", "(", "componentOrElement", ")", ";", "return", "elem", "&&", "elem", ".", "ownerDocument", "||", "document", ";", "}" ]
Get elements owner document @param {ReactComponent|HTMLElement} componentOrElement @returns {HTMLElement}
[ "Get", "elements", "owner", "document" ]
55c07ee019b1e1ca0ebfb9266ccddd258c3e45b3
https://github.com/subschema/subschema/blob/55c07ee019b1e1ca0ebfb9266ccddd258c3e45b3/src/Dom.js#L25-L28
train
subschema/subschema
src/Dom.js
isNodeInRoot
function isNodeInRoot(node, root) { node = ReactDOM.findDOMNode(node), root = ReactDOM.findDOMNode(root); return _isNodeInRoot(node, root); }
javascript
function isNodeInRoot(node, root) { node = ReactDOM.findDOMNode(node), root = ReactDOM.findDOMNode(root); return _isNodeInRoot(node, root); }
[ "function", "isNodeInRoot", "(", "node", ",", "root", ")", "{", "node", "=", "ReactDOM", ".", "findDOMNode", "(", "node", ")", ",", "root", "=", "ReactDOM", ".", "findDOMNode", "(", "root", ")", ";", "return", "_isNodeInRoot", "(", "node", ",", "root", ")", ";", "}" ]
Checks whether a node is within a root nodes tree @param {DOMElement} node @param {DOMElement} root @returns {boolean}
[ "Checks", "whether", "a", "node", "is", "within", "a", "root", "nodes", "tree" ]
55c07ee019b1e1ca0ebfb9266ccddd258c3e45b3
https://github.com/subschema/subschema/blob/55c07ee019b1e1ca0ebfb9266ccddd258c3e45b3/src/Dom.js#L37-L40
train
philipwalton/mozart
lib/class.js
Class
function Class(name, definition, parent) { // Argument shifting. if (typeof name == 'function') { parent = definition; definition = name; name = null; } this.definition = definition; this.parent = parent; // Create the constructor, add some methods to it, and store the association. this.Ctor = createConstructor(name); this.Ctor.subclass = subclass; this.Ctor.final = final; constructorToClassMap.set(this.Ctor, this); this._setupInheritance(); this._storeSecrets(); this._makeAccessors(); }
javascript
function Class(name, definition, parent) { // Argument shifting. if (typeof name == 'function') { parent = definition; definition = name; name = null; } this.definition = definition; this.parent = parent; // Create the constructor, add some methods to it, and store the association. this.Ctor = createConstructor(name); this.Ctor.subclass = subclass; this.Ctor.final = final; constructorToClassMap.set(this.Ctor, this); this._setupInheritance(); this._storeSecrets(); this._makeAccessors(); }
[ "function", "Class", "(", "name", ",", "definition", ",", "parent", ")", "{", "if", "(", "typeof", "name", "==", "'function'", ")", "{", "parent", "=", "definition", ";", "definition", "=", "name", ";", "name", "=", "null", ";", "}", "this", ".", "definition", "=", "definition", ";", "this", ".", "parent", "=", "parent", ";", "this", ".", "Ctor", "=", "createConstructor", "(", "name", ")", ";", "this", ".", "Ctor", ".", "subclass", "=", "subclass", ";", "this", ".", "Ctor", ".", "final", "=", "final", ";", "constructorToClassMap", ".", "set", "(", "this", ".", "Ctor", ",", "this", ")", ";", "this", ".", "_setupInheritance", "(", ")", ";", "this", ".", "_storeSecrets", "(", ")", ";", "this", ".", "_makeAccessors", "(", ")", ";", "}" ]
A Class. @constructor @param {string} name An optional function name given to the produced constructor. This can be useful for debugging purposes. @param {Function} definition An optional function used to define the new constructor. @param {Class} parent An optional parent Class instance to extend from. This parameter is only used internally.
[ "A", "Class", "." ]
8322dcfbb4da445f2c19ffcaba678ac07988b2b7
https://github.com/philipwalton/mozart/blob/8322dcfbb4da445f2c19ffcaba678ac07988b2b7/lib/class.js#L27-L47
train
philipwalton/mozart
lib/class.js
protectedFactory
function protectedFactory(instance) { var publicPrototype = Object.getPrototypeOf(instance); var protectedPrototype = protectToPrototypeMap.get(publicPrototype); if (!protectedPrototype) { throw new Error('The protected key function only accepts instances ' + 'of objects created using Mozart constructors.' ); } return Object.create(protectedPrototype); }
javascript
function protectedFactory(instance) { var publicPrototype = Object.getPrototypeOf(instance); var protectedPrototype = protectToPrototypeMap.get(publicPrototype); if (!protectedPrototype) { throw new Error('The protected key function only accepts instances ' + 'of objects created using Mozart constructors.' ); } return Object.create(protectedPrototype); }
[ "function", "protectedFactory", "(", "instance", ")", "{", "var", "publicPrototype", "=", "Object", ".", "getPrototypeOf", "(", "instance", ")", ";", "var", "protectedPrototype", "=", "protectToPrototypeMap", ".", "get", "(", "publicPrototype", ")", ";", "if", "(", "!", "protectedPrototype", ")", "{", "throw", "new", "Error", "(", "'The protected key function only accepts instances '", "+", "'of objects created using Mozart constructors.'", ")", ";", "}", "return", "Object", ".", "create", "(", "protectedPrototype", ")", ";", "}" ]
A creator function that can be passed to the Private Parts `createKey` method. If accepts an object and return a new object whose prototype is the protected counterpart to the prototype of the passed object. @param {Object} instance An instance of a constructor created with Class. @return {Object} The protected methods object.
[ "A", "creator", "function", "that", "can", "be", "passed", "to", "the", "Private", "Parts", "createKey", "method", ".", "If", "accepts", "an", "object", "and", "return", "a", "new", "object", "whose", "prototype", "is", "the", "protected", "counterpart", "to", "the", "prototype", "of", "the", "passed", "object", "." ]
8322dcfbb4da445f2c19ffcaba678ac07988b2b7
https://github.com/philipwalton/mozart/blob/8322dcfbb4da445f2c19ffcaba678ac07988b2b7/lib/class.js#L192-L201
train
gwtw/js-sorting
lib/cocktail-sort.js
sort
function sort(array, compare, swap) { var start = -1; var end = array.length - 2; var swapped; var i; do { swapped = false; for (i = ++start; i <= end; i++) { if (compare(array, i, i + 1) > 0) { swap(array, i, i + 1); swapped = true; } } if (!swapped) { break; } swapped = false; for (i = --end; i >= start; i--) { if (compare(array, i, i + 1) > 0) { swap(array, i, i + 1); swapped = true; } } } while (swapped); return array; }
javascript
function sort(array, compare, swap) { var start = -1; var end = array.length - 2; var swapped; var i; do { swapped = false; for (i = ++start; i <= end; i++) { if (compare(array, i, i + 1) > 0) { swap(array, i, i + 1); swapped = true; } } if (!swapped) { break; } swapped = false; for (i = --end; i >= start; i--) { if (compare(array, i, i + 1) > 0) { swap(array, i, i + 1); swapped = true; } } } while (swapped); return array; }
[ "function", "sort", "(", "array", ",", "compare", ",", "swap", ")", "{", "var", "start", "=", "-", "1", ";", "var", "end", "=", "array", ".", "length", "-", "2", ";", "var", "swapped", ";", "var", "i", ";", "do", "{", "swapped", "=", "false", ";", "for", "(", "i", "=", "++", "start", ";", "i", "<=", "end", ";", "i", "++", ")", "{", "if", "(", "compare", "(", "array", ",", "i", ",", "i", "+", "1", ")", ">", "0", ")", "{", "swap", "(", "array", ",", "i", ",", "i", "+", "1", ")", ";", "swapped", "=", "true", ";", "}", "}", "if", "(", "!", "swapped", ")", "{", "break", ";", "}", "swapped", "=", "false", ";", "for", "(", "i", "=", "--", "end", ";", "i", ">=", "start", ";", "i", "--", ")", "{", "if", "(", "compare", "(", "array", ",", "i", ",", "i", "+", "1", ")", ">", "0", ")", "{", "swap", "(", "array", ",", "i", ",", "i", "+", "1", ")", ";", "swapped", "=", "true", ";", "}", "}", "}", "while", "(", "swapped", ")", ";", "return", "array", ";", "}" ]
Sorts an array using cocktail sort. @param {Array} array The array to sort. @param {function} compare The compare function. @param {function} swap A function to call when the swap operation is performed. This can be used to listen in on internals of the algorithm. @returns The sorted array.
[ "Sorts", "an", "array", "using", "cocktail", "sort", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/cocktail-sort.js#L21-L50
train
mcollina/pbkdf2-password
pbkdf2-password.js
hasher
function hasher(opts, callback) { if (typeof opts.password !== 'string') { passNeeded(opts, callback); } else if (typeof opts.salt !== 'string') { saltNeeded(opts, callback); } else { opts.salt = new Buffer(opts.salt, 'base64'); genHash(opts, callback); } }
javascript
function hasher(opts, callback) { if (typeof opts.password !== 'string') { passNeeded(opts, callback); } else if (typeof opts.salt !== 'string') { saltNeeded(opts, callback); } else { opts.salt = new Buffer(opts.salt, 'base64'); genHash(opts, callback); } }
[ "function", "hasher", "(", "opts", ",", "callback", ")", "{", "if", "(", "typeof", "opts", ".", "password", "!==", "'string'", ")", "{", "passNeeded", "(", "opts", ",", "callback", ")", ";", "}", "else", "if", "(", "typeof", "opts", ".", "salt", "!==", "'string'", ")", "{", "saltNeeded", "(", "opts", ",", "callback", ")", ";", "}", "else", "{", "opts", ".", "salt", "=", "new", "Buffer", "(", "opts", ".", "salt", ",", "'base64'", ")", ";", "genHash", "(", "opts", ",", "callback", ")", ";", "}", "}" ]
Hash a password, using a hash and the pbkd2 crypto module. Options: - `password`, the password to hash. - `salt`, the salt to use, as a base64 string. If the `password` is left undefined, a new 10-bytes password will be generated, and converted to base64. If the `salt` is left undefined, a new salt is generated. The callback will be called with the following arguments: - the error, if something when wrong. - the password. - the salt, encoded in base64. - the hash, encoded in base64. @param {Object} opts The options (optional) @param {Function} callback
[ "Hash", "a", "password", "using", "a", "hash", "and", "the", "pbkd2", "crypto", "module", "." ]
170c735be649e353c19da0ffc585c22dd6b34c5a
https://github.com/mcollina/pbkdf2-password/blob/170c735be649e353c19da0ffc585c22dd6b34c5a/pbkdf2-password.js#L89-L98
train
mcollina/pbkdf2-password
pbkdf2-password.js
genPass
function genPass(opts, cb) { // generate a 10-bytes password crypto.randomBytes(10, function(err, buffer) { if (buffer) { opts.password = buffer.toString("base64"); } cb(err, opts); }); }
javascript
function genPass(opts, cb) { // generate a 10-bytes password crypto.randomBytes(10, function(err, buffer) { if (buffer) { opts.password = buffer.toString("base64"); } cb(err, opts); }); }
[ "function", "genPass", "(", "opts", ",", "cb", ")", "{", "crypto", ".", "randomBytes", "(", "10", ",", "function", "(", "err", ",", "buffer", ")", "{", "if", "(", "buffer", ")", "{", "opts", ".", "password", "=", "buffer", ".", "toString", "(", "\"base64\"", ")", ";", "}", "cb", "(", "err", ",", "opts", ")", ";", "}", ")", ";", "}" ]
Generates a new password @api private @param {Object} opts The options (where the new password will be stored) @param {Function} cb The callback
[ "Generates", "a", "new", "password" ]
170c735be649e353c19da0ffc585c22dd6b34c5a
https://github.com/mcollina/pbkdf2-password/blob/170c735be649e353c19da0ffc585c22dd6b34c5a/pbkdf2-password.js#L107-L115
train
mcollina/pbkdf2-password
pbkdf2-password.js
genSalt
function genSalt(opts, cb) { crypto.randomBytes(saltLength, function(err, buf) { opts.salt = buf; cb(err, opts); }); }
javascript
function genSalt(opts, cb) { crypto.randomBytes(saltLength, function(err, buf) { opts.salt = buf; cb(err, opts); }); }
[ "function", "genSalt", "(", "opts", ",", "cb", ")", "{", "crypto", ".", "randomBytes", "(", "saltLength", ",", "function", "(", "err", ",", "buf", ")", "{", "opts", ".", "salt", "=", "buf", ";", "cb", "(", "err", ",", "opts", ")", ";", "}", ")", ";", "}" ]
Generates a new salt @api private @param {Object} opts The options (where the new password will be stored) @param {Function} cb The callback
[ "Generates", "a", "new", "salt" ]
170c735be649e353c19da0ffc585c22dd6b34c5a
https://github.com/mcollina/pbkdf2-password/blob/170c735be649e353c19da0ffc585c22dd6b34c5a/pbkdf2-password.js#L124-L129
train
mcollina/pbkdf2-password
pbkdf2-password.js
genHashWithDigest
function genHashWithDigest(opts, cb) { crypto.pbkdf2(opts.password, opts.salt, iterations, keyLength, digest, function(err, hash) { if (typeof hash === 'string') { hash = new Buffer(hash, 'binary'); } cb(err, opts.password, opts.salt.toString("base64"), hash.toString("base64")); }); }
javascript
function genHashWithDigest(opts, cb) { crypto.pbkdf2(opts.password, opts.salt, iterations, keyLength, digest, function(err, hash) { if (typeof hash === 'string') { hash = new Buffer(hash, 'binary'); } cb(err, opts.password, opts.salt.toString("base64"), hash.toString("base64")); }); }
[ "function", "genHashWithDigest", "(", "opts", ",", "cb", ")", "{", "crypto", ".", "pbkdf2", "(", "opts", ".", "password", ",", "opts", ".", "salt", ",", "iterations", ",", "keyLength", ",", "digest", ",", "function", "(", "err", ",", "hash", ")", "{", "if", "(", "typeof", "hash", "===", "'string'", ")", "{", "hash", "=", "new", "Buffer", "(", "hash", ",", "'binary'", ")", ";", "}", "cb", "(", "err", ",", "opts", ".", "password", ",", "opts", ".", "salt", ".", "toString", "(", "\"base64\"", ")", ",", "hash", ".", "toString", "(", "\"base64\"", ")", ")", ";", "}", ")", ";", "}" ]
Generates a new hash using the password and the salt The callback will be called with the following arguments: - the error, if something when wrong. - the password. - the salt, encoded in base64. - the hash, encoded in base64. @api private @param {Object} opts The options used to generate the hash (password & salt) @param {Function} cb The callback
[ "Generates", "a", "new", "hash", "using", "the", "password", "and", "the", "salt" ]
170c735be649e353c19da0ffc585c22dd6b34c5a
https://github.com/mcollina/pbkdf2-password/blob/170c735be649e353c19da0ffc585c22dd6b34c5a/pbkdf2-password.js#L144-L152
train
gwtw/js-sorting
lib/bucket-sort.js
sort
function sort(array, bucketSize) { if (array.length === 0) { return array; } // Determine minimum and maximum values var i; var minValue = array[0]; var maxValue = array[0]; for (i = 1; i < array.length; i++) { if (array[i] < minValue) { minValue = array[i]; } else if (array[i] > maxValue) { maxValue = array[i]; } } // Initialise buckets var DEFAULT_BUCKET_SIZE = 5; bucketSize = bucketSize || DEFAULT_BUCKET_SIZE; var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1; var buckets = new Array(bucketCount); for (i = 0; i < buckets.length; i++) { buckets[i] = []; } // Distribute input array values into buckets for (i = 0; i < array.length; i++) { buckets[Math.floor((array[i] - minValue) / bucketSize)].push(array[i]); } // Sort buckets and place back into input array array.length = 0; for (i = 0; i < buckets.length; i++) { insertionSort(buckets[i]); for (var j = 0; j < buckets[i].length; j++) { array.push(buckets[i][j]); } } return array; }
javascript
function sort(array, bucketSize) { if (array.length === 0) { return array; } // Determine minimum and maximum values var i; var minValue = array[0]; var maxValue = array[0]; for (i = 1; i < array.length; i++) { if (array[i] < minValue) { minValue = array[i]; } else if (array[i] > maxValue) { maxValue = array[i]; } } // Initialise buckets var DEFAULT_BUCKET_SIZE = 5; bucketSize = bucketSize || DEFAULT_BUCKET_SIZE; var bucketCount = Math.floor((maxValue - minValue) / bucketSize) + 1; var buckets = new Array(bucketCount); for (i = 0; i < buckets.length; i++) { buckets[i] = []; } // Distribute input array values into buckets for (i = 0; i < array.length; i++) { buckets[Math.floor((array[i] - minValue) / bucketSize)].push(array[i]); } // Sort buckets and place back into input array array.length = 0; for (i = 0; i < buckets.length; i++) { insertionSort(buckets[i]); for (var j = 0; j < buckets[i].length; j++) { array.push(buckets[i][j]); } } return array; }
[ "function", "sort", "(", "array", ",", "bucketSize", ")", "{", "if", "(", "array", ".", "length", "===", "0", ")", "{", "return", "array", ";", "}", "var", "i", ";", "var", "minValue", "=", "array", "[", "0", "]", ";", "var", "maxValue", "=", "array", "[", "0", "]", ";", "for", "(", "i", "=", "1", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "if", "(", "array", "[", "i", "]", "<", "minValue", ")", "{", "minValue", "=", "array", "[", "i", "]", ";", "}", "else", "if", "(", "array", "[", "i", "]", ">", "maxValue", ")", "{", "maxValue", "=", "array", "[", "i", "]", ";", "}", "}", "var", "DEFAULT_BUCKET_SIZE", "=", "5", ";", "bucketSize", "=", "bucketSize", "||", "DEFAULT_BUCKET_SIZE", ";", "var", "bucketCount", "=", "Math", ".", "floor", "(", "(", "maxValue", "-", "minValue", ")", "/", "bucketSize", ")", "+", "1", ";", "var", "buckets", "=", "new", "Array", "(", "bucketCount", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "buckets", ".", "length", ";", "i", "++", ")", "{", "buckets", "[", "i", "]", "=", "[", "]", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "buckets", "[", "Math", ".", "floor", "(", "(", "array", "[", "i", "]", "-", "minValue", ")", "/", "bucketSize", ")", "]", ".", "push", "(", "array", "[", "i", "]", ")", ";", "}", "array", ".", "length", "=", "0", ";", "for", "(", "i", "=", "0", ";", "i", "<", "buckets", ".", "length", ";", "i", "++", ")", "{", "insertionSort", "(", "buckets", "[", "i", "]", ")", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "buckets", "[", "i", "]", ".", "length", ";", "j", "++", ")", "{", "array", ".", "push", "(", "buckets", "[", "i", "]", "[", "j", "]", ")", ";", "}", "}", "return", "array", ";", "}" ]
Sorts an array using bucket sort. @param {number[]} array The array to sort. @param {number} [bucketSize=5] The number of values a bucket can hold. @returns The sorted array.
[ "Sorts", "an", "array", "using", "bucket", "sort", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/bucket-sort.js#L15-L56
train
subschema/subschema
src/core.js
newSubschemaContext
function newSubschemaContext(defaultLoaders = [], defaultResolvers = {}, defaultPropTypes = PropTypes, defaultInjectorFactory = injectorFactory, Subschema = { Conditional, Field, FieldSet, RenderContent, RenderTemplate, Form, NewChildContext, Dom, PropTypes, ValueManager, css, eventable, loaderFactory, tutils, validators, warning, injectorFactory, cachedInjector, stringInjector }) { const {loader, injector, ...rest} = Subschema; const _injector = defaultInjectorFactory(); for (let key of Object.keys(defaultResolvers)) { if (key in defaultPropTypes) { _injector.resolver(defaultPropTypes[key], defaultResolvers[key]); } } const defaultLoader = loaderFactory(defaultLoaders); const defaultInjector = cachedInjector(stringInjector(_injector, defaultPropTypes)); //Form needs these to kick off the whole thing. Its defaults can be overriden with // properties. rest.Form.defaultProps.loader = defaultLoader; rest.Form.defaultProps.injector = defaultInjector; rest.loader = defaultLoader; rest.injector = defaultInjector; return rest; }
javascript
function newSubschemaContext(defaultLoaders = [], defaultResolvers = {}, defaultPropTypes = PropTypes, defaultInjectorFactory = injectorFactory, Subschema = { Conditional, Field, FieldSet, RenderContent, RenderTemplate, Form, NewChildContext, Dom, PropTypes, ValueManager, css, eventable, loaderFactory, tutils, validators, warning, injectorFactory, cachedInjector, stringInjector }) { const {loader, injector, ...rest} = Subschema; const _injector = defaultInjectorFactory(); for (let key of Object.keys(defaultResolvers)) { if (key in defaultPropTypes) { _injector.resolver(defaultPropTypes[key], defaultResolvers[key]); } } const defaultLoader = loaderFactory(defaultLoaders); const defaultInjector = cachedInjector(stringInjector(_injector, defaultPropTypes)); //Form needs these to kick off the whole thing. Its defaults can be overriden with // properties. rest.Form.defaultProps.loader = defaultLoader; rest.Form.defaultProps.injector = defaultInjector; rest.loader = defaultLoader; rest.injector = defaultInjector; return rest; }
[ "function", "newSubschemaContext", "(", "defaultLoaders", "=", "[", "]", ",", "defaultResolvers", "=", "{", "}", ",", "defaultPropTypes", "=", "PropTypes", ",", "defaultInjectorFactory", "=", "injectorFactory", ",", "Subschema", "=", "{", "Conditional", ",", "Field", ",", "FieldSet", ",", "RenderContent", ",", "RenderTemplate", ",", "Form", ",", "NewChildContext", ",", "Dom", ",", "PropTypes", ",", "ValueManager", ",", "css", ",", "eventable", ",", "loaderFactory", ",", "tutils", ",", "validators", ",", "warning", ",", "injectorFactory", ",", "cachedInjector", ",", "stringInjector", "}", ")", "{", "const", "{", "loader", ",", "injector", ",", "...", "rest", "}", "=", "Subschema", ";", "const", "_injector", "=", "defaultInjectorFactory", "(", ")", ";", "for", "(", "let", "key", "of", "Object", ".", "keys", "(", "defaultResolvers", ")", ")", "{", "if", "(", "key", "in", "defaultPropTypes", ")", "{", "_injector", ".", "resolver", "(", "defaultPropTypes", "[", "key", "]", ",", "defaultResolvers", "[", "key", "]", ")", ";", "}", "}", "const", "defaultLoader", "=", "loaderFactory", "(", "defaultLoaders", ")", ";", "const", "defaultInjector", "=", "cachedInjector", "(", "stringInjector", "(", "_injector", ",", "defaultPropTypes", ")", ")", ";", "rest", ".", "Form", ".", "defaultProps", ".", "loader", "=", "defaultLoader", ";", "rest", ".", "Form", ".", "defaultProps", ".", "injector", "=", "defaultInjector", ";", "rest", ".", "loader", "=", "defaultLoader", ";", "rest", ".", "injector", "=", "defaultInjector", ";", "return", "rest", ";", "}" ]
Used to initialize new subschema for testing. But also to override behaviours if necessary. @param defaultLoaders @param defaultResolvers @param defaultPropTypes @param defaultInjectorFactory @param Subschema
[ "Used", "to", "initialize", "new", "subschema", "for", "testing", ".", "But", "also", "to", "override", "behaviours", "if", "necessary", "." ]
55c07ee019b1e1ca0ebfb9266ccddd258c3e45b3
https://github.com/subschema/subschema/blob/55c07ee019b1e1ca0ebfb9266ccddd258c3e45b3/src/core.js#L76-L119
train
rhapsodyjs/RhapsodyJS
lib/rhapsody.js
Rhapsody
function Rhapsody(options) { //Expose object as global //Should fix it latter global.Rhapsody = this; this.options = options; this.root = options.root; //Libs used internally that the programmer can access this.libs = { express: require('express'), jsmin: require('jsmin').jsmin, lodash: require('lodash'), wolverine: require('wolverine') }; this.config = require(path.join(this.root, '/app/config/config')); //Get the general environment settings this.config = this.libs.lodash.merge(this.config, require(path.join(this.root, '/app/config/envs/all'))); //Overwrite it with the defined environment settings this.config = this.libs.lodash.merge(this.config, require(path.join(this.root, '/app/config/envs/' + this.config.environment))); //Then extends it with the other settings var loadConfig = require('./rhapsody/app/config'); this.config = this.libs.lodash.merge(this.config, loadConfig(options)); return this; }
javascript
function Rhapsody(options) { //Expose object as global //Should fix it latter global.Rhapsody = this; this.options = options; this.root = options.root; //Libs used internally that the programmer can access this.libs = { express: require('express'), jsmin: require('jsmin').jsmin, lodash: require('lodash'), wolverine: require('wolverine') }; this.config = require(path.join(this.root, '/app/config/config')); //Get the general environment settings this.config = this.libs.lodash.merge(this.config, require(path.join(this.root, '/app/config/envs/all'))); //Overwrite it with the defined environment settings this.config = this.libs.lodash.merge(this.config, require(path.join(this.root, '/app/config/envs/' + this.config.environment))); //Then extends it with the other settings var loadConfig = require('./rhapsody/app/config'); this.config = this.libs.lodash.merge(this.config, loadConfig(options)); return this; }
[ "function", "Rhapsody", "(", "options", ")", "{", "global", ".", "Rhapsody", "=", "this", ";", "this", ".", "options", "=", "options", ";", "this", ".", "root", "=", "options", ".", "root", ";", "this", ".", "libs", "=", "{", "express", ":", "require", "(", "'express'", ")", ",", "jsmin", ":", "require", "(", "'jsmin'", ")", ".", "jsmin", ",", "lodash", ":", "require", "(", "'lodash'", ")", ",", "wolverine", ":", "require", "(", "'wolverine'", ")", "}", ";", "this", ".", "config", "=", "require", "(", "path", ".", "join", "(", "this", ".", "root", ",", "'/app/config/config'", ")", ")", ";", "this", ".", "config", "=", "this", ".", "libs", ".", "lodash", ".", "merge", "(", "this", ".", "config", ",", "require", "(", "path", ".", "join", "(", "this", ".", "root", ",", "'/app/config/envs/all'", ")", ")", ")", ";", "this", ".", "config", "=", "this", ".", "libs", ".", "lodash", ".", "merge", "(", "this", ".", "config", ",", "require", "(", "path", ".", "join", "(", "this", ".", "root", ",", "'/app/config/envs/'", "+", "this", ".", "config", ".", "environment", ")", ")", ")", ";", "var", "loadConfig", "=", "require", "(", "'./rhapsody/app/config'", ")", ";", "this", ".", "config", "=", "this", ".", "libs", ".", "lodash", ".", "merge", "(", "this", ".", "config", ",", "loadConfig", "(", "options", ")", ")", ";", "return", "this", ";", "}" ]
RhapsodyJS app class @param {Object} options Options @constructor
[ "RhapsodyJS", "app", "class" ]
49cd89d3f82841b2d8086811e63f59a34999b07f
https://github.com/rhapsodyjs/RhapsodyJS/blob/49cd89d3f82841b2d8086811e63f59a34999b07f/lib/rhapsody.js#L16-L46
train
rhapsodyjs/RhapsodyJS
lib/rhapsody.js
requireModel
function requireModel(modelName, full) { if(!modelName) { return false; } var model = this.models[modelName]; if(full) { return (model ? model : false); } return (model ? model.serverModel : false); }
javascript
function requireModel(modelName, full) { if(!modelName) { return false; } var model = this.models[modelName]; if(full) { return (model ? model : false); } return (model ? model.serverModel : false); }
[ "function", "requireModel", "(", "modelName", ",", "full", ")", "{", "if", "(", "!", "modelName", ")", "{", "return", "false", ";", "}", "var", "model", "=", "this", ".", "models", "[", "modelName", "]", ";", "if", "(", "full", ")", "{", "return", "(", "model", "?", "model", ":", "false", ")", ";", "}", "return", "(", "model", "?", "model", ".", "serverModel", ":", "false", ")", ";", "}" ]
Returns the serverModel or the whole model @param {String} modelName The name of the model @param {Boolean} full Optional. Makes return the whole model @return {Model}
[ "Returns", "the", "serverModel", "or", "the", "whole", "model" ]
49cd89d3f82841b2d8086811e63f59a34999b07f
https://github.com/rhapsodyjs/RhapsodyJS/blob/49cd89d3f82841b2d8086811e63f59a34999b07f/lib/rhapsody.js#L64-L75
train
rhapsodyjs/RhapsodyJS
lib/rhapsody.js
onlineMessage
function onlineMessage() { _this.showLogo(); var httpPort = _this.config.http.port; Logger.info('Listening HTTP on port ' + httpPort); if(_this.config.https.enabled) { var httpsPort = _this.config.https.port; Logger.info('Listening HTTPS on port ' + httpsPort); } }
javascript
function onlineMessage() { _this.showLogo(); var httpPort = _this.config.http.port; Logger.info('Listening HTTP on port ' + httpPort); if(_this.config.https.enabled) { var httpsPort = _this.config.https.port; Logger.info('Listening HTTPS on port ' + httpsPort); } }
[ "function", "onlineMessage", "(", ")", "{", "_this", ".", "showLogo", "(", ")", ";", "var", "httpPort", "=", "_this", ".", "config", ".", "http", ".", "port", ";", "Logger", ".", "info", "(", "'Listening HTTP on port '", "+", "httpPort", ")", ";", "if", "(", "_this", ".", "config", ".", "https", ".", "enabled", ")", "{", "var", "httpsPort", "=", "_this", ".", "config", ".", "https", ".", "port", ";", "Logger", ".", "info", "(", "'Listening HTTPS on port '", "+", "httpsPort", ")", ";", "}", "}" ]
Show the message that it's all online
[ "Show", "the", "message", "that", "it", "s", "all", "online" ]
49cd89d3f82841b2d8086811e63f59a34999b07f
https://github.com/rhapsodyjs/RhapsodyJS/blob/49cd89d3f82841b2d8086811e63f59a34999b07f/lib/rhapsody.js#L398-L408
train
subschema/subschema
src/tutils.js
nextFunc
function nextFunc(f1, f2) { if (f1 && !f2) return f1; if (f2 && !f1) return f2; return function nextFunc$wrapper(...args) { if (f1.apply(this, args) !== false) { return f2.apply(this, args); } }; }
javascript
function nextFunc(f1, f2) { if (f1 && !f2) return f1; if (f2 && !f1) return f2; return function nextFunc$wrapper(...args) { if (f1.apply(this, args) !== false) { return f2.apply(this, args); } }; }
[ "function", "nextFunc", "(", "f1", ",", "f2", ")", "{", "if", "(", "f1", "&&", "!", "f2", ")", "return", "f1", ";", "if", "(", "f2", "&&", "!", "f1", ")", "return", "f2", ";", "return", "function", "nextFunc$wrapper", "(", "...", "args", ")", "{", "if", "(", "f1", ".", "apply", "(", "this", ",", "args", ")", "!==", "false", ")", "{", "return", "f2", ".", "apply", "(", "this", ",", "args", ")", ";", "}", "}", ";", "}" ]
When f1 and f2 are defined- Calls f1 and f2 if f1 and f2 are defined and f1 does not return false. If f1 returns false, f2 is not called. If f2 is not defined f1 is returned. if f1 is not defined f2 is returned. @param f1 @param f2 @returns {function}
[ "When", "f1", "and", "f2", "are", "defined", "-" ]
55c07ee019b1e1ca0ebfb9266ccddd258c3e45b3
https://github.com/subschema/subschema/blob/55c07ee019b1e1ca0ebfb9266ccddd258c3e45b3/src/tutils.js#L171-L179
train
subschema/subschema
src/types/RestrictedMixin.js
clean
function clean(parts) { var p = ''; for (var i = 0; i < parts.length; i += 3) { p += parts[i] || ''; } return p; }
javascript
function clean(parts) { var p = ''; for (var i = 0; i < parts.length; i += 3) { p += parts[i] || ''; } return p; }
[ "function", "clean", "(", "parts", ")", "{", "var", "p", "=", "''", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "parts", ".", "length", ";", "i", "+=", "3", ")", "{", "p", "+=", "parts", "[", "i", "]", "||", "''", ";", "}", "return", "p", ";", "}" ]
So we only care about every 3rd group. Remove delimeters and such, so the next parse can have something nice to work with.
[ "So", "we", "only", "care", "about", "every", "3rd", "group", ".", "Remove", "delimeters", "and", "such", "so", "the", "next", "parse", "can", "have", "something", "nice", "to", "work", "with", "." ]
55c07ee019b1e1ca0ebfb9266ccddd258c3e45b3
https://github.com/subschema/subschema/blob/55c07ee019b1e1ca0ebfb9266ccddd258c3e45b3/src/types/RestrictedMixin.js#L190-L196
train
WebReflection/broadcast
src/broadcast.js
function (x) { var i = indexOf.call(k, x); k.splice(i, 1); v.splice(i, 1); }
javascript
function (x) { var i = indexOf.call(k, x); k.splice(i, 1); v.splice(i, 1); }
[ "function", "(", "x", ")", "{", "var", "i", "=", "indexOf", ".", "call", "(", "k", ",", "x", ")", ";", "k", ".", "splice", "(", "i", ",", "1", ")", ";", "v", ".", "splice", "(", "i", ",", "1", ")", ";", "}" ]
delete used to be a reserved property name
[ "delete", "used", "to", "be", "a", "reserved", "property", "name" ]
f58a0812bbcdf9c224000b64cc79cc6ffe7f818d
https://github.com/WebReflection/broadcast/blob/f58a0812bbcdf9c224000b64cc79cc6ffe7f818d/src/broadcast.js#L74-L78
train
WebReflection/broadcast
src/broadcast.js
drop
function drop(type, callback) { if (arguments.length === 1) delete _[type]; else { var fn = wm.get(callback), cb, i; if (fn) { wm['delete'](callback); drop(type, fn); } else { cb = get(type).cb; i = indexOf.call(cb, callback); if (~i) cb.splice(i, 1); } } }
javascript
function drop(type, callback) { if (arguments.length === 1) delete _[type]; else { var fn = wm.get(callback), cb, i; if (fn) { wm['delete'](callback); drop(type, fn); } else { cb = get(type).cb; i = indexOf.call(cb, callback); if (~i) cb.splice(i, 1); } } }
[ "function", "drop", "(", "type", ",", "callback", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", ")", "delete", "_", "[", "type", "]", ";", "else", "{", "var", "fn", "=", "wm", ".", "get", "(", "callback", ")", ",", "cb", ",", "i", ";", "if", "(", "fn", ")", "{", "wm", "[", "'delete'", "]", "(", "callback", ")", ";", "drop", "(", "type", ",", "fn", ")", ";", "}", "else", "{", "cb", "=", "get", "(", "type", ")", ".", "cb", ";", "i", "=", "indexOf", ".", "call", "(", "cb", ",", "callback", ")", ";", "if", "(", "~", "i", ")", "cb", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "}", "}" ]
if we set a listener through `.when` and this hasn't been notified yet but we changed our mind about such notification we can still remove such listener via `.drop` otherwise, if we know the key, we can drop it.
[ "if", "we", "set", "a", "listener", "through", ".", "when", "and", "this", "hasn", "t", "been", "notified", "yet", "but", "we", "changed", "our", "mind", "about", "such", "notification", "we", "can", "still", "remove", "such", "listener", "via", ".", "drop", "otherwise", "if", "we", "know", "the", "key", "we", "can", "drop", "it", "." ]
f58a0812bbcdf9c224000b64cc79cc6ffe7f818d
https://github.com/WebReflection/broadcast/blob/f58a0812bbcdf9c224000b64cc79cc6ffe7f818d/src/broadcast.js#L201-L215
train
WebReflection/broadcast
src/broadcast.js
all
function all(type, callback) { if (!wm.get(callback)) { wm.set(callback, function fn() { invoke = false; when(type, fn); invoke = true; resolve(arguments).then(bind.call(broadcast, callback)); }); when(type, wm.get(callback)); } }
javascript
function all(type, callback) { if (!wm.get(callback)) { wm.set(callback, function fn() { invoke = false; when(type, fn); invoke = true; resolve(arguments).then(bind.call(broadcast, callback)); }); when(type, wm.get(callback)); } }
[ "function", "all", "(", "type", ",", "callback", ")", "{", "if", "(", "!", "wm", ".", "get", "(", "callback", ")", ")", "{", "wm", ".", "set", "(", "callback", ",", "function", "fn", "(", ")", "{", "invoke", "=", "false", ";", "when", "(", "type", ",", "fn", ")", ";", "invoke", "=", "true", ";", "resolve", "(", "arguments", ")", ".", "then", "(", "bind", ".", "call", "(", "broadcast", ",", "callback", ")", ")", ";", "}", ")", ";", "when", "(", "type", ",", "wm", ".", "get", "(", "callback", ")", ")", ";", "}", "}" ]
in case we'd like to react each time to a specific event. In this case a callback is mandatory, and it's also needed to eventually drop.
[ "in", "case", "we", "d", "like", "to", "react", "each", "time", "to", "a", "specific", "event", ".", "In", "this", "case", "a", "callback", "is", "mandatory", "and", "it", "s", "also", "needed", "to", "eventually", "drop", "." ]
f58a0812bbcdf9c224000b64cc79cc6ffe7f818d
https://github.com/WebReflection/broadcast/blob/f58a0812bbcdf9c224000b64cc79cc6ffe7f818d/src/broadcast.js#L226-L236
train
rhapsodyjs/RhapsodyJS
lib/rhapsody/router/modelRouter/index.js
getModel
function getModel(req, res, next, model) { var fullModel = Rhapsody.requireModel(model, true); if(!fullModel) { Rhapsody.log.verbose('Nonexistent model', 'Couldn\'t find collection %s.', model); return responseUtils.respond(res, 400); //Malformed syntax or a bad query } //This model does not allow REST API if(!fullModel.options.allowREST) { return responseUtils.respond(res, 404); } req.fullModel = fullModel; next(); }
javascript
function getModel(req, res, next, model) { var fullModel = Rhapsody.requireModel(model, true); if(!fullModel) { Rhapsody.log.verbose('Nonexistent model', 'Couldn\'t find collection %s.', model); return responseUtils.respond(res, 400); //Malformed syntax or a bad query } //This model does not allow REST API if(!fullModel.options.allowREST) { return responseUtils.respond(res, 404); } req.fullModel = fullModel; next(); }
[ "function", "getModel", "(", "req", ",", "res", ",", "next", ",", "model", ")", "{", "var", "fullModel", "=", "Rhapsody", ".", "requireModel", "(", "model", ",", "true", ")", ";", "if", "(", "!", "fullModel", ")", "{", "Rhapsody", ".", "log", ".", "verbose", "(", "'Nonexistent model'", ",", "'Couldn\\'t find collection %s.'", ",", "\\'", ")", ";", "model", "}", "return", "responseUtils", ".", "respond", "(", "res", ",", "400", ")", ";", "if", "(", "!", "fullModel", ".", "options", ".", "allowREST", ")", "{", "return", "responseUtils", ".", "respond", "(", "res", ",", "404", ")", ";", "}", "req", ".", "fullModel", "=", "fullModel", ";", "}" ]
Gets the model and save it in the req object @param {ExpressRequest} req @param {ExpressResponse} res @param {Function} next Pass to the next route
[ "Gets", "the", "model", "and", "save", "it", "in", "the", "req", "object" ]
49cd89d3f82841b2d8086811e63f59a34999b07f
https://github.com/rhapsodyjs/RhapsodyJS/blob/49cd89d3f82841b2d8086811e63f59a34999b07f/lib/rhapsody/router/modelRouter/index.js#L47-L63
train
rhapsodyjs/RhapsodyJS
lib/rhapsody/router/modelRouter/index.js
function(req, res, next, relationship) { if(req.fullModel.hasRelationship(relationship)) { return next(); } return responseUtils.respond(res, 400); //Malformed syntax or a bad query }
javascript
function(req, res, next, relationship) { if(req.fullModel.hasRelationship(relationship)) { return next(); } return responseUtils.respond(res, 400); //Malformed syntax or a bad query }
[ "function", "(", "req", ",", "res", ",", "next", ",", "relationship", ")", "{", "if", "(", "req", ".", "fullModel", ".", "hasRelationship", "(", "relationship", ")", ")", "{", "return", "next", "(", ")", ";", "}", "return", "responseUtils", ".", "respond", "(", "res", ",", "400", ")", ";", "}" ]
Check whether req.fullModel has relationship @param {ExpressRequest} req @param {ExpressResponse} res @param {Function} next Pass to the next route @param {String} relationship Relationship name
[ "Check", "whether", "req", ".", "fullModel", "has", "relationship" ]
49cd89d3f82841b2d8086811e63f59a34999b07f
https://github.com/rhapsodyjs/RhapsodyJS/blob/49cd89d3f82841b2d8086811e63f59a34999b07f/lib/rhapsody/router/modelRouter/index.js#L72-L78
train
rhapsodyjs/RhapsodyJS
lib/rhapsody/router/modelRouter/index.js
bindMiddlewares
function bindMiddlewares() { var modelName, _this = this; for(modelName in Rhapsody.models) { (function(model) { model.options.middlewares.forEach(function(middleware) { if(typeof middleware !== 'function') { middleware = require(path.join(Rhapsody.root, '/app/middlewares/' + middleware)); } modelName = '/' + modelName; _this.router.post(modelName, middleware); _this.router.post(modelName + '/:id/:relationship', middleware); _this.router.get(modelName + '/:id?', middleware); _this.router.get(modelName + '/:id/:relationship', middleware); _this.router.put(modelName + '/:id', middleware); _this.router.patch(modelName + '/:id', middleware); _this.router.delete(modelName + '/:id', middleware); }); }(Rhapsody.models[modelName])); } }
javascript
function bindMiddlewares() { var modelName, _this = this; for(modelName in Rhapsody.models) { (function(model) { model.options.middlewares.forEach(function(middleware) { if(typeof middleware !== 'function') { middleware = require(path.join(Rhapsody.root, '/app/middlewares/' + middleware)); } modelName = '/' + modelName; _this.router.post(modelName, middleware); _this.router.post(modelName + '/:id/:relationship', middleware); _this.router.get(modelName + '/:id?', middleware); _this.router.get(modelName + '/:id/:relationship', middleware); _this.router.put(modelName + '/:id', middleware); _this.router.patch(modelName + '/:id', middleware); _this.router.delete(modelName + '/:id', middleware); }); }(Rhapsody.models[modelName])); } }
[ "function", "bindMiddlewares", "(", ")", "{", "var", "modelName", ",", "_this", "=", "this", ";", "for", "(", "modelName", "in", "Rhapsody", ".", "models", ")", "{", "(", "function", "(", "model", ")", "{", "model", ".", "options", ".", "middlewares", ".", "forEach", "(", "function", "(", "middleware", ")", "{", "if", "(", "typeof", "middleware", "!==", "'function'", ")", "{", "middleware", "=", "require", "(", "path", ".", "join", "(", "Rhapsody", ".", "root", ",", "'/app/middlewares/'", "+", "middleware", ")", ")", ";", "}", "modelName", "=", "'/'", "+", "modelName", ";", "_this", ".", "router", ".", "post", "(", "modelName", ",", "middleware", ")", ";", "_this", ".", "router", ".", "post", "(", "modelName", "+", "'/:id/:relationship'", ",", "middleware", ")", ";", "_this", ".", "router", ".", "get", "(", "modelName", "+", "'/:id?'", ",", "middleware", ")", ";", "_this", ".", "router", ".", "get", "(", "modelName", "+", "'/:id/:relationship'", ",", "middleware", ")", ";", "_this", ".", "router", ".", "put", "(", "modelName", "+", "'/:id'", ",", "middleware", ")", ";", "_this", ".", "router", ".", "patch", "(", "modelName", "+", "'/:id'", ",", "middleware", ")", ";", "_this", ".", "router", ".", "delete", "(", "modelName", "+", "'/:id'", ",", "middleware", ")", ";", "}", ")", ";", "}", "(", "Rhapsody", ".", "models", "[", "modelName", "]", ")", ")", ";", "}", "}" ]
Bind the middlewares to the model routes
[ "Bind", "the", "middlewares", "to", "the", "model", "routes" ]
49cd89d3f82841b2d8086811e63f59a34999b07f
https://github.com/rhapsodyjs/RhapsodyJS/blob/49cd89d3f82841b2d8086811e63f59a34999b07f/lib/rhapsody/router/modelRouter/index.js#L83-L109
train
subschema/subschema
src/ValueManager.js
function (e, errors, value, path) { var parts = path && path.split('.') || [], i = 0, l = parts.length, pp = null; do { if (this.submitListeners.some(v=> { if (v.path === pp) { return (v.listener.call(v.scope, e, errors, value, path) === false); } }, this) === true) { return false } pp = tpath(pp, parts[i]); } while (i++ < l); return true; }
javascript
function (e, errors, value, path) { var parts = path && path.split('.') || [], i = 0, l = parts.length, pp = null; do { if (this.submitListeners.some(v=> { if (v.path === pp) { return (v.listener.call(v.scope, e, errors, value, path) === false); } }, this) === true) { return false } pp = tpath(pp, parts[i]); } while (i++ < l); return true; }
[ "function", "(", "e", ",", "errors", ",", "value", ",", "path", ")", "{", "var", "parts", "=", "path", "&&", "path", ".", "split", "(", "'.'", ")", "||", "[", "]", ",", "i", "=", "0", ",", "l", "=", "parts", ".", "length", ",", "pp", "=", "null", ";", "do", "{", "if", "(", "this", ".", "submitListeners", ".", "some", "(", "v", "=>", "{", "if", "(", "v", ".", "path", "===", "pp", ")", "{", "return", "(", "v", ".", "listener", ".", "call", "(", "v", ".", "scope", ",", "e", ",", "errors", ",", "value", ",", "path", ")", "===", "false", ")", ";", "}", "}", ",", "this", ")", "===", "true", ")", "{", "return", "false", "}", "pp", "=", "tpath", "(", "pp", ",", "parts", "[", "i", "]", ")", ";", "}", "while", "(", "i", "++", "<", "l", ")", ";", "return", "true", ";", "}" ]
When onSubmit is called this is fired
[ "When", "onSubmit", "is", "called", "this", "is", "fired" ]
55c07ee019b1e1ca0ebfb9266ccddd258c3e45b3
https://github.com/subschema/subschema/blob/55c07ee019b1e1ca0ebfb9266ccddd258c3e45b3/src/ValueManager.js#L130-L143
train
gwtw/js-sorting
lib/heapsort.js
heapify
function heapify(array, heapSize, i, compare, swap) { var left = i * 2 + 1; var right = i * 2 + 2; var largest = i; if (left < heapSize && compare(array, left, largest) > 0) { largest = left; } if (right < heapSize && compare(array, right, largest) > 0) { largest = right; } if (largest !== i) { swap(array, i, largest); heapify(array, heapSize, largest, compare, swap); } }
javascript
function heapify(array, heapSize, i, compare, swap) { var left = i * 2 + 1; var right = i * 2 + 2; var largest = i; if (left < heapSize && compare(array, left, largest) > 0) { largest = left; } if (right < heapSize && compare(array, right, largest) > 0) { largest = right; } if (largest !== i) { swap(array, i, largest); heapify(array, heapSize, largest, compare, swap); } }
[ "function", "heapify", "(", "array", ",", "heapSize", ",", "i", ",", "compare", ",", "swap", ")", "{", "var", "left", "=", "i", "*", "2", "+", "1", ";", "var", "right", "=", "i", "*", "2", "+", "2", ";", "var", "largest", "=", "i", ";", "if", "(", "left", "<", "heapSize", "&&", "compare", "(", "array", ",", "left", ",", "largest", ")", ">", "0", ")", "{", "largest", "=", "left", ";", "}", "if", "(", "right", "<", "heapSize", "&&", "compare", "(", "array", ",", "right", ",", "largest", ")", ">", "0", ")", "{", "largest", "=", "right", ";", "}", "if", "(", "largest", "!==", "i", ")", "{", "swap", "(", "array", ",", "i", ",", "largest", ")", ";", "heapify", "(", "array", ",", "heapSize", ",", "largest", ",", "compare", ",", "swap", ")", ";", "}", "}" ]
Heapify an array. @param {Array} array The array to build a heapify. @param {number} heapSize The size of the heap. @param {number} i The index of the array to heapify. @param {function} compare The compare function. @param {function} swap A function to call when the swap operation is performed. This can be used to listen in on internals of the algorithm. @returns The sorted array.
[ "Heapify", "an", "array", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/heapsort.js#L23-L39
train
gwtw/js-sorting
lib/heapsort.js
buildHeap
function buildHeap(array, heapSize, compare, swap) { for (var i = Math.floor(array.length / 2); i >= 0; i--) { heapify(array, heapSize, i, compare, swap); } }
javascript
function buildHeap(array, heapSize, compare, swap) { for (var i = Math.floor(array.length / 2); i >= 0; i--) { heapify(array, heapSize, i, compare, swap); } }
[ "function", "buildHeap", "(", "array", ",", "heapSize", ",", "compare", ",", "swap", ")", "{", "for", "(", "var", "i", "=", "Math", ".", "floor", "(", "array", ".", "length", "/", "2", ")", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "heapify", "(", "array", ",", "heapSize", ",", "i", ",", "compare", ",", "swap", ")", ";", "}", "}" ]
Build a heap out of an array. @param {Array} array The array to build a heap on. @param {number} heapSize The size of the heap. @param {function} compare The compare function. @param {function} swap A function to call when the swap operation is performed. This can be used to listen in on internals of the algorithm. @returns The sorted array.
[ "Build", "a", "heap", "out", "of", "an", "array", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/heapsort.js#L50-L54
train
gwtw/js-sorting
lib/heapsort.js
sort
function sort(array, compare, swap) { var heapSize = array.length; buildHeap(array, heapSize, compare, swap); while (heapSize > 1) { swap(array, 0, --heapSize); heapify(array, heapSize, 0, compare, swap); } return array; }
javascript
function sort(array, compare, swap) { var heapSize = array.length; buildHeap(array, heapSize, compare, swap); while (heapSize > 1) { swap(array, 0, --heapSize); heapify(array, heapSize, 0, compare, swap); } return array; }
[ "function", "sort", "(", "array", ",", "compare", ",", "swap", ")", "{", "var", "heapSize", "=", "array", ".", "length", ";", "buildHeap", "(", "array", ",", "heapSize", ",", "compare", ",", "swap", ")", ";", "while", "(", "heapSize", ">", "1", ")", "{", "swap", "(", "array", ",", "0", ",", "--", "heapSize", ")", ";", "heapify", "(", "array", ",", "heapSize", ",", "0", ",", "compare", ",", "swap", ")", ";", "}", "return", "array", ";", "}" ]
Sorts an array using heapsort. @param {Array} array The array to sort. @param {function} compare The compare function. @param {function} swap A function to call when the swap operation is performed. This can be used to listen in on internals of the algorithm. @returns The sorted array.
[ "Sorts", "an", "array", "using", "heapsort", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/heapsort.js#L64-L72
train
themouette/selenium-grid
src/driver/native.js
exposeNative
function exposeNative(Browser, command, exposed) { if (_.isNumber(exposed)) { exposed = command; } Browser.prototype[exposed] = function () { ensureDriverCommand.call(this, command, 'exposeNative'); var args = wrapArguments.call(this, arguments, errorToExceptionCallback); this._driver[command].apply(this._driver, args); return this; }; }
javascript
function exposeNative(Browser, command, exposed) { if (_.isNumber(exposed)) { exposed = command; } Browser.prototype[exposed] = function () { ensureDriverCommand.call(this, command, 'exposeNative'); var args = wrapArguments.call(this, arguments, errorToExceptionCallback); this._driver[command].apply(this._driver, args); return this; }; }
[ "function", "exposeNative", "(", "Browser", ",", "command", ",", "exposed", ")", "{", "if", "(", "_", ".", "isNumber", "(", "exposed", ")", ")", "{", "exposed", "=", "command", ";", "}", "Browser", ".", "prototype", "[", "exposed", "]", "=", "function", "(", ")", "{", "ensureDriverCommand", ".", "call", "(", "this", ",", "command", ",", "'exposeNative'", ")", ";", "var", "args", "=", "wrapArguments", ".", "call", "(", "this", ",", "arguments", ",", "errorToExceptionCallback", ")", ";", "this", ".", "_driver", "[", "command", "]", ".", "apply", "(", "this", ".", "_driver", ",", "args", ")", ";", "return", "this", ";", "}", ";", "}" ]
exposed methods handle errors as exceptions.
[ "exposed", "methods", "handle", "errors", "as", "exceptions", "." ]
b1971890ff0c6ee27869df0c6e8b384687492bb6
https://github.com/themouette/selenium-grid/blob/b1971890ff0c6ee27869df0c6e8b384687492bb6/src/driver/native.js#L76-L88
train
gwtw/js-sorting
lib/comb-sort.js
sort
function sort(array, compare, swap) { var gap = array.length; var shrinkFactor = 1.3; var swapped; while (gap > 1 || swapped) { if (gap > 1) { gap = Math.floor(gap / shrinkFactor); } swapped = false; for (var i = 0; gap + i < array.length; ++i) { if (compare(array, i, i + gap) > 0) { swap(array, i, i + gap); swapped = true; } } } return array; }
javascript
function sort(array, compare, swap) { var gap = array.length; var shrinkFactor = 1.3; var swapped; while (gap > 1 || swapped) { if (gap > 1) { gap = Math.floor(gap / shrinkFactor); } swapped = false; for (var i = 0; gap + i < array.length; ++i) { if (compare(array, i, i + gap) > 0) { swap(array, i, i + gap); swapped = true; } } } return array; }
[ "function", "sort", "(", "array", ",", "compare", ",", "swap", ")", "{", "var", "gap", "=", "array", ".", "length", ";", "var", "shrinkFactor", "=", "1.3", ";", "var", "swapped", ";", "while", "(", "gap", ">", "1", "||", "swapped", ")", "{", "if", "(", "gap", ">", "1", ")", "{", "gap", "=", "Math", ".", "floor", "(", "gap", "/", "shrinkFactor", ")", ";", "}", "swapped", "=", "false", ";", "for", "(", "var", "i", "=", "0", ";", "gap", "+", "i", "<", "array", ".", "length", ";", "++", "i", ")", "{", "if", "(", "compare", "(", "array", ",", "i", ",", "i", "+", "gap", ")", ">", "0", ")", "{", "swap", "(", "array", ",", "i", ",", "i", "+", "gap", ")", ";", "swapped", "=", "true", ";", "}", "}", "}", "return", "array", ";", "}" ]
Sorts an array using comb sort. @param {Array} array The array to sort. @param {function} compare The compare function. @param {function} swap A function to call when the swap operation is performed. This can be used to listen in on internals of the algorithm. @returns The sorted array.
[ "Sorts", "an", "array", "using", "comb", "sort", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/comb-sort.js#L21-L42
train
gwtw/js-sorting
lib/odd-even-sort.js
innerSort
function innerSort(array, i, compare, swap) { var sorted = true; for (; i < array.length - 1; i += 2) { if (compare(array, i, i + 1) > 0) { swap(array, i, i + 1); sorted = false; } } return sorted; }
javascript
function innerSort(array, i, compare, swap) { var sorted = true; for (; i < array.length - 1; i += 2) { if (compare(array, i, i + 1) > 0) { swap(array, i, i + 1); sorted = false; } } return sorted; }
[ "function", "innerSort", "(", "array", ",", "i", ",", "compare", ",", "swap", ")", "{", "var", "sorted", "=", "true", ";", "for", "(", ";", "i", "<", "array", ".", "length", "-", "1", ";", "i", "+=", "2", ")", "{", "if", "(", "compare", "(", "array", ",", "i", ",", "i", "+", "1", ")", ">", "0", ")", "{", "swap", "(", "array", ",", "i", ",", "i", "+", "1", ")", ";", "sorted", "=", "false", ";", "}", "}", "return", "sorted", ";", "}" ]
Compares every second element of an array with its following element and swaps it if not in order using a compare function. @param {Array} array The array to sort. @param {number} i The index to start at, should be either 0 or 1. @param {function} compare The compare function. @param {function} swap A function to call when the swap operation is performed. This can be used to listen in on internals of the algorithm. @returns The sorted array.
[ "Compares", "every", "second", "element", "of", "an", "array", "with", "its", "following", "element", "and", "swaps", "it", "if", "not", "in", "order", "using", "a", "compare", "function", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/odd-even-sort.js#L23-L32
train
gwtw/js-sorting
lib/odd-even-sort.js
sort
function sort(array, compare, swap) { var sorted = false; while (!sorted) { sorted = innerSort(array, 1, compare, swap); sorted = innerSort(array, 0, compare, swap) && sorted; } return array; }
javascript
function sort(array, compare, swap) { var sorted = false; while (!sorted) { sorted = innerSort(array, 1, compare, swap); sorted = innerSort(array, 0, compare, swap) && sorted; } return array; }
[ "function", "sort", "(", "array", ",", "compare", ",", "swap", ")", "{", "var", "sorted", "=", "false", ";", "while", "(", "!", "sorted", ")", "{", "sorted", "=", "innerSort", "(", "array", ",", "1", ",", "compare", ",", "swap", ")", ";", "sorted", "=", "innerSort", "(", "array", ",", "0", ",", "compare", ",", "swap", ")", "&&", "sorted", ";", "}", "return", "array", ";", "}" ]
Sorts an array using odd even sort. @param {Array} array The array to sort. @param {function} compare The compare function. @param {function} swap A function to call when the swap operation is performed. This can be used to listen in on internals of the algorithm. @returns The sorted array.
[ "Sorts", "an", "array", "using", "odd", "even", "sort", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/odd-even-sort.js#L42-L49
train
themouette/selenium-grid
src/driver/utils.js
errorToExceptionCallback
function errorToExceptionCallback(cb) { var browser = this; return function errorWrapped(err) { if (err) throw err; if (cb) { cb.apply(browser, _.tail(arguments)); } }; }
javascript
function errorToExceptionCallback(cb) { var browser = this; return function errorWrapped(err) { if (err) throw err; if (cb) { cb.apply(browser, _.tail(arguments)); } }; }
[ "function", "errorToExceptionCallback", "(", "cb", ")", "{", "var", "browser", "=", "this", ";", "return", "function", "errorWrapped", "(", "err", ")", "{", "if", "(", "err", ")", "throw", "err", ";", "if", "(", "cb", ")", "{", "cb", ".", "apply", "(", "browser", ",", "_", ".", "tail", "(", "arguments", ")", ")", ";", "}", "}", ";", "}" ]
any error is thrown as an exception. remaining arguments are given to callback.
[ "any", "error", "is", "thrown", "as", "an", "exception", ".", "remaining", "arguments", "are", "given", "to", "callback", "." ]
b1971890ff0c6ee27869df0c6e8b384687492bb6
https://github.com/themouette/selenium-grid/blob/b1971890ff0c6ee27869df0c6e8b384687492bb6/src/driver/utils.js#L66-L75
train
themouette/selenium-grid
src/driver/utils.js
exposeThenNative
function exposeThenNative(Browser, command) { var exposed = ['then', ucfirst(command)].join(''); Browser.prototype[exposed] = function () { var args = arguments; ensureDriverCommand.call(this, command, 'exposeThenNative'); this.then(function (next) { args = wrapArguments.call(this, args, chainAndErrorCallback, next); this._driver[command].apply(this._driver, args); }); return this; }; }
javascript
function exposeThenNative(Browser, command) { var exposed = ['then', ucfirst(command)].join(''); Browser.prototype[exposed] = function () { var args = arguments; ensureDriverCommand.call(this, command, 'exposeThenNative'); this.then(function (next) { args = wrapArguments.call(this, args, chainAndErrorCallback, next); this._driver[command].apply(this._driver, args); }); return this; }; }
[ "function", "exposeThenNative", "(", "Browser", ",", "command", ")", "{", "var", "exposed", "=", "[", "'then'", ",", "ucfirst", "(", "command", ")", "]", ".", "join", "(", "''", ")", ";", "Browser", ".", "prototype", "[", "exposed", "]", "=", "function", "(", ")", "{", "var", "args", "=", "arguments", ";", "ensureDriverCommand", ".", "call", "(", "this", ",", "command", ",", "'exposeThenNative'", ")", ";", "this", ".", "then", "(", "function", "(", "next", ")", "{", "args", "=", "wrapArguments", ".", "call", "(", "this", ",", "args", ",", "chainAndErrorCallback", ",", "next", ")", ";", "this", ".", "_driver", "[", "command", "]", ".", "apply", "(", "this", ".", "_driver", ",", "args", ")", ";", "}", ")", ";", "return", "this", ";", "}", ";", "}" ]
expose a native command to promise api. if a callback is given, next is not called automaticly.
[ "expose", "a", "native", "command", "to", "promise", "api", ".", "if", "a", "callback", "is", "given", "next", "is", "not", "called", "automaticly", "." ]
b1971890ff0c6ee27869df0c6e8b384687492bb6
https://github.com/themouette/selenium-grid/blob/b1971890ff0c6ee27869df0c6e8b384687492bb6/src/driver/utils.js#L132-L146
train
gwtw/js-sorting
lib/radix-sort.js
countingSortByDigit
function countingSortByDigit(array, radix, exponent, minValue) { var i; var bucketIndex; var buckets = new Array(radix); var output = new Array(array.length); // Initialize bucket for (i = 0; i < radix; i++) { buckets[i] = 0; } // Count frequencies for (i = 0; i < array.length; i++) { bucketIndex = Math.floor(((array[i] - minValue) / exponent) % radix); buckets[bucketIndex]++; } // Compute cumulates for (i = 1; i < radix; i++) { buckets[i] += buckets[i - 1]; } // Move records for (i = array.length - 1; i >= 0; i--) { bucketIndex = Math.floor(((array[i] - minValue) / exponent) % radix); output[--buckets[bucketIndex]] = array[i]; } // Copy back for (i = 0; i < array.length; i++) { array[i] = output[i]; } return array; }
javascript
function countingSortByDigit(array, radix, exponent, minValue) { var i; var bucketIndex; var buckets = new Array(radix); var output = new Array(array.length); // Initialize bucket for (i = 0; i < radix; i++) { buckets[i] = 0; } // Count frequencies for (i = 0; i < array.length; i++) { bucketIndex = Math.floor(((array[i] - minValue) / exponent) % radix); buckets[bucketIndex]++; } // Compute cumulates for (i = 1; i < radix; i++) { buckets[i] += buckets[i - 1]; } // Move records for (i = array.length - 1; i >= 0; i--) { bucketIndex = Math.floor(((array[i] - minValue) / exponent) % radix); output[--buckets[bucketIndex]] = array[i]; } // Copy back for (i = 0; i < array.length; i++) { array[i] = output[i]; } return array; }
[ "function", "countingSortByDigit", "(", "array", ",", "radix", ",", "exponent", ",", "minValue", ")", "{", "var", "i", ";", "var", "bucketIndex", ";", "var", "buckets", "=", "new", "Array", "(", "radix", ")", ";", "var", "output", "=", "new", "Array", "(", "array", ".", "length", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "radix", ";", "i", "++", ")", "{", "buckets", "[", "i", "]", "=", "0", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "bucketIndex", "=", "Math", ".", "floor", "(", "(", "(", "array", "[", "i", "]", "-", "minValue", ")", "/", "exponent", ")", "%", "radix", ")", ";", "buckets", "[", "bucketIndex", "]", "++", ";", "}", "for", "(", "i", "=", "1", ";", "i", "<", "radix", ";", "i", "++", ")", "{", "buckets", "[", "i", "]", "+=", "buckets", "[", "i", "-", "1", "]", ";", "}", "for", "(", "i", "=", "array", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "bucketIndex", "=", "Math", ".", "floor", "(", "(", "(", "array", "[", "i", "]", "-", "minValue", ")", "/", "exponent", ")", "%", "radix", ")", ";", "output", "[", "--", "buckets", "[", "bucketIndex", "]", "]", "=", "array", "[", "i", "]", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "array", "[", "i", "]", "=", "output", "[", "i", "]", ";", "}", "return", "array", ";", "}" ]
Stable sorts an array by a particular digit using counting sort. @param {Array} array The array to sort. @param {number} radix The base/radix to use to sort. @param {number} exponent The exponent of the significant digit to sort. @param {number} minValue The minimum value within the array. @returns The sorted array.
[ "Stable", "sorts", "an", "array", "by", "a", "particular", "digit", "using", "counting", "sort", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/radix-sort.js#L15-L49
train
gwtw/js-sorting
lib/radix-sort.js
sort
function sort(array, radix) { if (array.length === 0) { return array; } radix = radix || 10; // Determine minimum and maximum values var minValue = array[0]; var maxValue = array[0]; for (var i = 1; i < array.length; i++) { if (array[i] < minValue) { minValue = array[i]; } else if (array[i] > maxValue) { maxValue = array[i]; } } // Perform counting sort on each exponent/digit, starting at the least // significant digit var exponent = 1; while ((maxValue - minValue) / exponent >= 1) { array = countingSortByDigit(array, radix, exponent, minValue); exponent *= radix; } return array; }
javascript
function sort(array, radix) { if (array.length === 0) { return array; } radix = radix || 10; // Determine minimum and maximum values var minValue = array[0]; var maxValue = array[0]; for (var i = 1; i < array.length; i++) { if (array[i] < minValue) { minValue = array[i]; } else if (array[i] > maxValue) { maxValue = array[i]; } } // Perform counting sort on each exponent/digit, starting at the least // significant digit var exponent = 1; while ((maxValue - minValue) / exponent >= 1) { array = countingSortByDigit(array, radix, exponent, minValue); exponent *= radix; } return array; }
[ "function", "sort", "(", "array", ",", "radix", ")", "{", "if", "(", "array", ".", "length", "===", "0", ")", "{", "return", "array", ";", "}", "radix", "=", "radix", "||", "10", ";", "var", "minValue", "=", "array", "[", "0", "]", ";", "var", "maxValue", "=", "array", "[", "0", "]", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "array", ".", "length", ";", "i", "++", ")", "{", "if", "(", "array", "[", "i", "]", "<", "minValue", ")", "{", "minValue", "=", "array", "[", "i", "]", ";", "}", "else", "if", "(", "array", "[", "i", "]", ">", "maxValue", ")", "{", "maxValue", "=", "array", "[", "i", "]", ";", "}", "}", "var", "exponent", "=", "1", ";", "while", "(", "(", "maxValue", "-", "minValue", ")", "/", "exponent", ">=", "1", ")", "{", "array", "=", "countingSortByDigit", "(", "array", ",", "radix", ",", "exponent", ",", "minValue", ")", ";", "exponent", "*=", "radix", ";", "}", "return", "array", ";", "}" ]
Sorts an array using radix sort. @param {Array} array The array to sort. @param {number} [radix=10] The base/radix to use. @returns The sorted array.
[ "Sorts", "an", "array", "using", "radix", "sort", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/radix-sort.js#L57-L85
train
gwtw/js-sorting
lib/quicksort.js
partitionRandom
function partitionRandom(array, left, right, compare, swap) { var pivot = left + Math.floor(Math.random() * (right - left)); if (pivot !== right) { swap(array, right, pivot); } return partitionRight(array, left, right, compare, swap); }
javascript
function partitionRandom(array, left, right, compare, swap) { var pivot = left + Math.floor(Math.random() * (right - left)); if (pivot !== right) { swap(array, right, pivot); } return partitionRight(array, left, right, compare, swap); }
[ "function", "partitionRandom", "(", "array", ",", "left", ",", "right", ",", "compare", ",", "swap", ")", "{", "var", "pivot", "=", "left", "+", "Math", ".", "floor", "(", "Math", ".", "random", "(", ")", "*", "(", "right", "-", "left", ")", ")", ";", "if", "(", "pivot", "!==", "right", ")", "{", "swap", "(", "array", ",", "right", ",", "pivot", ")", ";", "}", "return", "partitionRight", "(", "array", ",", "left", ",", "right", ",", "compare", ",", "swap", ")", ";", "}" ]
Partition the array by selecting a random pivot and moving all elements less than the pivot to a lesser index and all elements greater than the pivot to a greater index. @param {Array} array The array to sort. @param {number} left The index to sort from. @param {number} right The index to sort to. @param {function} compare The compare function. @param {function} swapObserver A function to call when the swap operation is performed. This can be used to listen in on internals of the algorithm. @returns The pivot.
[ "Partition", "the", "array", "by", "selecting", "a", "random", "pivot", "and", "moving", "all", "elements", "less", "than", "the", "pivot", "to", "a", "lesser", "index", "and", "all", "elements", "greater", "than", "the", "pivot", "to", "a", "greater", "index", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/quicksort.js#L44-L50
train
gwtw/js-sorting
lib/quicksort.js
partitionRight
function partitionRight(array, left, right, compare, swap) { var mid = left; for (var i = mid; i < right; i++) { if (compare(array, i, right) <= 0) { if (i !== mid) { swap(array, i, mid); } mid++; } } if (right !== mid) { swap(array, right, mid); } return mid; }
javascript
function partitionRight(array, left, right, compare, swap) { var mid = left; for (var i = mid; i < right; i++) { if (compare(array, i, right) <= 0) { if (i !== mid) { swap(array, i, mid); } mid++; } } if (right !== mid) { swap(array, right, mid); } return mid; }
[ "function", "partitionRight", "(", "array", ",", "left", ",", "right", ",", "compare", ",", "swap", ")", "{", "var", "mid", "=", "left", ";", "for", "(", "var", "i", "=", "mid", ";", "i", "<", "right", ";", "i", "++", ")", "{", "if", "(", "compare", "(", "array", ",", "i", ",", "right", ")", "<=", "0", ")", "{", "if", "(", "i", "!==", "mid", ")", "{", "swap", "(", "array", ",", "i", ",", "mid", ")", ";", "}", "mid", "++", ";", "}", "}", "if", "(", "right", "!==", "mid", ")", "{", "swap", "(", "array", ",", "right", ",", "mid", ")", ";", "}", "return", "mid", ";", "}" ]
Partition the array using the right most element as the pivot by moving all elements less than the pivot to a lesser index and all elements greater than the pivot to a greater index. @param {Array} array The array to sort. @param {number} left The index to sort from. @param {number} right The index to sort to. @param {function} compare The compare function. @param {function} swapObserver A function to call when the swap operation is performed. This can be used to listen in on internals of the algorithm. @returns The pivot.
[ "Partition", "the", "array", "using", "the", "right", "most", "element", "as", "the", "pivot", "by", "moving", "all", "elements", "less", "than", "the", "pivot", "to", "a", "lesser", "index", "and", "all", "elements", "greater", "than", "the", "pivot", "to", "a", "greater", "index", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/quicksort.js#L64-L80
train
davedoesdev/simple-crypt
dist/simple-crypt-deps.js
function(word,iteration) { /* rotate the 32-bit word 8 bits to the left */ word = this.rotate(word); /* apply S-Box substitution on all 4 parts of the 32-bit word */ for (var i = 0; i < 4; ++i) word[i] = this.sbox[word[i]]; /* XOR the output of the rcon operation with i to the first part (leftmost) only */ word[0] = word[0]^this.Rcon[iteration]; return word; }
javascript
function(word,iteration) { /* rotate the 32-bit word 8 bits to the left */ word = this.rotate(word); /* apply S-Box substitution on all 4 parts of the 32-bit word */ for (var i = 0; i < 4; ++i) word[i] = this.sbox[word[i]]; /* XOR the output of the rcon operation with i to the first part (leftmost) only */ word[0] = word[0]^this.Rcon[iteration]; return word; }
[ "function", "(", "word", ",", "iteration", ")", "{", "word", "=", "this", ".", "rotate", "(", "word", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "4", ";", "++", "i", ")", "word", "[", "i", "]", "=", "this", ".", "sbox", "[", "word", "[", "i", "]", "]", ";", "word", "[", "0", "]", "=", "word", "[", "0", "]", "^", "this", ".", "Rcon", "[", "iteration", "]", ";", "return", "word", ";", "}" ]
Key Schedule Core
[ "Key", "Schedule", "Core" ]
406225a854239db7d4cccc82b1e482388a48b758
https://github.com/davedoesdev/simple-crypt/blob/406225a854239db7d4cccc82b1e482388a48b758/dist/simple-crypt-deps.js#L249-L259
train
davedoesdev/simple-crypt
dist/simple-crypt-deps.js
function(expandedKey,roundKeyPointer) { var roundKey = []; for (var i = 0; i < 4; i++) for (var j = 0; j < 4; j++) roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4 + j]; return roundKey; }
javascript
function(expandedKey,roundKeyPointer) { var roundKey = []; for (var i = 0; i < 4; i++) for (var j = 0; j < 4; j++) roundKey[j*4+i] = expandedKey[roundKeyPointer + i*4 + j]; return roundKey; }
[ "function", "(", "expandedKey", ",", "roundKeyPointer", ")", "{", "var", "roundKey", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "for", "(", "var", "j", "=", "0", ";", "j", "<", "4", ";", "j", "++", ")", "roundKey", "[", "j", "*", "4", "+", "i", "]", "=", "expandedKey", "[", "roundKeyPointer", "+", "i", "*", "4", "+", "j", "]", ";", "return", "roundKey", ";", "}" ]
Creates a round key from the given expanded key and the position within the expanded key.
[ "Creates", "a", "round", "key", "from", "the", "given", "expanded", "key", "and", "the", "position", "within", "the", "expanded", "key", "." ]
406225a854239db7d4cccc82b1e482388a48b758
https://github.com/davedoesdev/simple-crypt/blob/406225a854239db7d4cccc82b1e482388a48b758/dist/simple-crypt-deps.js#L323-L330
train
davedoesdev/simple-crypt
dist/simple-crypt-deps.js
function(a,b) { var p = 0; for(var counter = 0; counter < 8; counter++) { if((b & 1) == 1) p ^= a; if(p > 0x100) p ^= 0x100; var hi_bit_set = (a & 0x80); //keep p 8 bit a <<= 1; if(a > 0x100) a ^= 0x100; //keep a 8 bit if(hi_bit_set == 0x80) a ^= 0x1b; if(a > 0x100) a ^= 0x100; //keep a 8 bit b >>= 1; if(b > 0x100) b ^= 0x100; //keep b 8 bit } return p; }
javascript
function(a,b) { var p = 0; for(var counter = 0; counter < 8; counter++) { if((b & 1) == 1) p ^= a; if(p > 0x100) p ^= 0x100; var hi_bit_set = (a & 0x80); //keep p 8 bit a <<= 1; if(a > 0x100) a ^= 0x100; //keep a 8 bit if(hi_bit_set == 0x80) a ^= 0x1b; if(a > 0x100) a ^= 0x100; //keep a 8 bit b >>= 1; if(b > 0x100) b ^= 0x100; //keep b 8 bit } return p; }
[ "function", "(", "a", ",", "b", ")", "{", "var", "p", "=", "0", ";", "for", "(", "var", "counter", "=", "0", ";", "counter", "<", "8", ";", "counter", "++", ")", "{", "if", "(", "(", "b", "&", "1", ")", "==", "1", ")", "p", "^=", "a", ";", "if", "(", "p", ">", "0x100", ")", "p", "^=", "0x100", ";", "var", "hi_bit_set", "=", "(", "a", "&", "0x80", ")", ";", "a", "<<=", "1", ";", "if", "(", "a", ">", "0x100", ")", "a", "^=", "0x100", ";", "if", "(", "hi_bit_set", "==", "0x80", ")", "a", "^=", "0x1b", ";", "if", "(", "a", ">", "0x100", ")", "a", "^=", "0x100", ";", "b", ">>=", "1", ";", "if", "(", "b", ">", "0x100", ")", "b", "^=", "0x100", ";", "}", "return", "p", ";", "}" ]
galois multiplication of 8 bit characters a and b
[ "galois", "multiplication", "of", "8", "bit", "characters", "a", "and", "b" ]
406225a854239db7d4cccc82b1e482388a48b758
https://github.com/davedoesdev/simple-crypt/blob/406225a854239db7d4cccc82b1e482388a48b758/dist/simple-crypt-deps.js#L374-L392
train
davedoesdev/simple-crypt
dist/simple-crypt-deps.js
function(state,isInv) { var column = []; /* iterate over the 4 columns */ for (var i = 0; i < 4; i++) { /* construct one column by iterating over the 4 rows */ for (var j = 0; j < 4; j++) column[j] = state[(j*4)+i]; /* apply the mixColumn on one column */ column = this.mixColumn(column,isInv); /* put the values back into the state */ for (var k = 0; k < 4; k++) state[(k*4)+i] = column[k]; } return state; }
javascript
function(state,isInv) { var column = []; /* iterate over the 4 columns */ for (var i = 0; i < 4; i++) { /* construct one column by iterating over the 4 rows */ for (var j = 0; j < 4; j++) column[j] = state[(j*4)+i]; /* apply the mixColumn on one column */ column = this.mixColumn(column,isInv); /* put the values back into the state */ for (var k = 0; k < 4; k++) state[(k*4)+i] = column[k]; } return state; }
[ "function", "(", "state", ",", "isInv", ")", "{", "var", "column", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "{", "for", "(", "var", "j", "=", "0", ";", "j", "<", "4", ";", "j", "++", ")", "column", "[", "j", "]", "=", "state", "[", "(", "j", "*", "4", ")", "+", "i", "]", ";", "column", "=", "this", ".", "mixColumn", "(", "column", ",", "isInv", ")", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "4", ";", "k", "++", ")", "state", "[", "(", "k", "*", "4", ")", "+", "i", "]", "=", "column", "[", "k", "]", ";", "}", "return", "state", ";", "}" ]
galois multipication of the 4x4 matrix
[ "galois", "multipication", "of", "the", "4x4", "matrix" ]
406225a854239db7d4cccc82b1e482388a48b758
https://github.com/davedoesdev/simple-crypt/blob/406225a854239db7d4cccc82b1e482388a48b758/dist/simple-crypt-deps.js#L395-L411
train
davedoesdev/simple-crypt
dist/simple-crypt-deps.js
function(column,isInv) { var mult = []; if(isInv) mult = [14,9,13,11]; else mult = [2,1,1,3]; var cpy = []; for(var i = 0; i < 4; i++) cpy[i] = column[i]; column[0] = this.galois_multiplication(cpy[0],mult[0]) ^ this.galois_multiplication(cpy[3],mult[1]) ^ this.galois_multiplication(cpy[2],mult[2]) ^ this.galois_multiplication(cpy[1],mult[3]); column[1] = this.galois_multiplication(cpy[1],mult[0]) ^ this.galois_multiplication(cpy[0],mult[1]) ^ this.galois_multiplication(cpy[3],mult[2]) ^ this.galois_multiplication(cpy[2],mult[3]); column[2] = this.galois_multiplication(cpy[2],mult[0]) ^ this.galois_multiplication(cpy[1],mult[1]) ^ this.galois_multiplication(cpy[0],mult[2]) ^ this.galois_multiplication(cpy[3],mult[3]); column[3] = this.galois_multiplication(cpy[3],mult[0]) ^ this.galois_multiplication(cpy[2],mult[1]) ^ this.galois_multiplication(cpy[1],mult[2]) ^ this.galois_multiplication(cpy[0],mult[3]); return column; }
javascript
function(column,isInv) { var mult = []; if(isInv) mult = [14,9,13,11]; else mult = [2,1,1,3]; var cpy = []; for(var i = 0; i < 4; i++) cpy[i] = column[i]; column[0] = this.galois_multiplication(cpy[0],mult[0]) ^ this.galois_multiplication(cpy[3],mult[1]) ^ this.galois_multiplication(cpy[2],mult[2]) ^ this.galois_multiplication(cpy[1],mult[3]); column[1] = this.galois_multiplication(cpy[1],mult[0]) ^ this.galois_multiplication(cpy[0],mult[1]) ^ this.galois_multiplication(cpy[3],mult[2]) ^ this.galois_multiplication(cpy[2],mult[3]); column[2] = this.galois_multiplication(cpy[2],mult[0]) ^ this.galois_multiplication(cpy[1],mult[1]) ^ this.galois_multiplication(cpy[0],mult[2]) ^ this.galois_multiplication(cpy[3],mult[3]); column[3] = this.galois_multiplication(cpy[3],mult[0]) ^ this.galois_multiplication(cpy[2],mult[1]) ^ this.galois_multiplication(cpy[1],mult[2]) ^ this.galois_multiplication(cpy[0],mult[3]); return column; }
[ "function", "(", "column", ",", "isInv", ")", "{", "var", "mult", "=", "[", "]", ";", "if", "(", "isInv", ")", "mult", "=", "[", "14", ",", "9", ",", "13", ",", "11", "]", ";", "else", "mult", "=", "[", "2", ",", "1", ",", "1", ",", "3", "]", ";", "var", "cpy", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "cpy", "[", "i", "]", "=", "column", "[", "i", "]", ";", "column", "[", "0", "]", "=", "this", ".", "galois_multiplication", "(", "cpy", "[", "0", "]", ",", "mult", "[", "0", "]", ")", "^", "this", ".", "galois_multiplication", "(", "cpy", "[", "3", "]", ",", "mult", "[", "1", "]", ")", "^", "this", ".", "galois_multiplication", "(", "cpy", "[", "2", "]", ",", "mult", "[", "2", "]", ")", "^", "this", ".", "galois_multiplication", "(", "cpy", "[", "1", "]", ",", "mult", "[", "3", "]", ")", ";", "column", "[", "1", "]", "=", "this", ".", "galois_multiplication", "(", "cpy", "[", "1", "]", ",", "mult", "[", "0", "]", ")", "^", "this", ".", "galois_multiplication", "(", "cpy", "[", "0", "]", ",", "mult", "[", "1", "]", ")", "^", "this", ".", "galois_multiplication", "(", "cpy", "[", "3", "]", ",", "mult", "[", "2", "]", ")", "^", "this", ".", "galois_multiplication", "(", "cpy", "[", "2", "]", ",", "mult", "[", "3", "]", ")", ";", "column", "[", "2", "]", "=", "this", ".", "galois_multiplication", "(", "cpy", "[", "2", "]", ",", "mult", "[", "0", "]", ")", "^", "this", ".", "galois_multiplication", "(", "cpy", "[", "1", "]", ",", "mult", "[", "1", "]", ")", "^", "this", ".", "galois_multiplication", "(", "cpy", "[", "0", "]", ",", "mult", "[", "2", "]", ")", "^", "this", ".", "galois_multiplication", "(", "cpy", "[", "3", "]", ",", "mult", "[", "3", "]", ")", ";", "column", "[", "3", "]", "=", "this", ".", "galois_multiplication", "(", "cpy", "[", "3", "]", ",", "mult", "[", "0", "]", ")", "^", "this", ".", "galois_multiplication", "(", "cpy", "[", "2", "]", ",", "mult", "[", "1", "]", ")", "^", "this", ".", "galois_multiplication", "(", "cpy", "[", "1", "]", ",", "mult", "[", "2", "]", ")", "^", "this", ".", "galois_multiplication", "(", "cpy", "[", "0", "]", ",", "mult", "[", "3", "]", ")", ";", "return", "column", ";", "}" ]
galois multipication of 1 column of the 4x4 matrix
[ "galois", "multipication", "of", "1", "column", "of", "the", "4x4", "matrix" ]
406225a854239db7d4cccc82b1e482388a48b758
https://github.com/davedoesdev/simple-crypt/blob/406225a854239db7d4cccc82b1e482388a48b758/dist/simple-crypt-deps.js#L414-L442
train
davedoesdev/simple-crypt
dist/simple-crypt-deps.js
function(state, roundKey) { state = this.subBytes(state,false); state = this.shiftRows(state,false); state = this.mixColumns(state,false); state = this.addRoundKey(state, roundKey); return state; }
javascript
function(state, roundKey) { state = this.subBytes(state,false); state = this.shiftRows(state,false); state = this.mixColumns(state,false); state = this.addRoundKey(state, roundKey); return state; }
[ "function", "(", "state", ",", "roundKey", ")", "{", "state", "=", "this", ".", "subBytes", "(", "state", ",", "false", ")", ";", "state", "=", "this", ".", "shiftRows", "(", "state", ",", "false", ")", ";", "state", "=", "this", ".", "mixColumns", "(", "state", ",", "false", ")", ";", "state", "=", "this", ".", "addRoundKey", "(", "state", ",", "roundKey", ")", ";", "return", "state", ";", "}" ]
applies the 4 operations of the forward round in sequence
[ "applies", "the", "4", "operations", "of", "the", "forward", "round", "in", "sequence" ]
406225a854239db7d4cccc82b1e482388a48b758
https://github.com/davedoesdev/simple-crypt/blob/406225a854239db7d4cccc82b1e482388a48b758/dist/simple-crypt-deps.js#L445-L452
train
davedoesdev/simple-crypt
dist/simple-crypt-deps.js
function(state,roundKey) { state = this.shiftRows(state,true); state = this.subBytes(state,true); state = this.addRoundKey(state, roundKey); state = this.mixColumns(state,true); return state; }
javascript
function(state,roundKey) { state = this.shiftRows(state,true); state = this.subBytes(state,true); state = this.addRoundKey(state, roundKey); state = this.mixColumns(state,true); return state; }
[ "function", "(", "state", ",", "roundKey", ")", "{", "state", "=", "this", ".", "shiftRows", "(", "state", ",", "true", ")", ";", "state", "=", "this", ".", "subBytes", "(", "state", ",", "true", ")", ";", "state", "=", "this", ".", "addRoundKey", "(", "state", ",", "roundKey", ")", ";", "state", "=", "this", ".", "mixColumns", "(", "state", ",", "true", ")", ";", "return", "state", ";", "}" ]
applies the 4 operations of the inverse round in sequence
[ "applies", "the", "4", "operations", "of", "the", "inverse", "round", "in", "sequence" ]
406225a854239db7d4cccc82b1e482388a48b758
https://github.com/davedoesdev/simple-crypt/blob/406225a854239db7d4cccc82b1e482388a48b758/dist/simple-crypt-deps.js#L455-L462
train
davedoesdev/simple-crypt
dist/simple-crypt-deps.js
function(input,key,size) { var output = []; var block = []; /* the 128 bit block to encode */ var nbrRounds = this.numberOfRounds(size); /* Set the block values, for the block: * a0,0 a0,1 a0,2 a0,3 * a1,0 a1,1 a1,2 a1,3 * a2,0 a2,1 a2,2 a2,3 * a3,0 a3,1 a3,2 a3,3 * the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3 */ for (var i = 0; i < 4; i++) /* iterate over the columns */ for (var j = 0; j < 4; j++) /* iterate over the rows */ block[(i+(j*4))] = input[(i*4)+j]; /* expand the key into an 176, 208, 240 bytes key */ var expandedKey = this.expandKey(key, size); /* the expanded key */ /* encrypt the block using the expandedKey */ block = this.main(block, expandedKey, nbrRounds); for (var k = 0; k < 4; k++) /* unmap the block again into the output */ for (var l = 0; l < 4; l++) /* iterate over the rows */ output[(k*4)+l] = block[(k+(l*4))]; return output; }
javascript
function(input,key,size) { var output = []; var block = []; /* the 128 bit block to encode */ var nbrRounds = this.numberOfRounds(size); /* Set the block values, for the block: * a0,0 a0,1 a0,2 a0,3 * a1,0 a1,1 a1,2 a1,3 * a2,0 a2,1 a2,2 a2,3 * a3,0 a3,1 a3,2 a3,3 * the mapping order is a0,0 a1,0 a2,0 a3,0 a0,1 a1,1 ... a2,3 a3,3 */ for (var i = 0; i < 4; i++) /* iterate over the columns */ for (var j = 0; j < 4; j++) /* iterate over the rows */ block[(i+(j*4))] = input[(i*4)+j]; /* expand the key into an 176, 208, 240 bytes key */ var expandedKey = this.expandKey(key, size); /* the expanded key */ /* encrypt the block using the expandedKey */ block = this.main(block, expandedKey, nbrRounds); for (var k = 0; k < 4; k++) /* unmap the block again into the output */ for (var l = 0; l < 4; l++) /* iterate over the rows */ output[(k*4)+l] = block[(k+(l*4))]; return output; }
[ "function", "(", "input", ",", "key", ",", "size", ")", "{", "var", "output", "=", "[", "]", ";", "var", "block", "=", "[", "]", ";", "var", "nbrRounds", "=", "this", ".", "numberOfRounds", "(", "size", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "4", ";", "i", "++", ")", "for", "(", "var", "j", "=", "0", ";", "j", "<", "4", ";", "j", "++", ")", "block", "[", "(", "i", "+", "(", "j", "*", "4", ")", ")", "]", "=", "input", "[", "(", "i", "*", "4", ")", "+", "j", "]", ";", "var", "expandedKey", "=", "this", ".", "expandKey", "(", "key", ",", "size", ")", ";", "block", "=", "this", ".", "main", "(", "block", ",", "expandedKey", ",", "nbrRounds", ")", ";", "for", "(", "var", "k", "=", "0", ";", "k", "<", "4", ";", "k", "++", ")", "for", "(", "var", "l", "=", "0", ";", "l", "<", "4", ";", "l", "++", ")", "output", "[", "(", "k", "*", "4", ")", "+", "l", "]", "=", "block", "[", "(", "k", "+", "(", "l", "*", "4", ")", ")", "]", ";", "return", "output", ";", "}" ]
encrypts a 128 bit input block against the given key of size specified
[ "encrypts", "a", "128", "bit", "input", "block", "against", "the", "given", "key", "of", "size", "specified" ]
406225a854239db7d4cccc82b1e482388a48b758
https://github.com/davedoesdev/simple-crypt/blob/406225a854239db7d4cccc82b1e482388a48b758/dist/simple-crypt-deps.js#L516-L540
train
davedoesdev/simple-crypt
dist/simple-crypt-deps.js
function(s1, s2) { var n = s1.length; if (s1.length > s2.length) n = s2.length; for (var i = 0; i < n; i++) { if (s1.charCodeAt(i) != s2.charCodeAt(i)) return i; } if (s1.length != s2.length) return n; return -1; // same }
javascript
function(s1, s2) { var n = s1.length; if (s1.length > s2.length) n = s2.length; for (var i = 0; i < n; i++) { if (s1.charCodeAt(i) != s2.charCodeAt(i)) return i; } if (s1.length != s2.length) return n; return -1; // same }
[ "function", "(", "s1", ",", "s2", ")", "{", "var", "n", "=", "s1", ".", "length", ";", "if", "(", "s1", ".", "length", ">", "s2", ".", "length", ")", "n", "=", "s2", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "n", ";", "i", "++", ")", "{", "if", "(", "s1", ".", "charCodeAt", "(", "i", ")", "!=", "s2", ".", "charCodeAt", "(", "i", ")", ")", "return", "i", ";", "}", "if", "(", "s1", ".", "length", "!=", "s2", ".", "length", ")", "return", "n", ";", "return", "-", "1", ";", "}" ]
find index of string where two string differs @name strdiffidx @function @param {String} s1 string to compare @param {String} s2 string to compare @return {Number} string index of where character differs. Return -1 if same. @since jsrsasign 4.9.0 base64x 1.1.5 @example strdiffidx("abcdefg", "abcd4fg") -> 4 strdiffidx("abcdefg", "abcdefg") -> -1 strdiffidx("abcdefg", "abcdef") -> 6 strdiffidx("abcdefgh", "abcdef") -> 6
[ "find", "index", "of", "string", "where", "two", "string", "differs" ]
406225a854239db7d4cccc82b1e482388a48b758
https://github.com/davedoesdev/simple-crypt/blob/406225a854239db7d4cccc82b1e482388a48b758/dist/simple-crypt-deps.js#L6321-L6329
train
davedoesdev/simple-crypt
dist/simple-crypt-deps.js
_rsapem_privateKeyToPkcs1HexString
function _rsapem_privateKeyToPkcs1HexString(rsaKey) { var result = _rsapem_derEncodeNumber(0); result += _rsapem_derEncodeNumber(rsaKey.n); result += _rsapem_derEncodeNumber(rsaKey.e); result += _rsapem_derEncodeNumber(rsaKey.d); result += _rsapem_derEncodeNumber(rsaKey.p); result += _rsapem_derEncodeNumber(rsaKey.q); result += _rsapem_derEncodeNumber(rsaKey.dmp1); result += _rsapem_derEncodeNumber(rsaKey.dmq1); result += _rsapem_derEncodeNumber(rsaKey.coeff); var fullLen = _rsapem_encodeLength(result.length / 2); return '30' + fullLen + result; }
javascript
function _rsapem_privateKeyToPkcs1HexString(rsaKey) { var result = _rsapem_derEncodeNumber(0); result += _rsapem_derEncodeNumber(rsaKey.n); result += _rsapem_derEncodeNumber(rsaKey.e); result += _rsapem_derEncodeNumber(rsaKey.d); result += _rsapem_derEncodeNumber(rsaKey.p); result += _rsapem_derEncodeNumber(rsaKey.q); result += _rsapem_derEncodeNumber(rsaKey.dmp1); result += _rsapem_derEncodeNumber(rsaKey.dmq1); result += _rsapem_derEncodeNumber(rsaKey.coeff); var fullLen = _rsapem_encodeLength(result.length / 2); return '30' + fullLen + result; }
[ "function", "_rsapem_privateKeyToPkcs1HexString", "(", "rsaKey", ")", "{", "var", "result", "=", "_rsapem_derEncodeNumber", "(", "0", ")", ";", "result", "+=", "_rsapem_derEncodeNumber", "(", "rsaKey", ".", "n", ")", ";", "result", "+=", "_rsapem_derEncodeNumber", "(", "rsaKey", ".", "e", ")", ";", "result", "+=", "_rsapem_derEncodeNumber", "(", "rsaKey", ".", "d", ")", ";", "result", "+=", "_rsapem_derEncodeNumber", "(", "rsaKey", ".", "p", ")", ";", "result", "+=", "_rsapem_derEncodeNumber", "(", "rsaKey", ".", "q", ")", ";", "result", "+=", "_rsapem_derEncodeNumber", "(", "rsaKey", ".", "dmp1", ")", ";", "result", "+=", "_rsapem_derEncodeNumber", "(", "rsaKey", ".", "dmq1", ")", ";", "result", "+=", "_rsapem_derEncodeNumber", "(", "rsaKey", ".", "coeff", ")", ";", "var", "fullLen", "=", "_rsapem_encodeLength", "(", "result", ".", "length", "/", "2", ")", ";", "return", "'30'", "+", "fullLen", "+", "result", ";", "}" ]
Converts private & public part of given key to ASN1 Hex String.
[ "Converts", "private", "&", "public", "part", "of", "given", "key", "to", "ASN1", "Hex", "String", "." ]
406225a854239db7d4cccc82b1e482388a48b758
https://github.com/davedoesdev/simple-crypt/blob/406225a854239db7d4cccc82b1e482388a48b758/dist/simple-crypt-deps.js#L8364-L8377
train
davedoesdev/simple-crypt
dist/simple-crypt-deps.js
_rsapem_publicKeyToX509HexString
function _rsapem_publicKeyToX509HexString(rsaKey) { var encodedIdentifier = "06092A864886F70D010101"; var encodedNull = "0500"; var headerSequence = "300D" + encodedIdentifier + encodedNull; var keys = _rsapem_derEncodeNumber(rsaKey.n); keys += _rsapem_derEncodeNumber(rsaKey.e); var keySequence = "0030" + _rsapem_encodeLength(keys.length / 2) + keys; var bitstring = "03" + _rsapem_encodeLength(keySequence.length / 2) + keySequence; var mainSequence = headerSequence + bitstring; return "30" + _rsapem_encodeLength(mainSequence.length / 2) + mainSequence; }
javascript
function _rsapem_publicKeyToX509HexString(rsaKey) { var encodedIdentifier = "06092A864886F70D010101"; var encodedNull = "0500"; var headerSequence = "300D" + encodedIdentifier + encodedNull; var keys = _rsapem_derEncodeNumber(rsaKey.n); keys += _rsapem_derEncodeNumber(rsaKey.e); var keySequence = "0030" + _rsapem_encodeLength(keys.length / 2) + keys; var bitstring = "03" + _rsapem_encodeLength(keySequence.length / 2) + keySequence; var mainSequence = headerSequence + bitstring; return "30" + _rsapem_encodeLength(mainSequence.length / 2) + mainSequence; }
[ "function", "_rsapem_publicKeyToX509HexString", "(", "rsaKey", ")", "{", "var", "encodedIdentifier", "=", "\"06092A864886F70D010101\"", ";", "var", "encodedNull", "=", "\"0500\"", ";", "var", "headerSequence", "=", "\"300D\"", "+", "encodedIdentifier", "+", "encodedNull", ";", "var", "keys", "=", "_rsapem_derEncodeNumber", "(", "rsaKey", ".", "n", ")", ";", "keys", "+=", "_rsapem_derEncodeNumber", "(", "rsaKey", ".", "e", ")", ";", "var", "keySequence", "=", "\"0030\"", "+", "_rsapem_encodeLength", "(", "keys", ".", "length", "/", "2", ")", "+", "keys", ";", "var", "bitstring", "=", "\"03\"", "+", "_rsapem_encodeLength", "(", "keySequence", ".", "length", "/", "2", ")", "+", "keySequence", ";", "var", "mainSequence", "=", "headerSequence", "+", "bitstring", ";", "return", "\"30\"", "+", "_rsapem_encodeLength", "(", "mainSequence", ".", "length", "/", "2", ")", "+", "mainSequence", ";", "}" ]
Converts public part of given key to ASN1 Hex String.
[ "Converts", "public", "part", "of", "given", "key", "to", "ASN1", "Hex", "String", "." ]
406225a854239db7d4cccc82b1e482388a48b758
https://github.com/davedoesdev/simple-crypt/blob/406225a854239db7d4cccc82b1e482388a48b758/dist/simple-crypt-deps.js#L8398-L8412
train
gwtw/js-sorting
lib/selection-sort.js
sort
function sort(array, compare, swap) { for (var i = 0; i < array.length - 1; i++) { var minIndex = i; for (var j = i + 1; j < array.length; j++) { if (compare(array, j, minIndex) < 0) { minIndex = j; } } if (minIndex !== i) { swap(array, i, minIndex); } } return array; }
javascript
function sort(array, compare, swap) { for (var i = 0; i < array.length - 1; i++) { var minIndex = i; for (var j = i + 1; j < array.length; j++) { if (compare(array, j, minIndex) < 0) { minIndex = j; } } if (minIndex !== i) { swap(array, i, minIndex); } } return array; }
[ "function", "sort", "(", "array", ",", "compare", ",", "swap", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "array", ".", "length", "-", "1", ";", "i", "++", ")", "{", "var", "minIndex", "=", "i", ";", "for", "(", "var", "j", "=", "i", "+", "1", ";", "j", "<", "array", ".", "length", ";", "j", "++", ")", "{", "if", "(", "compare", "(", "array", ",", "j", ",", "minIndex", ")", "<", "0", ")", "{", "minIndex", "=", "j", ";", "}", "}", "if", "(", "minIndex", "!==", "i", ")", "{", "swap", "(", "array", ",", "i", ",", "minIndex", ")", ";", "}", "}", "return", "array", ";", "}" ]
Sorts an array using selection sort. @param {Array} array The array to sort. @param {function} compare The compare function. @param {function} swap A function to call when the swap operation is performed. This can be used to listen in on internals of the algorithm. @returns The sorted array.
[ "Sorts", "an", "array", "using", "selection", "sort", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/selection-sort.js#L21-L37
train
MrPeak/flatten-tree
index.js
function(tree, options) { let list = []; const stack = []; console.log(tree); const _tree = _.cloneDeep(tree); const settings = { initNode: options.initNode || (node => node), itemsKey: options.itemsKey || 'children', idKey: options.idKey || 'id', uniqueIdStart: options.uniqueIdStart || 1, generateUniqueId: options.generateUniqueId || (() => settings.uniqueIdStart++), }; if (Array.isArray(_tree) && _tree.length) { // Object Array for (let i = 0, len = _tree.length; i < len; i++) { stack.push( flattenNodeGenerator( _tree[i], 'root', // placeholder i, settings, stack ) ); } } else { // One object tree stack.push(flattenNodeGenerator(_tree, 'root', 0, settings, stack)); } while (stack.length) { list = stack.shift()(list); } return list; }
javascript
function(tree, options) { let list = []; const stack = []; console.log(tree); const _tree = _.cloneDeep(tree); const settings = { initNode: options.initNode || (node => node), itemsKey: options.itemsKey || 'children', idKey: options.idKey || 'id', uniqueIdStart: options.uniqueIdStart || 1, generateUniqueId: options.generateUniqueId || (() => settings.uniqueIdStart++), }; if (Array.isArray(_tree) && _tree.length) { // Object Array for (let i = 0, len = _tree.length; i < len; i++) { stack.push( flattenNodeGenerator( _tree[i], 'root', // placeholder i, settings, stack ) ); } } else { // One object tree stack.push(flattenNodeGenerator(_tree, 'root', 0, settings, stack)); } while (stack.length) { list = stack.shift()(list); } return list; }
[ "function", "(", "tree", ",", "options", ")", "{", "let", "list", "=", "[", "]", ";", "const", "stack", "=", "[", "]", ";", "console", ".", "log", "(", "tree", ")", ";", "const", "_tree", "=", "_", ".", "cloneDeep", "(", "tree", ")", ";", "const", "settings", "=", "{", "initNode", ":", "options", ".", "initNode", "||", "(", "node", "=>", "node", ")", ",", "itemsKey", ":", "options", ".", "itemsKey", "||", "'children'", ",", "idKey", ":", "options", ".", "idKey", "||", "'id'", ",", "uniqueIdStart", ":", "options", ".", "uniqueIdStart", "||", "1", ",", "generateUniqueId", ":", "options", ".", "generateUniqueId", "||", "(", "(", ")", "=>", "settings", ".", "uniqueIdStart", "++", ")", ",", "}", ";", "if", "(", "Array", ".", "isArray", "(", "_tree", ")", "&&", "_tree", ".", "length", ")", "{", "for", "(", "let", "i", "=", "0", ",", "len", "=", "_tree", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "stack", ".", "push", "(", "flattenNodeGenerator", "(", "_tree", "[", "i", "]", ",", "'root'", ",", "i", ",", "settings", ",", "stack", ")", ")", ";", "}", "}", "else", "{", "stack", ".", "push", "(", "flattenNodeGenerator", "(", "_tree", ",", "'root'", ",", "0", ",", "settings", ",", "stack", ")", ")", ";", "}", "while", "(", "stack", ".", "length", ")", "{", "list", "=", "stack", ".", "shift", "(", ")", "(", "list", ")", ";", "}", "return", "list", ";", "}" ]
Flatten Object tree @param {Array|Object} tree - Object tree @param {Object} options - Config options @param {Function=} [options.initNode=(node=>node)] - Initialize node @param {String=} [options.itemsKey='children'] - Specifies item's children itemsKey @param {String=} [options.idKey='id'] - Specifies item's idKey @param {Number=} [options.uniqueIdStart=1] - Unique id start @param {Function=} [options.generateUniqueId=(() => settings.uniqueIdStart++)] - Unique id generator @return {Object[]} Flatten collection
[ "Flatten", "Object", "tree" ]
61f1fdf542334f597a055c9a59d8862404660cd1
https://github.com/MrPeak/flatten-tree/blob/61f1fdf542334f597a055c9a59d8862404660cd1/index.js#L60-L97
train
dwieeb/node-jsondir
src/File.js
function(options) { options = options || {}; this.path = PATH.resolve(PATH.normalize(options.path)); this.exists = FS.existsSync(this.path); this.umask = 'umask' in options ? options.umask : File.UMASK; if (this.exists) { this.stats = this.getStats(); this.type = this.getType(); this.mode = this.stats.mode & 511; // 511 == 0777 this.uid = this.stats.uid; this.gid = this.stats.gid; } else { this.owner = options.owner; this.group = options.group; if ('exists' in options && options.exists) { throw new File.FileMissingException('File was expected to exist, but does not.'); } if ('type' in options) { if (options.type in File.Types) { this.type = File.Types[options.type]; } else { throw new File.UnknownFileTypeException('Unknown file type: ' + options.type + '.'); } } else { throw new File.MissingRequiredParameterException('"type" is required for nonexistent files.'); } switch (this.type) { case File.Types.file: this.content = 'content' in options ? options.content : ''; break; case File.Types.symlink: if ('dest' in options) { this.dest = options.dest; } else { throw new File.MissingRequiredParameterException('"dest" is a required option for symlink files.'); } break; } this.mode = File.interpretMode(options.mode, options.type, this.umask); } }
javascript
function(options) { options = options || {}; this.path = PATH.resolve(PATH.normalize(options.path)); this.exists = FS.existsSync(this.path); this.umask = 'umask' in options ? options.umask : File.UMASK; if (this.exists) { this.stats = this.getStats(); this.type = this.getType(); this.mode = this.stats.mode & 511; // 511 == 0777 this.uid = this.stats.uid; this.gid = this.stats.gid; } else { this.owner = options.owner; this.group = options.group; if ('exists' in options && options.exists) { throw new File.FileMissingException('File was expected to exist, but does not.'); } if ('type' in options) { if (options.type in File.Types) { this.type = File.Types[options.type]; } else { throw new File.UnknownFileTypeException('Unknown file type: ' + options.type + '.'); } } else { throw new File.MissingRequiredParameterException('"type" is required for nonexistent files.'); } switch (this.type) { case File.Types.file: this.content = 'content' in options ? options.content : ''; break; case File.Types.symlink: if ('dest' in options) { this.dest = options.dest; } else { throw new File.MissingRequiredParameterException('"dest" is a required option for symlink files.'); } break; } this.mode = File.interpretMode(options.mode, options.type, this.umask); } }
[ "function", "(", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "this", ".", "path", "=", "PATH", ".", "resolve", "(", "PATH", ".", "normalize", "(", "options", ".", "path", ")", ")", ";", "this", ".", "exists", "=", "FS", ".", "existsSync", "(", "this", ".", "path", ")", ";", "this", ".", "umask", "=", "'umask'", "in", "options", "?", "options", ".", "umask", ":", "File", ".", "UMASK", ";", "if", "(", "this", ".", "exists", ")", "{", "this", ".", "stats", "=", "this", ".", "getStats", "(", ")", ";", "this", ".", "type", "=", "this", ".", "getType", "(", ")", ";", "this", ".", "mode", "=", "this", ".", "stats", ".", "mode", "&", "511", ";", "this", ".", "uid", "=", "this", ".", "stats", ".", "uid", ";", "this", ".", "gid", "=", "this", ".", "stats", ".", "gid", ";", "}", "else", "{", "this", ".", "owner", "=", "options", ".", "owner", ";", "this", ".", "group", "=", "options", ".", "group", ";", "if", "(", "'exists'", "in", "options", "&&", "options", ".", "exists", ")", "{", "throw", "new", "File", ".", "FileMissingException", "(", "'File was expected to exist, but does not.'", ")", ";", "}", "if", "(", "'type'", "in", "options", ")", "{", "if", "(", "options", ".", "type", "in", "File", ".", "Types", ")", "{", "this", ".", "type", "=", "File", ".", "Types", "[", "options", ".", "type", "]", ";", "}", "else", "{", "throw", "new", "File", ".", "UnknownFileTypeException", "(", "'Unknown file type: '", "+", "options", ".", "type", "+", "'.'", ")", ";", "}", "}", "else", "{", "throw", "new", "File", ".", "MissingRequiredParameterException", "(", "'\"type\" is required for nonexistent files.'", ")", ";", "}", "switch", "(", "this", ".", "type", ")", "{", "case", "File", ".", "Types", ".", "file", ":", "this", ".", "content", "=", "'content'", "in", "options", "?", "options", ".", "content", ":", "''", ";", "break", ";", "case", "File", ".", "Types", ".", "symlink", ":", "if", "(", "'dest'", "in", "options", ")", "{", "this", ".", "dest", "=", "options", ".", "dest", ";", "}", "else", "{", "throw", "new", "File", ".", "MissingRequiredParameterException", "(", "'\"dest\" is a required option for symlink files.'", ")", ";", "}", "break", ";", "}", "this", ".", "mode", "=", "File", ".", "interpretMode", "(", "options", ".", "mode", ",", "options", ".", "type", ",", "this", ".", "umask", ")", ";", "}", "}" ]
A File represents any regular, directory, or symlink file. @param {object} options
[ "A", "File", "represents", "any", "regular", "directory", "or", "symlink", "file", "." ]
40894504be170a74759de804e559dc0c589574eb
https://github.com/dwieeb/node-jsondir/blob/40894504be170a74759de804e559dc0c589574eb/src/File.js#L26-L78
train
gwtw/js-sorting
lib/merge-sort.js
sort
function sort(array, compare) { if (array.length <= 1) { return array; } var i; var middle = Math.floor(array.length / 2); var left = new Array(middle); var right = new Array(array.length - middle); for (i = 0; i < left.length; i++) { left[i] = array[i]; } for (i = 0; i < right.length; i++) { right[i] = array[i + left.length]; } return merge(sort(left, compare), sort(right, compare), compare); }
javascript
function sort(array, compare) { if (array.length <= 1) { return array; } var i; var middle = Math.floor(array.length / 2); var left = new Array(middle); var right = new Array(array.length - middle); for (i = 0; i < left.length; i++) { left[i] = array[i]; } for (i = 0; i < right.length; i++) { right[i] = array[i + left.length]; } return merge(sort(left, compare), sort(right, compare), compare); }
[ "function", "sort", "(", "array", ",", "compare", ")", "{", "if", "(", "array", ".", "length", "<=", "1", ")", "{", "return", "array", ";", "}", "var", "i", ";", "var", "middle", "=", "Math", ".", "floor", "(", "array", ".", "length", "/", "2", ")", ";", "var", "left", "=", "new", "Array", "(", "middle", ")", ";", "var", "right", "=", "new", "Array", "(", "array", ".", "length", "-", "middle", ")", ";", "for", "(", "i", "=", "0", ";", "i", "<", "left", ".", "length", ";", "i", "++", ")", "{", "left", "[", "i", "]", "=", "array", "[", "i", "]", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "right", ".", "length", ";", "i", "++", ")", "{", "right", "[", "i", "]", "=", "array", "[", "i", "+", "left", ".", "length", "]", ";", "}", "return", "merge", "(", "sort", "(", "left", ",", "compare", ")", ",", "sort", "(", "right", ",", "compare", ")", ",", "compare", ")", ";", "}" ]
Sorts an array using top down merge sort. @param {Array} array The array to sort. @param {function} compare The compare function. @returns The sorted array.
[ "Sorts", "an", "array", "using", "top", "down", "merge", "sort", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/merge-sort.js#L15-L33
train
gwtw/js-sorting
lib/merge-sort.js
merge
function merge(left, right, compare) { var result = []; var leftIndex = 0; var rightIndex = 0; while (leftIndex < left.length || rightIndex < right.length) { if (leftIndex < left.length && rightIndex < right.length) { if (compare(left[leftIndex], right[rightIndex]) <= 0) { result.push(left[leftIndex++]); } else { result.push(right[rightIndex++]); } } else if (leftIndex < left.length) { result.push(left[leftIndex++]); } else if (rightIndex < right.length) { result.push(right[rightIndex++]); } } return result; }
javascript
function merge(left, right, compare) { var result = []; var leftIndex = 0; var rightIndex = 0; while (leftIndex < left.length || rightIndex < right.length) { if (leftIndex < left.length && rightIndex < right.length) { if (compare(left[leftIndex], right[rightIndex]) <= 0) { result.push(left[leftIndex++]); } else { result.push(right[rightIndex++]); } } else if (leftIndex < left.length) { result.push(left[leftIndex++]); } else if (rightIndex < right.length) { result.push(right[rightIndex++]); } } return result; }
[ "function", "merge", "(", "left", ",", "right", ",", "compare", ")", "{", "var", "result", "=", "[", "]", ";", "var", "leftIndex", "=", "0", ";", "var", "rightIndex", "=", "0", ";", "while", "(", "leftIndex", "<", "left", ".", "length", "||", "rightIndex", "<", "right", ".", "length", ")", "{", "if", "(", "leftIndex", "<", "left", ".", "length", "&&", "rightIndex", "<", "right", ".", "length", ")", "{", "if", "(", "compare", "(", "left", "[", "leftIndex", "]", ",", "right", "[", "rightIndex", "]", ")", "<=", "0", ")", "{", "result", ".", "push", "(", "left", "[", "leftIndex", "++", "]", ")", ";", "}", "else", "{", "result", ".", "push", "(", "right", "[", "rightIndex", "++", "]", ")", ";", "}", "}", "else", "if", "(", "leftIndex", "<", "left", ".", "length", ")", "{", "result", ".", "push", "(", "left", "[", "leftIndex", "++", "]", ")", ";", "}", "else", "if", "(", "rightIndex", "<", "right", ".", "length", ")", "{", "result", ".", "push", "(", "right", "[", "rightIndex", "++", "]", ")", ";", "}", "}", "return", "result", ";", "}" ]
Merges two arrays in to a new array. @param {Array} left The first array. @param {Array} left The second array. @param {function} compare The compare function. @return The merged array.
[ "Merges", "two", "arrays", "in", "to", "a", "new", "array", "." ]
158286752539a4ec3bfc7c0f578372953357d4ed
https://github.com/gwtw/js-sorting/blob/158286752539a4ec3bfc7c0f578372953357d4ed/lib/merge-sort.js#L42-L61
train
themouette/selenium-grid
src/driver/selector.js
exposeThenSelector
function exposeThenSelector(Browser, command, exposed) { if (_.isNumber(exposed)) { exposed = command; } exposed = ['then', ucfirst(exposed)].join(''); Browser.prototype[exposed] = function () { var args = arguments; ensureDriverCommand.call(this, command, 'exposeThenSelector'); this.then(function (next) { args = wrapArguments.call(this, args, chainAndErrorCallback, next); args = wrapSelectorArguments(args); this._driver[command].apply(this._driver, args); }); return this; }; }
javascript
function exposeThenSelector(Browser, command, exposed) { if (_.isNumber(exposed)) { exposed = command; } exposed = ['then', ucfirst(exposed)].join(''); Browser.prototype[exposed] = function () { var args = arguments; ensureDriverCommand.call(this, command, 'exposeThenSelector'); this.then(function (next) { args = wrapArguments.call(this, args, chainAndErrorCallback, next); args = wrapSelectorArguments(args); this._driver[command].apply(this._driver, args); }); return this; }; }
[ "function", "exposeThenSelector", "(", "Browser", ",", "command", ",", "exposed", ")", "{", "if", "(", "_", ".", "isNumber", "(", "exposed", ")", ")", "{", "exposed", "=", "command", ";", "}", "exposed", "=", "[", "'then'", ",", "ucfirst", "(", "exposed", ")", "]", ".", "join", "(", "''", ")", ";", "Browser", ".", "prototype", "[", "exposed", "]", "=", "function", "(", ")", "{", "var", "args", "=", "arguments", ";", "ensureDriverCommand", ".", "call", "(", "this", ",", "command", ",", "'exposeThenSelector'", ")", ";", "this", ".", "then", "(", "function", "(", "next", ")", "{", "args", "=", "wrapArguments", ".", "call", "(", "this", ",", "args", ",", "chainAndErrorCallback", ",", "next", ")", ";", "args", "=", "wrapSelectorArguments", "(", "args", ")", ";", "this", ".", "_driver", "[", "command", "]", ".", "apply", "(", "this", ".", "_driver", ",", "args", ")", ";", "}", ")", ";", "return", "this", ";", "}", ";", "}" ]
expose a native selector command to promise api. if a callback is given, next is not called automaticly.
[ "expose", "a", "native", "selector", "command", "to", "promise", "api", ".", "if", "a", "callback", "is", "given", "next", "is", "not", "called", "automaticly", "." ]
b1971890ff0c6ee27869df0c6e8b384687492bb6
https://github.com/themouette/selenium-grid/blob/b1971890ff0c6ee27869df0c6e8b384687492bb6/src/driver/selector.js#L109-L127
train
themouette/selenium-grid
src/driver/selector.js
_fillInputText
function _fillInputText(element, value, next) { var onFilled = chainAndErrorCallback.call(this, null, next); var onClear = chainAndErrorCallback.call(this, function () { element.type(value || '', onFilled); }, onFilled); element.clear(onClear); }
javascript
function _fillInputText(element, value, next) { var onFilled = chainAndErrorCallback.call(this, null, next); var onClear = chainAndErrorCallback.call(this, function () { element.type(value || '', onFilled); }, onFilled); element.clear(onClear); }
[ "function", "_fillInputText", "(", "element", ",", "value", ",", "next", ")", "{", "var", "onFilled", "=", "chainAndErrorCallback", ".", "call", "(", "this", ",", "null", ",", "next", ")", ";", "var", "onClear", "=", "chainAndErrorCallback", ".", "call", "(", "this", ",", "function", "(", ")", "{", "element", ".", "type", "(", "value", "||", "''", ",", "onFilled", ")", ";", "}", ",", "onFilled", ")", ";", "element", ".", "clear", "(", "onClear", ")", ";", "}" ]
fill an input text or a textarea
[ "fill", "an", "input", "text", "or", "a", "textarea" ]
b1971890ff0c6ee27869df0c6e8b384687492bb6
https://github.com/themouette/selenium-grid/blob/b1971890ff0c6ee27869df0c6e8b384687492bb6/src/driver/selector.js#L305-L312
train
themouette/selenium-grid
src/driver/selector.js
_fillInputFile
function _fillInputFile(element, value, next) { var onUploadDone = function (localPath) { element.type(localPath, next); }; this.uploadFile(value, onUploadDone); }
javascript
function _fillInputFile(element, value, next) { var onUploadDone = function (localPath) { element.type(localPath, next); }; this.uploadFile(value, onUploadDone); }
[ "function", "_fillInputFile", "(", "element", ",", "value", ",", "next", ")", "{", "var", "onUploadDone", "=", "function", "(", "localPath", ")", "{", "element", ".", "type", "(", "localPath", ",", "next", ")", ";", "}", ";", "this", ".", "uploadFile", "(", "value", ",", "onUploadDone", ")", ";", "}" ]
upload a file to selenium slave and fill the input with reference.
[ "upload", "a", "file", "to", "selenium", "slave", "and", "fill", "the", "input", "with", "reference", "." ]
b1971890ff0c6ee27869df0c6e8b384687492bb6
https://github.com/themouette/selenium-grid/blob/b1971890ff0c6ee27869df0c6e8b384687492bb6/src/driver/selector.js#L314-L319
train
themouette/selenium-grid
src/driver/selector.js
_fillInputCheckbox
function _fillInputCheckbox(element, value, next) { var onIsSelected = chainAndErrorCallback.call(this, function (selected, next) { //ensure boolean value = !!value; if (value === selected) { // nothing to do return next(); } element.click(next); }, next); element.isSelected(onIsSelected); }
javascript
function _fillInputCheckbox(element, value, next) { var onIsSelected = chainAndErrorCallback.call(this, function (selected, next) { //ensure boolean value = !!value; if (value === selected) { // nothing to do return next(); } element.click(next); }, next); element.isSelected(onIsSelected); }
[ "function", "_fillInputCheckbox", "(", "element", ",", "value", ",", "next", ")", "{", "var", "onIsSelected", "=", "chainAndErrorCallback", ".", "call", "(", "this", ",", "function", "(", "selected", ",", "next", ")", "{", "value", "=", "!", "!", "value", ";", "if", "(", "value", "===", "selected", ")", "{", "return", "next", "(", ")", ";", "}", "element", ".", "click", "(", "next", ")", ";", "}", ",", "next", ")", ";", "element", ".", "isSelected", "(", "onIsSelected", ")", ";", "}" ]
check or uncheck given checkbox
[ "check", "or", "uncheck", "given", "checkbox" ]
b1971890ff0c6ee27869df0c6e8b384687492bb6
https://github.com/themouette/selenium-grid/blob/b1971890ff0c6ee27869df0c6e8b384687492bb6/src/driver/selector.js#L321-L332
train
themouette/selenium-grid
src/driver/selector.js
_fillInputRadio
function _fillInputRadio(name, value, next) { this.element({ value: "//input[@name='"+escapeString(name, "'")+"' and @value='"+escapeString(value, "'")+"']", strategy: "xpath" }, function (el) { el.click(next); }); }
javascript
function _fillInputRadio(name, value, next) { this.element({ value: "//input[@name='"+escapeString(name, "'")+"' and @value='"+escapeString(value, "'")+"']", strategy: "xpath" }, function (el) { el.click(next); }); }
[ "function", "_fillInputRadio", "(", "name", ",", "value", ",", "next", ")", "{", "this", ".", "element", "(", "{", "value", ":", "\"//input[@name='\"", "+", "escapeString", "(", "name", ",", "\"'\"", ")", "+", "\"' and @value='\"", "+", "escapeString", "(", "value", ",", "\"'\"", ")", "+", "\"']\"", ",", "strategy", ":", "\"xpath\"", "}", ",", "function", "(", "el", ")", "{", "el", ".", "click", "(", "next", ")", ";", "}", ")", ";", "}" ]
retrieve the radio button qith value and click on it
[ "retrieve", "the", "radio", "button", "qith", "value", "and", "click", "on", "it" ]
b1971890ff0c6ee27869df0c6e8b384687492bb6
https://github.com/themouette/selenium-grid/blob/b1971890ff0c6ee27869df0c6e8b384687492bb6/src/driver/selector.js#L334-L341
train
themouette/selenium-grid
src/driver/selector.js
_fillSelect
function _fillSelect(element, value, next) { var clickOnOption = chainAndErrorCallback.call(this, function (el, next) { el.click(next); }, next); element.elementByXPath("//option[@value='"+escapeString(value, "'")+"']", clickOnOption); }
javascript
function _fillSelect(element, value, next) { var clickOnOption = chainAndErrorCallback.call(this, function (el, next) { el.click(next); }, next); element.elementByXPath("//option[@value='"+escapeString(value, "'")+"']", clickOnOption); }
[ "function", "_fillSelect", "(", "element", ",", "value", ",", "next", ")", "{", "var", "clickOnOption", "=", "chainAndErrorCallback", ".", "call", "(", "this", ",", "function", "(", "el", ",", "next", ")", "{", "el", ".", "click", "(", "next", ")", ";", "}", ",", "next", ")", ";", "element", ".", "elementByXPath", "(", "\"//option[@value='\"", "+", "escapeString", "(", "value", ",", "\"'\"", ")", "+", "\"']\"", ",", "clickOnOption", ")", ";", "}" ]
open select and select element
[ "open", "select", "and", "select", "element" ]
b1971890ff0c6ee27869df0c6e8b384687492bb6
https://github.com/themouette/selenium-grid/blob/b1971890ff0c6ee27869df0c6e8b384687492bb6/src/driver/selector.js#L343-L348
train
sitegui/ejs-html
lib/custom.js
appendJSValue
function appendJSValue(token) { builder.add('(') if (options.compileDebug) { builder.add(`${compile._getDebugMarker(token)},`) } builder.addToken(token) builder.add(')') }
javascript
function appendJSValue(token) { builder.add('(') if (options.compileDebug) { builder.add(`${compile._getDebugMarker(token)},`) } builder.addToken(token) builder.add(')') }
[ "function", "appendJSValue", "(", "token", ")", "{", "builder", ".", "add", "(", "'('", ")", "if", "(", "options", ".", "compileDebug", ")", "{", "builder", ".", "add", "(", "`", "${", "compile", ".", "_getDebugMarker", "(", "token", ")", "}", "`", ")", "}", "builder", ".", "addToken", "(", "token", ")", "builder", ".", "add", "(", "')'", ")", "}" ]
Append ejs expression, with position update @param {Token} token - ejs-escaped token
[ "Append", "ejs", "expression", "with", "position", "update" ]
cfad09dd07d4b121da130327c8221222db5f6cb4
https://github.com/sitegui/ejs-html/blob/cfad09dd07d4b121da130327c8221222db5f6cb4/lib/custom.js#L99-L106
train
sitegui/ejs-html
lib/custom.js
prepareContents
function prepareContents(tokens) { let contents = new Map for (let i = 0, len = tokens.length; i < len; i++) { let token = tokens[i] if (token.type === 'element' && token.name === 'eh-content') { // Find attribute 'name' let name = getNameAttributeValue(token), arr = getArr(name) for (let j = 0, len2 = token.children.length; j < len2; j++) { arr.push(token.children[j]) } } else { getArr('').push(token) } } /** * @param {string} name * @returns {Array<Token>} */ function getArr(name) { if (!contents.has(name)) { let arr = [] contents.set(name, arr) return arr } return contents.get(name) } return contents }
javascript
function prepareContents(tokens) { let contents = new Map for (let i = 0, len = tokens.length; i < len; i++) { let token = tokens[i] if (token.type === 'element' && token.name === 'eh-content') { // Find attribute 'name' let name = getNameAttributeValue(token), arr = getArr(name) for (let j = 0, len2 = token.children.length; j < len2; j++) { arr.push(token.children[j]) } } else { getArr('').push(token) } } /** * @param {string} name * @returns {Array<Token>} */ function getArr(name) { if (!contents.has(name)) { let arr = [] contents.set(name, arr) return arr } return contents.get(name) } return contents }
[ "function", "prepareContents", "(", "tokens", ")", "{", "let", "contents", "=", "new", "Map", "for", "(", "let", "i", "=", "0", ",", "len", "=", "tokens", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "let", "token", "=", "tokens", "[", "i", "]", "if", "(", "token", ".", "type", "===", "'element'", "&&", "token", ".", "name", "===", "'eh-content'", ")", "{", "let", "name", "=", "getNameAttributeValue", "(", "token", ")", ",", "arr", "=", "getArr", "(", "name", ")", "for", "(", "let", "j", "=", "0", ",", "len2", "=", "token", ".", "children", ".", "length", ";", "j", "<", "len2", ";", "j", "++", ")", "{", "arr", ".", "push", "(", "token", ".", "children", "[", "j", "]", ")", "}", "}", "else", "{", "getArr", "(", "''", ")", ".", "push", "(", "token", ")", "}", "}", "function", "getArr", "(", "name", ")", "{", "if", "(", "!", "contents", ".", "has", "(", "name", ")", ")", "{", "let", "arr", "=", "[", "]", "contents", ".", "set", "(", "name", ",", "arr", ")", "return", "arr", "}", "return", "contents", ".", "get", "(", "name", ")", "}", "return", "contents", "}" ]
Split children tokens by content name @param {Array<Token>} tokens @returns {Map<string, Array<Token>>}
[ "Split", "children", "tokens", "by", "content", "name" ]
cfad09dd07d4b121da130327c8221222db5f6cb4
https://github.com/sitegui/ejs-html/blob/cfad09dd07d4b121da130327c8221222db5f6cb4/lib/custom.js#L135-L168
train
sitegui/ejs-html
lib/custom.js
getNameAttributeValue
function getNameAttributeValue(element) { for (let i = 0, len = element.attributes.length; i < len; i++) { let attribute = element.attributes[i] if (attribute.name === 'name') { if (attribute.type !== 'attribute-simple') { throw new Error(`name attribute for ${element.name} tag must be a literal value`) } return attribute.value } } return '' }
javascript
function getNameAttributeValue(element) { for (let i = 0, len = element.attributes.length; i < len; i++) { let attribute = element.attributes[i] if (attribute.name === 'name') { if (attribute.type !== 'attribute-simple') { throw new Error(`name attribute for ${element.name} tag must be a literal value`) } return attribute.value } } return '' }
[ "function", "getNameAttributeValue", "(", "element", ")", "{", "for", "(", "let", "i", "=", "0", ",", "len", "=", "element", ".", "attributes", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "let", "attribute", "=", "element", ".", "attributes", "[", "i", "]", "if", "(", "attribute", ".", "name", "===", "'name'", ")", "{", "if", "(", "attribute", ".", "type", "!==", "'attribute-simple'", ")", "{", "throw", "new", "Error", "(", "`", "${", "element", ".", "name", "}", "`", ")", "}", "return", "attribute", ".", "value", "}", "}", "return", "''", "}" ]
Return the value of the `value` attribute @param {Token} element - must be of type 'element' @returns {string}
[ "Return", "the", "value", "of", "the", "value", "attribute" ]
cfad09dd07d4b121da130327c8221222db5f6cb4
https://github.com/sitegui/ejs-html/blob/cfad09dd07d4b121da130327c8221222db5f6cb4/lib/custom.js#L175-L188
train
sitegui/ejs-html
lib/compile.js
prepareInternalJSCode
function prepareInternalJSCode(source, options) { // Parse let tokens = parse(source) // Transform if (options.transformer) { tokens = options.transformer(tokens) || tokens } let reducedTokens = reduce(tokens, options) return createCode(reducedTokens, options, false) }
javascript
function prepareInternalJSCode(source, options) { // Parse let tokens = parse(source) // Transform if (options.transformer) { tokens = options.transformer(tokens) || tokens } let reducedTokens = reduce(tokens, options) return createCode(reducedTokens, options, false) }
[ "function", "prepareInternalJSCode", "(", "source", ",", "options", ")", "{", "let", "tokens", "=", "parse", "(", "source", ")", "if", "(", "options", ".", "transformer", ")", "{", "tokens", "=", "options", ".", "transformer", "(", "tokens", ")", "||", "tokens", "}", "let", "reducedTokens", "=", "reduce", "(", "tokens", ",", "options", ")", "return", "createCode", "(", "reducedTokens", ",", "options", ",", "false", ")", "}" ]
Common logic for `compile` and `compile.standAlone` @private @param {string} source @param {Object} options - already prepared @returns {SourceBuilder}
[ "Common", "logic", "for", "compile", "and", "compile", ".", "standAlone" ]
cfad09dd07d4b121da130327c8221222db5f6cb4
https://github.com/sitegui/ejs-html/blob/cfad09dd07d4b121da130327c8221222db5f6cb4/lib/compile.js#L151-L163
train
sitegui/ejs-html
lib/compile.js
appendExpression
function appendExpression(prefix, token, suffix, isString) { if (state === 'very-first') { if (!isString) { builder.add('""+') } } else if (state === 'first') { builder.add('__o+=') } else { builder.add('+') } if (options.compileDebug && token) { builder.add(`(${getDebugMarker(token)},`) } if (prefix) { builder.add(prefix) } if (token) { if (token.type === 'source-builder') { builder.addBuilder(token.sourceBuilder) } else { builder.addToken(token) } } if (suffix) { builder.add(suffix) } if (options.compileDebug && token) { builder.add(')') } state = 'rest' }
javascript
function appendExpression(prefix, token, suffix, isString) { if (state === 'very-first') { if (!isString) { builder.add('""+') } } else if (state === 'first') { builder.add('__o+=') } else { builder.add('+') } if (options.compileDebug && token) { builder.add(`(${getDebugMarker(token)},`) } if (prefix) { builder.add(prefix) } if (token) { if (token.type === 'source-builder') { builder.addBuilder(token.sourceBuilder) } else { builder.addToken(token) } } if (suffix) { builder.add(suffix) } if (options.compileDebug && token) { builder.add(')') } state = 'rest' }
[ "function", "appendExpression", "(", "prefix", ",", "token", ",", "suffix", ",", "isString", ")", "{", "if", "(", "state", "===", "'very-first'", ")", "{", "if", "(", "!", "isString", ")", "{", "builder", ".", "add", "(", "'\"\"+'", ")", "}", "}", "else", "if", "(", "state", "===", "'first'", ")", "{", "builder", ".", "add", "(", "'__o+='", ")", "}", "else", "{", "builder", ".", "add", "(", "'+'", ")", "}", "if", "(", "options", ".", "compileDebug", "&&", "token", ")", "{", "builder", ".", "add", "(", "`", "${", "getDebugMarker", "(", "token", ")", "}", "`", ")", "}", "if", "(", "prefix", ")", "{", "builder", ".", "add", "(", "prefix", ")", "}", "if", "(", "token", ")", "{", "if", "(", "token", ".", "type", "===", "'source-builder'", ")", "{", "builder", ".", "addBuilder", "(", "token", ".", "sourceBuilder", ")", "}", "else", "{", "builder", ".", "addToken", "(", "token", ")", "}", "}", "if", "(", "suffix", ")", "{", "builder", ".", "add", "(", "suffix", ")", "}", "if", "(", "options", ".", "compileDebug", "&&", "token", ")", "{", "builder", ".", "add", "(", "')'", ")", "}", "state", "=", "'rest'", "}" ]
Append an expression that contributes directly to the output @param {?string} prefix @param {?Token|SourceBuilder} token @param {?string} suffix @param {boolean} isString - whether this expression certainly evaluates to a string
[ "Append", "an", "expression", "that", "contributes", "directly", "to", "the", "output" ]
cfad09dd07d4b121da130327c8221222db5f6cb4
https://github.com/sitegui/ejs-html/blob/cfad09dd07d4b121da130327c8221222db5f6cb4/lib/compile.js#L256-L288
train
ohager/nanoflux
examples/fullflux.js
ActionProvider
function ActionProvider(dispatcher){ this.action1 = function(data){ console.log("Action 1"); // this way, the dispatcher establishes dynamically the action binding. dispatcher.dispatch('action1', data); }; this.action2 = function(data){ console.log("Action 2"); dispatcher.dispatch('action2', data); } }
javascript
function ActionProvider(dispatcher){ this.action1 = function(data){ console.log("Action 1"); // this way, the dispatcher establishes dynamically the action binding. dispatcher.dispatch('action1', data); }; this.action2 = function(data){ console.log("Action 2"); dispatcher.dispatch('action2', data); } }
[ "function", "ActionProvider", "(", "dispatcher", ")", "{", "this", ".", "action1", "=", "function", "(", "data", ")", "{", "console", ".", "log", "(", "\"Action 1\"", ")", ";", "dispatcher", ".", "dispatch", "(", "'action1'", ",", "data", ")", ";", "}", ";", "this", ".", "action2", "=", "function", "(", "data", ")", "{", "console", ".", "log", "(", "\"Action 2\"", ")", ";", "dispatcher", ".", "dispatch", "(", "'action2'", ",", "data", ")", ";", "}", "}" ]
The full flux concept foresees a separation of actions and dispatcher Here we create an action provider using the more dynamic Dispatcher.dispatch method.
[ "The", "full", "flux", "concept", "foresees", "a", "separation", "of", "actions", "and", "dispatcher", "Here", "we", "create", "an", "action", "provider", "using", "the", "more", "dynamic", "Dispatcher", ".", "dispatch", "method", "." ]
df3840a496867869ddaccf6c0433819d6caaf125
https://github.com/ohager/nanoflux/blob/df3840a496867869ddaccf6c0433819d6caaf125/examples/fullflux.js#L32-L44
train
sitegui/ejs-html
lib/parse.js
readSimpleToken
function readSimpleToken(type, endRegex, trimRight) { if (trimRight) { let matchTrim = exec(/\S/g) if (matchTrim) { advanceTo(matchTrim.index) } } let match = exec(endRegex) if (!match) { throwSyntaxError(`Unterminated ${type}`) } let start = getSourcePoint() advanceTo(match.index) let token = createContentToken(type, start) advanceTo(endRegex.lastIndex) return token }
javascript
function readSimpleToken(type, endRegex, trimRight) { if (trimRight) { let matchTrim = exec(/\S/g) if (matchTrim) { advanceTo(matchTrim.index) } } let match = exec(endRegex) if (!match) { throwSyntaxError(`Unterminated ${type}`) } let start = getSourcePoint() advanceTo(match.index) let token = createContentToken(type, start) advanceTo(endRegex.lastIndex) return token }
[ "function", "readSimpleToken", "(", "type", ",", "endRegex", ",", "trimRight", ")", "{", "if", "(", "trimRight", ")", "{", "let", "matchTrim", "=", "exec", "(", "/", "\\S", "/", "g", ")", "if", "(", "matchTrim", ")", "{", "advanceTo", "(", "matchTrim", ".", "index", ")", "}", "}", "let", "match", "=", "exec", "(", "endRegex", ")", "if", "(", "!", "match", ")", "{", "throwSyntaxError", "(", "`", "${", "type", "}", "`", ")", "}", "let", "start", "=", "getSourcePoint", "(", ")", "advanceTo", "(", "match", ".", "index", ")", "let", "token", "=", "createContentToken", "(", "type", ",", "start", ")", "advanceTo", "(", "endRegex", ".", "lastIndex", ")", "return", "token", "}" ]
Read a single token that has a known end @param {string} type @param {RegExp} endRegex @param {boolean} trimRight - ignore starting empty spaces (\s) @returns {Token}
[ "Read", "a", "single", "token", "that", "has", "a", "known", "end" ]
cfad09dd07d4b121da130327c8221222db5f6cb4
https://github.com/sitegui/ejs-html/blob/cfad09dd07d4b121da130327c8221222db5f6cb4/lib/parse.js#L174-L190
train
sitegui/ejs-html
lib/parse.js
readCloseTag
function readCloseTag() { let start = getSourcePoint(), match = tagCloseRegex.exec(source.substr(pos)) if (!match) { throwSyntaxError('Invalid close tag') } advanceTo(pos + match[0].length) let end = getSourcePoint() return { type: 'tag-close', start, end, name: match[1].toLowerCase() } }
javascript
function readCloseTag() { let start = getSourcePoint(), match = tagCloseRegex.exec(source.substr(pos)) if (!match) { throwSyntaxError('Invalid close tag') } advanceTo(pos + match[0].length) let end = getSourcePoint() return { type: 'tag-close', start, end, name: match[1].toLowerCase() } }
[ "function", "readCloseTag", "(", ")", "{", "let", "start", "=", "getSourcePoint", "(", ")", ",", "match", "=", "tagCloseRegex", ".", "exec", "(", "source", ".", "substr", "(", "pos", ")", ")", "if", "(", "!", "match", ")", "{", "throwSyntaxError", "(", "'Invalid close tag'", ")", "}", "advanceTo", "(", "pos", "+", "match", "[", "0", "]", ".", "length", ")", "let", "end", "=", "getSourcePoint", "(", ")", "return", "{", "type", ":", "'tag-close'", ",", "start", ",", "end", ",", "name", ":", "match", "[", "1", "]", ".", "toLowerCase", "(", ")", "}", "}" ]
Read a close tag token @returns {Token}
[ "Read", "a", "close", "tag", "token" ]
cfad09dd07d4b121da130327c8221222db5f6cb4
https://github.com/sitegui/ejs-html/blob/cfad09dd07d4b121da130327c8221222db5f6cb4/lib/parse.js#L196-L210
train
sitegui/ejs-html
lib/parse.js
readOpenTag
function readOpenTag() { // Read tag name let start = getSourcePoint(), match = tagNameRegex.exec(source.substr(pos)) if (!match) { throwSyntaxError('Invalid open tag') } let tagName = match[0].toLowerCase(), isVoid = voidElementsRegex.test(tagName) advanceTo(pos + tagName.length) // Keep reading content let selfClose = false, attributes = [], // Used to detect repeated attributes foundAttributeNames = [] while (true) { // Match using anchored regex let match = tagOpenContentStartRegex.exec(source.substr(pos)) if (!match) { throwSyntaxError('Invalid open tag') } advanceTo(pos + match[0].length) if (match[1] === '<%-') { throwSyntaxError('EJS unescaped tags are not allowed inside open tags') } else if (match[1] === '<%=') { throwSyntaxError('EJS escaped tags are not allowed inside open tags') } else if (match[1] === '<%') { throwSyntaxError('EJS eval tags are not allowed inside open tags') } else if (match[1] === '>') { break } else if (match[1] === '/>') { selfClose = true break } else { // Attribute start let lowerName = match[1].toLowerCase() if (foundAttributeNames.indexOf(lowerName) !== -1) { throwSyntaxError(`Repeated attribute ${match[1]} in open tag ${tagName}`) } foundAttributeNames.push(lowerName) attributes.push(readAttribute(lowerName)) } } if (!isVoid && selfClose) { throwSyntaxError('Self-closed tags for non-void elements are not allowed') } return { type: 'element', start, end: getSourcePoint(), name: tagName, isVoid, attributes, children: [] } }
javascript
function readOpenTag() { // Read tag name let start = getSourcePoint(), match = tagNameRegex.exec(source.substr(pos)) if (!match) { throwSyntaxError('Invalid open tag') } let tagName = match[0].toLowerCase(), isVoid = voidElementsRegex.test(tagName) advanceTo(pos + tagName.length) // Keep reading content let selfClose = false, attributes = [], // Used to detect repeated attributes foundAttributeNames = [] while (true) { // Match using anchored regex let match = tagOpenContentStartRegex.exec(source.substr(pos)) if (!match) { throwSyntaxError('Invalid open tag') } advanceTo(pos + match[0].length) if (match[1] === '<%-') { throwSyntaxError('EJS unescaped tags are not allowed inside open tags') } else if (match[1] === '<%=') { throwSyntaxError('EJS escaped tags are not allowed inside open tags') } else if (match[1] === '<%') { throwSyntaxError('EJS eval tags are not allowed inside open tags') } else if (match[1] === '>') { break } else if (match[1] === '/>') { selfClose = true break } else { // Attribute start let lowerName = match[1].toLowerCase() if (foundAttributeNames.indexOf(lowerName) !== -1) { throwSyntaxError(`Repeated attribute ${match[1]} in open tag ${tagName}`) } foundAttributeNames.push(lowerName) attributes.push(readAttribute(lowerName)) } } if (!isVoid && selfClose) { throwSyntaxError('Self-closed tags for non-void elements are not allowed') } return { type: 'element', start, end: getSourcePoint(), name: tagName, isVoid, attributes, children: [] } }
[ "function", "readOpenTag", "(", ")", "{", "let", "start", "=", "getSourcePoint", "(", ")", ",", "match", "=", "tagNameRegex", ".", "exec", "(", "source", ".", "substr", "(", "pos", ")", ")", "if", "(", "!", "match", ")", "{", "throwSyntaxError", "(", "'Invalid open tag'", ")", "}", "let", "tagName", "=", "match", "[", "0", "]", ".", "toLowerCase", "(", ")", ",", "isVoid", "=", "voidElementsRegex", ".", "test", "(", "tagName", ")", "advanceTo", "(", "pos", "+", "tagName", ".", "length", ")", "let", "selfClose", "=", "false", ",", "attributes", "=", "[", "]", ",", "foundAttributeNames", "=", "[", "]", "while", "(", "true", ")", "{", "let", "match", "=", "tagOpenContentStartRegex", ".", "exec", "(", "source", ".", "substr", "(", "pos", ")", ")", "if", "(", "!", "match", ")", "{", "throwSyntaxError", "(", "'Invalid open tag'", ")", "}", "advanceTo", "(", "pos", "+", "match", "[", "0", "]", ".", "length", ")", "if", "(", "match", "[", "1", "]", "===", "'<%-'", ")", "{", "throwSyntaxError", "(", "'EJS unescaped tags are not allowed inside open tags'", ")", "}", "else", "if", "(", "match", "[", "1", "]", "===", "'<%='", ")", "{", "throwSyntaxError", "(", "'EJS escaped tags are not allowed inside open tags'", ")", "}", "else", "if", "(", "match", "[", "1", "]", "===", "'<%'", ")", "{", "throwSyntaxError", "(", "'EJS eval tags are not allowed inside open tags'", ")", "}", "else", "if", "(", "match", "[", "1", "]", "===", "'>'", ")", "{", "break", "}", "else", "if", "(", "match", "[", "1", "]", "===", "'/>'", ")", "{", "selfClose", "=", "true", "break", "}", "else", "{", "let", "lowerName", "=", "match", "[", "1", "]", ".", "toLowerCase", "(", ")", "if", "(", "foundAttributeNames", ".", "indexOf", "(", "lowerName", ")", "!==", "-", "1", ")", "{", "throwSyntaxError", "(", "`", "${", "match", "[", "1", "]", "}", "${", "tagName", "}", "`", ")", "}", "foundAttributeNames", ".", "push", "(", "lowerName", ")", "attributes", ".", "push", "(", "readAttribute", "(", "lowerName", ")", ")", "}", "}", "if", "(", "!", "isVoid", "&&", "selfClose", ")", "{", "throwSyntaxError", "(", "'Self-closed tags for non-void elements are not allowed'", ")", "}", "return", "{", "type", ":", "'element'", ",", "start", ",", "end", ":", "getSourcePoint", "(", ")", ",", "name", ":", "tagName", ",", "isVoid", ",", "attributes", ",", "children", ":", "[", "]", "}", "}" ]
Read an open tag token @returns {Token}
[ "Read", "an", "open", "tag", "token" ]
cfad09dd07d4b121da130327c8221222db5f6cb4
https://github.com/sitegui/ejs-html/blob/cfad09dd07d4b121da130327c8221222db5f6cb4/lib/parse.js#L216-L275
train
sitegui/ejs-html
lib/parse.js
advanceTo
function advanceTo(newPos) { let n = newPos - pos assert(n >= 0) while (n--) { if (source[pos] === '\n') { column = 1 line++ } else { column++ } pos += 1 } }
javascript
function advanceTo(newPos) { let n = newPos - pos assert(n >= 0) while (n--) { if (source[pos] === '\n') { column = 1 line++ } else { column++ } pos += 1 } }
[ "function", "advanceTo", "(", "newPos", ")", "{", "let", "n", "=", "newPos", "-", "pos", "assert", "(", "n", ">=", "0", ")", "while", "(", "n", "--", ")", "{", "if", "(", "source", "[", "pos", "]", "===", "'\\n'", ")", "\\n", "else", "{", "column", "=", "1", "line", "++", "}", "{", "column", "++", "}", "}", "}" ]
Advance reading position, updating `pos`, `line` and `column` @param {number} newPos - must be greater or equal to current pos
[ "Advance", "reading", "position", "updating", "pos", "line", "and", "column" ]
cfad09dd07d4b121da130327c8221222db5f6cb4
https://github.com/sitegui/ejs-html/blob/cfad09dd07d4b121da130327c8221222db5f6cb4/lib/parse.js#L370-L382
train
sitegui/ejs-html
lib/parse.js
createContentToken
function createContentToken(type, start) { let end = getSourcePoint() return { type, start, end, content: source.substring(start.pos, end.pos) } }
javascript
function createContentToken(type, start) { let end = getSourcePoint() return { type, start, end, content: source.substring(start.pos, end.pos) } }
[ "function", "createContentToken", "(", "type", ",", "start", ")", "{", "let", "end", "=", "getSourcePoint", "(", ")", "return", "{", "type", ",", "start", ",", "end", ",", "content", ":", "source", ".", "substring", "(", "start", ".", "pos", ",", "end", ".", "pos", ")", "}", "}" ]
Create a simple, content-oriented token up to current position @param {string} type - one of: text, ejs-eval, ejs-escaped, ejs-raw, comment, doctype @param {SourcePoint} start @returns {Token}
[ "Create", "a", "simple", "content", "-", "oriented", "token", "up", "to", "current", "position" ]
cfad09dd07d4b121da130327c8221222db5f6cb4
https://github.com/sitegui/ejs-html/blob/cfad09dd07d4b121da130327c8221222db5f6cb4/lib/parse.js#L412-L420
train
sitegui/ejs-html
lib/parse.js
throwSyntaxError
function throwSyntaxError(message) { let curr = getSourcePoint(), snippet = getSnippet(source, curr.line, curr.line), err = new SyntaxError(`${message}\n${snippet}`) err.pos = getSourcePoint() throw err }
javascript
function throwSyntaxError(message) { let curr = getSourcePoint(), snippet = getSnippet(source, curr.line, curr.line), err = new SyntaxError(`${message}\n${snippet}`) err.pos = getSourcePoint() throw err }
[ "function", "throwSyntaxError", "(", "message", ")", "{", "let", "curr", "=", "getSourcePoint", "(", ")", ",", "snippet", "=", "getSnippet", "(", "source", ",", "curr", ".", "line", ",", "curr", ".", "line", ")", ",", "err", "=", "new", "SyntaxError", "(", "`", "${", "message", "}", "\\n", "${", "snippet", "}", "`", ")", "err", ".", "pos", "=", "getSourcePoint", "(", ")", "throw", "err", "}" ]
Throw a syntax error in the current position @param {string} message @throws {SyntaxError}
[ "Throw", "a", "syntax", "error", "in", "the", "current", "position" ]
cfad09dd07d4b121da130327c8221222db5f6cb4
https://github.com/sitegui/ejs-html/blob/cfad09dd07d4b121da130327c8221222db5f6cb4/lib/parse.js#L427-L433
train
conveyal/lonlat
index.js
fromLatFirstString
function fromLatFirstString (str) { var arr = str.split(',') return floatize({lat: arr[0], lon: arr[1]}) }
javascript
function fromLatFirstString (str) { var arr = str.split(',') return floatize({lat: arr[0], lon: arr[1]}) }
[ "function", "fromLatFirstString", "(", "str", ")", "{", "var", "arr", "=", "str", ".", "split", "(", "','", ")", "return", "floatize", "(", "{", "lat", ":", "arr", "[", "0", "]", ",", "lon", ":", "arr", "[", "1", "]", "}", ")", "}" ]
Tries to parse from a string where the latitude appears before the longitude. @memberof conveyal/lonlat @param {string} str A string in the format: `latitude,longitude` @return {lonlat.types.output} @throws {lonlat.types.InvalidCoordinateException} @example var lonlat = require('@conveyal/lonlat') var position = lonlat.fromLatFirstString('12,34') // { lon: 34, lat: 12 }
[ "Tries", "to", "parse", "from", "a", "string", "where", "the", "latitude", "appears", "before", "the", "longitude", "." ]
91240d483d302ad9f19cf6dd04d5f908357aaefa
https://github.com/conveyal/lonlat/blob/91240d483d302ad9f19cf6dd04d5f908357aaefa/index.js#L170-L173
train
conveyal/lonlat
index.js
latitudeToPixel
function latitudeToPixel (latitude, zoom) { const latRad = toRadians(latitude) return (1 - Math.log(Math.tan(latRad) + (1 / Math.cos(latRad))) / Math.PI) / 2 * zScale(zoom) }
javascript
function latitudeToPixel (latitude, zoom) { const latRad = toRadians(latitude) return (1 - Math.log(Math.tan(latRad) + (1 / Math.cos(latRad))) / Math.PI) / 2 * zScale(zoom) }
[ "function", "latitudeToPixel", "(", "latitude", ",", "zoom", ")", "{", "const", "latRad", "=", "toRadians", "(", "latitude", ")", "return", "(", "1", "-", "Math", ".", "log", "(", "Math", ".", "tan", "(", "latRad", ")", "+", "(", "1", "/", "Math", ".", "cos", "(", "latRad", ")", ")", ")", "/", "Math", ".", "PI", ")", "/", "2", "*", "zScale", "(", "zoom", ")", "}" ]
Convert a latitude to it's pixel value given a `zoom` level. @param {number} latitude @param {number} zoom @return {number} pixel @example var yPixel = lonlat.latitudeToPixel(40, 9) //= 49621.12736343896
[ "Convert", "a", "latitude", "to", "it", "s", "pixel", "value", "given", "a", "zoom", "level", "." ]
91240d483d302ad9f19cf6dd04d5f908357aaefa
https://github.com/conveyal/lonlat/blob/91240d483d302ad9f19cf6dd04d5f908357aaefa/index.js#L347-L352
train
conveyal/lonlat
index.js
pixelToLatitude
function pixelToLatitude (y, zoom) { var latRad = Math.atan(Math.sinh(Math.PI * (1 - 2 * y / zScale(zoom)))) return toDegrees(latRad) }
javascript
function pixelToLatitude (y, zoom) { var latRad = Math.atan(Math.sinh(Math.PI * (1 - 2 * y / zScale(zoom)))) return toDegrees(latRad) }
[ "function", "pixelToLatitude", "(", "y", ",", "zoom", ")", "{", "var", "latRad", "=", "Math", ".", "atan", "(", "Math", ".", "sinh", "(", "Math", ".", "PI", "*", "(", "1", "-", "2", "*", "y", "/", "zScale", "(", "zoom", ")", ")", ")", ")", "return", "toDegrees", "(", "latRad", ")", "}" ]
Convert a pixel to it's latitude value given a zoom level. @param {number} y @param {number} zoom @return {number} latitude @example var lat = lonlat.pixelToLatitude(50000, 9) //= 39.1982053488948
[ "Convert", "a", "pixel", "to", "it", "s", "latitude", "value", "given", "a", "zoom", "level", "." ]
91240d483d302ad9f19cf6dd04d5f908357aaefa
https://github.com/conveyal/lonlat/blob/91240d483d302ad9f19cf6dd04d5f908357aaefa/index.js#L407-L410
train
chad-autry/hex-grid-map-3D
src/contexts/InverseGridContext.js
function(hexDimensions, radius) { var positionArray = []; var pixelCoordinates; //For every hex, place an instance of the original mesh. The symbol fills in 3 of the 6 lines, the other 3 being shared with an adjacent hex //Make a hexagonal grid of hexagons since it is approximately circular. var u = 0; var v = 0; //For each radius positionArray.push({ y: 0, x: 0 }); for (var i = 1; i < radius + 1; i++) { //Hold u constant as the radius, add an instance for each v for (v = -i; v <= 0; v++) { pixelCoordinates = hexDimensions.getPixelCoordinates(i, v); positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x }); } //Hold u constant as negative the radius, add an instance for each v for (v = 0; v <= i; v++) { pixelCoordinates = hexDimensions.getPixelCoordinates(-i, v); positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x }); } //Hold v constant as the radius, add an instance for each u for (u = -i + 1; u <= 0; u++) { pixelCoordinates = hexDimensions.getPixelCoordinates(u, i); positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x }); } //Hold v constant as negative the radius, add an instance for each u for (u = 0; u < i; u++) { pixelCoordinates = hexDimensions.getPixelCoordinates(u, -i); positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x }); } //Hold w constant as the radius, add an instance for each u + v = -i for (u = -i + 1, v = -1; v > -i; u++, v--) { pixelCoordinates = hexDimensions.getPixelCoordinates(u, v); positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x }); } //Hold w constant as the negative radius, add an instance for each u + v = i for (u = i - 1, v = 1; v < i; u--, v++) { pixelCoordinates = hexDimensions.getPixelCoordinates(u, v); positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x }); } } return positionArray; }
javascript
function(hexDimensions, radius) { var positionArray = []; var pixelCoordinates; //For every hex, place an instance of the original mesh. The symbol fills in 3 of the 6 lines, the other 3 being shared with an adjacent hex //Make a hexagonal grid of hexagons since it is approximately circular. var u = 0; var v = 0; //For each radius positionArray.push({ y: 0, x: 0 }); for (var i = 1; i < radius + 1; i++) { //Hold u constant as the radius, add an instance for each v for (v = -i; v <= 0; v++) { pixelCoordinates = hexDimensions.getPixelCoordinates(i, v); positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x }); } //Hold u constant as negative the radius, add an instance for each v for (v = 0; v <= i; v++) { pixelCoordinates = hexDimensions.getPixelCoordinates(-i, v); positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x }); } //Hold v constant as the radius, add an instance for each u for (u = -i + 1; u <= 0; u++) { pixelCoordinates = hexDimensions.getPixelCoordinates(u, i); positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x }); } //Hold v constant as negative the radius, add an instance for each u for (u = 0; u < i; u++) { pixelCoordinates = hexDimensions.getPixelCoordinates(u, -i); positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x }); } //Hold w constant as the radius, add an instance for each u + v = -i for (u = -i + 1, v = -1; v > -i; u++, v--) { pixelCoordinates = hexDimensions.getPixelCoordinates(u, v); positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x }); } //Hold w constant as the negative radius, add an instance for each u + v = i for (u = i - 1, v = 1; v < i; u--, v++) { pixelCoordinates = hexDimensions.getPixelCoordinates(u, v); positionArray.push({ y: pixelCoordinates.y, x: pixelCoordinates.x }); } } return positionArray; }
[ "function", "(", "hexDimensions", ",", "radius", ")", "{", "var", "positionArray", "=", "[", "]", ";", "var", "pixelCoordinates", ";", "var", "u", "=", "0", ";", "var", "v", "=", "0", ";", "positionArray", ".", "push", "(", "{", "y", ":", "0", ",", "x", ":", "0", "}", ")", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "radius", "+", "1", ";", "i", "++", ")", "{", "for", "(", "v", "=", "-", "i", ";", "v", "<=", "0", ";", "v", "++", ")", "{", "pixelCoordinates", "=", "hexDimensions", ".", "getPixelCoordinates", "(", "i", ",", "v", ")", ";", "positionArray", ".", "push", "(", "{", "y", ":", "pixelCoordinates", ".", "y", ",", "x", ":", "pixelCoordinates", ".", "x", "}", ")", ";", "}", "for", "(", "v", "=", "0", ";", "v", "<=", "i", ";", "v", "++", ")", "{", "pixelCoordinates", "=", "hexDimensions", ".", "getPixelCoordinates", "(", "-", "i", ",", "v", ")", ";", "positionArray", ".", "push", "(", "{", "y", ":", "pixelCoordinates", ".", "y", ",", "x", ":", "pixelCoordinates", ".", "x", "}", ")", ";", "}", "for", "(", "u", "=", "-", "i", "+", "1", ";", "u", "<=", "0", ";", "u", "++", ")", "{", "pixelCoordinates", "=", "hexDimensions", ".", "getPixelCoordinates", "(", "u", ",", "i", ")", ";", "positionArray", ".", "push", "(", "{", "y", ":", "pixelCoordinates", ".", "y", ",", "x", ":", "pixelCoordinates", ".", "x", "}", ")", ";", "}", "for", "(", "u", "=", "0", ";", "u", "<", "i", ";", "u", "++", ")", "{", "pixelCoordinates", "=", "hexDimensions", ".", "getPixelCoordinates", "(", "u", ",", "-", "i", ")", ";", "positionArray", ".", "push", "(", "{", "y", ":", "pixelCoordinates", ".", "y", ",", "x", ":", "pixelCoordinates", ".", "x", "}", ")", ";", "}", "for", "(", "u", "=", "-", "i", "+", "1", ",", "v", "=", "-", "1", ";", "v", ">", "-", "i", ";", "u", "++", ",", "v", "--", ")", "{", "pixelCoordinates", "=", "hexDimensions", ".", "getPixelCoordinates", "(", "u", ",", "v", ")", ";", "positionArray", ".", "push", "(", "{", "y", ":", "pixelCoordinates", ".", "y", ",", "x", ":", "pixelCoordinates", ".", "x", "}", ")", ";", "}", "for", "(", "u", "=", "i", "-", "1", ",", "v", "=", "1", ";", "v", "<", "i", ";", "u", "--", ",", "v", "++", ")", "{", "pixelCoordinates", "=", "hexDimensions", ".", "getPixelCoordinates", "(", "u", ",", "v", ")", ";", "positionArray", ".", "push", "(", "{", "y", ":", "pixelCoordinates", ".", "y", ",", "x", ":", "pixelCoordinates", ".", "x", "}", ")", ";", "}", "}", "return", "positionArray", ";", "}" ]
Creates a full grid from the single mesh @private
[ "Creates", "a", "full", "grid", "from", "the", "single", "mesh" ]
4c80bcb2580b2ba573df257b40082de97e8938e8
https://github.com/chad-autry/hex-grid-map-3D/blob/4c80bcb2580b2ba573df257b40082de97e8938e8/src/contexts/InverseGridContext.js#L151-L202
train
Suor/serverless-docker-artifacts
index.js
run
function run(cmd, args, options) { if (process.env.SLS_DEBUG) console.log('Running', cmd, args.join(' ')); const stdio = process.env.SLS_DEBUG && options && options.showOutput ? ['pipe', 'inherit', 'pipe'] : 'pipe'; const ps = child_process.spawnSync(cmd, args, {encoding: 'utf-8', 'stdio': stdio}); if (ps.error) { if (ps.error.code === 'ENOENT') { throw new Error(`${cmd} not found! Please install it.`); } throw new Error(ps.error); } else if (ps.status !== 0) { throw new Error(ps.stderr); } return ps; }
javascript
function run(cmd, args, options) { if (process.env.SLS_DEBUG) console.log('Running', cmd, args.join(' ')); const stdio = process.env.SLS_DEBUG && options && options.showOutput ? ['pipe', 'inherit', 'pipe'] : 'pipe'; const ps = child_process.spawnSync(cmd, args, {encoding: 'utf-8', 'stdio': stdio}); if (ps.error) { if (ps.error.code === 'ENOENT') { throw new Error(`${cmd} not found! Please install it.`); } throw new Error(ps.error); } else if (ps.status !== 0) { throw new Error(ps.stderr); } return ps; }
[ "function", "run", "(", "cmd", ",", "args", ",", "options", ")", "{", "if", "(", "process", ".", "env", ".", "SLS_DEBUG", ")", "console", ".", "log", "(", "'Running'", ",", "cmd", ",", "args", ".", "join", "(", "' '", ")", ")", ";", "const", "stdio", "=", "process", ".", "env", ".", "SLS_DEBUG", "&&", "options", "&&", "options", ".", "showOutput", "?", "[", "'pipe'", ",", "'inherit'", ",", "'pipe'", "]", ":", "'pipe'", ";", "const", "ps", "=", "child_process", ".", "spawnSync", "(", "cmd", ",", "args", ",", "{", "encoding", ":", "'utf-8'", ",", "'stdio'", ":", "stdio", "}", ")", ";", "if", "(", "ps", ".", "error", ")", "{", "if", "(", "ps", ".", "error", ".", "code", "===", "'ENOENT'", ")", "{", "throw", "new", "Error", "(", "`", "${", "cmd", "}", "`", ")", ";", "}", "throw", "new", "Error", "(", "ps", ".", "error", ")", ";", "}", "else", "if", "(", "ps", ".", "status", "!==", "0", ")", "{", "throw", "new", "Error", "(", "ps", ".", "stderr", ")", ";", "}", "return", "ps", ";", "}" ]
Helper function to run commands
[ "Helper", "function", "to", "run", "commands" ]
4ea6edba602ec2c03ce6f0fc9c1b20c09ca35c77
https://github.com/Suor/serverless-docker-artifacts/blob/4ea6edba602ec2c03ce6f0fc9c1b20c09ca35c77/index.js#L109-L124
train
chad-autry/hex-grid-map-3D
jsdoc-template/publish.js
linkto
function linkto(parentState, longname, name) { if (!!longname && longname !== '') { return '<a ui-sref="jsdoc.' + parentState + "({anchor:'" + longname.replace('module:', '') + "'})" + '">' + name + '</a>'; } return '<a ui-sref="jsdoc.' + parentState + '">' + name + '</a>'; }
javascript
function linkto(parentState, longname, name) { if (!!longname && longname !== '') { return '<a ui-sref="jsdoc.' + parentState + "({anchor:'" + longname.replace('module:', '') + "'})" + '">' + name + '</a>'; } return '<a ui-sref="jsdoc.' + parentState + '">' + name + '</a>'; }
[ "function", "linkto", "(", "parentState", ",", "longname", ",", "name", ")", "{", "if", "(", "!", "!", "longname", "&&", "longname", "!==", "''", ")", "{", "return", "'<a ui-sref=\"jsdoc.'", "+", "parentState", "+", "\"({anchor:'\"", "+", "longname", ".", "replace", "(", "'module:'", ",", "''", ")", "+", "\"'})\"", "+", "'\">'", "+", "name", "+", "'</a>'", ";", "}", "return", "'<a ui-sref=\"jsdoc.'", "+", "parentState", "+", "'\">'", "+", "name", "+", "'</a>'", ";", "}" ]
Create links to items
[ "Create", "links", "to", "items" ]
4c80bcb2580b2ba573df257b40082de97e8938e8
https://github.com/chad-autry/hex-grid-map-3D/blob/4c80bcb2580b2ba573df257b40082de97e8938e8/jsdoc-template/publish.js#L379-L386
train
chad-autry/hex-grid-map-3D
jsdoc-template/publish.js
linkToSrc
function linkToSrc(shortPath, lineNumber) { var splitPath = shortPath.split("/"); return '<a href="{{srcroot}}' + shortPath+'">' + splitPath[splitPath.length - 1] + '</a>, <a href="{{srcroot}}' + shortPath+'#L'+lineNumber+'">' + lineNumber + '</a>'; }
javascript
function linkToSrc(shortPath, lineNumber) { var splitPath = shortPath.split("/"); return '<a href="{{srcroot}}' + shortPath+'">' + splitPath[splitPath.length - 1] + '</a>, <a href="{{srcroot}}' + shortPath+'#L'+lineNumber+'">' + lineNumber + '</a>'; }
[ "function", "linkToSrc", "(", "shortPath", ",", "lineNumber", ")", "{", "var", "splitPath", "=", "shortPath", ".", "split", "(", "\"/\"", ")", ";", "return", "'<a href=\"{{srcroot}}'", "+", "shortPath", "+", "'\">'", "+", "splitPath", "[", "splitPath", ".", "length", "-", "1", "]", "+", "'</a>, <a href=\"{{srcroot}}'", "+", "shortPath", "+", "'#L'", "+", "lineNumber", "+", "'\">'", "+", "lineNumber", "+", "'</a>'", ";", "}" ]
Create links to the src relative to the external source url Adds a link to the line number according to github's format Since JSDoc seems incapable of accept external parameters, inject a value which will be replaced in Angular
[ "Create", "links", "to", "the", "src", "relative", "to", "the", "external", "source", "url", "Adds", "a", "link", "to", "the", "line", "number", "according", "to", "github", "s", "format", "Since", "JSDoc", "seems", "incapable", "of", "accept", "external", "parameters", "inject", "a", "value", "which", "will", "be", "replaced", "in", "Angular" ]
4c80bcb2580b2ba573df257b40082de97e8938e8
https://github.com/chad-autry/hex-grid-map-3D/blob/4c80bcb2580b2ba573df257b40082de97e8938e8/jsdoc-template/publish.js#L393-L397
train
alawatthe/MathLib
build/commonjs/SVG.js
function (circle, options, redraw) { if (typeof options === "undefined") { options = {}; } if (typeof redraw === "undefined") { redraw = false; } var screen = this.screen, prop, opts, svgCircle = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); svgCircle.setAttribute('cx', circle.center[0]); svgCircle.setAttribute('cy', circle.center[1]); svgCircle.setAttribute('r', circle.radius); if (options) { svgCircle.setAttribute('stroke-width', (options.lineWidth || 4) / (screen.scale.x - screen.scale.y) + ''); opts = MathLib.SVG.convertOptions(options); for (prop in opts) { if (opts.hasOwnProperty(prop)) { svgCircle.setAttribute(prop, opts[prop]); } } } this.ctx.appendChild(svgCircle); if (!redraw) { this.stack.push({ type: 'circle', object: circle, options: options }); } return this; }
javascript
function (circle, options, redraw) { if (typeof options === "undefined") { options = {}; } if (typeof redraw === "undefined") { redraw = false; } var screen = this.screen, prop, opts, svgCircle = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); svgCircle.setAttribute('cx', circle.center[0]); svgCircle.setAttribute('cy', circle.center[1]); svgCircle.setAttribute('r', circle.radius); if (options) { svgCircle.setAttribute('stroke-width', (options.lineWidth || 4) / (screen.scale.x - screen.scale.y) + ''); opts = MathLib.SVG.convertOptions(options); for (prop in opts) { if (opts.hasOwnProperty(prop)) { svgCircle.setAttribute(prop, opts[prop]); } } } this.ctx.appendChild(svgCircle); if (!redraw) { this.stack.push({ type: 'circle', object: circle, options: options }); } return this; }
[ "function", "(", "circle", ",", "options", ",", "redraw", ")", "{", "if", "(", "typeof", "options", "===", "\"undefined\"", ")", "{", "options", "=", "{", "}", ";", "}", "if", "(", "typeof", "redraw", "===", "\"undefined\"", ")", "{", "redraw", "=", "false", ";", "}", "var", "screen", "=", "this", ".", "screen", ",", "prop", ",", "opts", ",", "svgCircle", "=", "document", ".", "createElementNS", "(", "'http://www.w3.org/2000/svg'", ",", "'circle'", ")", ";", "svgCircle", ".", "setAttribute", "(", "'cx'", ",", "circle", ".", "center", "[", "0", "]", ")", ";", "svgCircle", ".", "setAttribute", "(", "'cy'", ",", "circle", ".", "center", "[", "1", "]", ")", ";", "svgCircle", ".", "setAttribute", "(", "'r'", ",", "circle", ".", "radius", ")", ";", "if", "(", "options", ")", "{", "svgCircle", ".", "setAttribute", "(", "'stroke-width'", ",", "(", "options", ".", "lineWidth", "||", "4", ")", "/", "(", "screen", ".", "scale", ".", "x", "-", "screen", ".", "scale", ".", "y", ")", "+", "''", ")", ";", "opts", "=", "MathLib", ".", "SVG", ".", "convertOptions", "(", "options", ")", ";", "for", "(", "prop", "in", "opts", ")", "{", "if", "(", "opts", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "svgCircle", ".", "setAttribute", "(", "prop", ",", "opts", "[", "prop", "]", ")", ";", "}", "}", "}", "this", ".", "ctx", ".", "appendChild", "(", "svgCircle", ")", ";", "if", "(", "!", "redraw", ")", "{", "this", ".", "stack", ".", "push", "(", "{", "type", ":", "'circle'", ",", "object", ":", "circle", ",", "options", ":", "options", "}", ")", ";", "}", "return", "this", ";", "}" ]
Draws a circle on the screen. @param {Circle} circle The circle to be drawn @param {drawingOptions} options Optional drawing options @param {boolean} redraw Indicates if the current draw call is happening during a redraw @return {Screen} Returns the screen
[ "Draws", "a", "circle", "on", "the", "screen", "." ]
43dbd35263da672bd2ca41f93dc447b60da9bdac
https://github.com/alawatthe/MathLib/blob/43dbd35263da672bd2ca41f93dc447b60da9bdac/build/commonjs/SVG.js#L32-L62
train
wbyoung/azul
lib/relations/has_many_prefetch.js
function(instances) { var queryKey = this.foreignKey; var pks = _.map(instances, this.primaryKey); if (instances.length === 1) { pks = pks[0]; } else { queryKey += '$in'; } var where = _.object([[queryKey, pks]]); return this._relatedModel.objects.where(where); }
javascript
function(instances) { var queryKey = this.foreignKey; var pks = _.map(instances, this.primaryKey); if (instances.length === 1) { pks = pks[0]; } else { queryKey += '$in'; } var where = _.object([[queryKey, pks]]); return this._relatedModel.objects.where(where); }
[ "function", "(", "instances", ")", "{", "var", "queryKey", "=", "this", ".", "foreignKey", ";", "var", "pks", "=", "_", ".", "map", "(", "instances", ",", "this", ".", "primaryKey", ")", ";", "if", "(", "instances", ".", "length", "===", "1", ")", "{", "pks", "=", "pks", "[", "0", "]", ";", "}", "else", "{", "queryKey", "+=", "'$in'", ";", "}", "var", "where", "=", "_", ".", "object", "(", "[", "[", "queryKey", ",", "pks", "]", "]", ")", ";", "return", "this", ".", "_relatedModel", ".", "objects", ".", "where", "(", "where", ")", ";", "}" ]
Generate the prefetch query. Subclasses can override this. @method @protected @see {@link HasMany#_prefetch}
[ "Generate", "the", "prefetch", "query", "." ]
860197318f9a1ca79970b2d053351e44e810b1ef
https://github.com/wbyoung/azul/blob/860197318f9a1ca79970b2d053351e44e810b1ef/lib/relations/has_many_prefetch.js#L47-L56
train
alawatthe/MathLib
build/MathLib.js
function (options) { var convertedOptions = {}; if ('fillColor' in options) { convertedOptions.fillStyle = MathLib.colorConvert(options.fillColor); } else if ('color' in options) { convertedOptions.fillStyle = MathLib.colorConvert(options.color); } if ('font' in options) { convertedOptions.font = options.font; } if ('fontSize' in options) { convertedOptions.fontSize = options.fontSize; } if ('lineColor' in options) { convertedOptions.strokeStyle = MathLib.colorConvert(options.lineColor); } else if ('color' in options) { convertedOptions.strokeStyle = MathLib.colorConvert(options.color); } return convertedOptions; }
javascript
function (options) { var convertedOptions = {}; if ('fillColor' in options) { convertedOptions.fillStyle = MathLib.colorConvert(options.fillColor); } else if ('color' in options) { convertedOptions.fillStyle = MathLib.colorConvert(options.color); } if ('font' in options) { convertedOptions.font = options.font; } if ('fontSize' in options) { convertedOptions.fontSize = options.fontSize; } if ('lineColor' in options) { convertedOptions.strokeStyle = MathLib.colorConvert(options.lineColor); } else if ('color' in options) { convertedOptions.strokeStyle = MathLib.colorConvert(options.color); } return convertedOptions; }
[ "function", "(", "options", ")", "{", "var", "convertedOptions", "=", "{", "}", ";", "if", "(", "'fillColor'", "in", "options", ")", "{", "convertedOptions", ".", "fillStyle", "=", "MathLib", ".", "colorConvert", "(", "options", ".", "fillColor", ")", ";", "}", "else", "if", "(", "'color'", "in", "options", ")", "{", "convertedOptions", ".", "fillStyle", "=", "MathLib", ".", "colorConvert", "(", "options", ".", "color", ")", ";", "}", "if", "(", "'font'", "in", "options", ")", "{", "convertedOptions", ".", "font", "=", "options", ".", "font", ";", "}", "if", "(", "'fontSize'", "in", "options", ")", "{", "convertedOptions", ".", "fontSize", "=", "options", ".", "fontSize", ";", "}", "if", "(", "'lineColor'", "in", "options", ")", "{", "convertedOptions", ".", "strokeStyle", "=", "MathLib", ".", "colorConvert", "(", "options", ".", "lineColor", ")", ";", "}", "else", "if", "(", "'color'", "in", "options", ")", "{", "convertedOptions", ".", "strokeStyle", "=", "MathLib", ".", "colorConvert", "(", "options", ".", "color", ")", ";", "}", "return", "convertedOptions", ";", "}" ]
Converts the options to the Canvas options format @param {drawingOptions} options The drawing options @return {canvasDrawingOptions} The converted options
[ "Converts", "the", "options", "to", "the", "Canvas", "options", "format" ]
43dbd35263da672bd2ca41f93dc447b60da9bdac
https://github.com/alawatthe/MathLib/blob/43dbd35263da672bd2ca41f93dc447b60da9bdac/build/MathLib.js#L4325-L4349
train
alawatthe/MathLib
build/MathLib.js
function (line, options, redraw) { if (typeof options === "undefined") { options = {}; } if (typeof redraw === "undefined") { redraw = false; } var screen = this.screen, points, ctx = this.ctx, prop, opts; ctx.save(); ctx.lineWidth = (options.lineWidth || 4) / (screen.scale.x - screen.scale.y); // Don't try to draw the line at infinity if (line.type === 'line' && MathLib.isZero(line[0]) && MathLib.isZero(line[1])) { return this; } else { points = this.screen.getLineEndPoints(line); } // Set the drawing options if (options) { opts = MathLib.Canvas.convertOptions(options); for (prop in opts) { if (opts.hasOwnProperty(prop)) { ctx[prop] = opts[prop]; } } if ('setLineDash' in ctx) { ctx.setLineDash(('dash' in options ? options.dash : [])); } if ('lineDashOffset' in ctx) { ctx.lineDashOffset = ('dashOffset' in options ? options.dashOffset : 0); } } // Draw the line ctx.beginPath(); ctx.moveTo(points[0][0], points[0][1]); ctx.lineTo(points[1][0], points[1][1]); ctx.stroke(); ctx.closePath(); ctx.restore(); if (!redraw) { this.stack.push({ type: 'line', object: line, options: options }); } return this; }
javascript
function (line, options, redraw) { if (typeof options === "undefined") { options = {}; } if (typeof redraw === "undefined") { redraw = false; } var screen = this.screen, points, ctx = this.ctx, prop, opts; ctx.save(); ctx.lineWidth = (options.lineWidth || 4) / (screen.scale.x - screen.scale.y); // Don't try to draw the line at infinity if (line.type === 'line' && MathLib.isZero(line[0]) && MathLib.isZero(line[1])) { return this; } else { points = this.screen.getLineEndPoints(line); } // Set the drawing options if (options) { opts = MathLib.Canvas.convertOptions(options); for (prop in opts) { if (opts.hasOwnProperty(prop)) { ctx[prop] = opts[prop]; } } if ('setLineDash' in ctx) { ctx.setLineDash(('dash' in options ? options.dash : [])); } if ('lineDashOffset' in ctx) { ctx.lineDashOffset = ('dashOffset' in options ? options.dashOffset : 0); } } // Draw the line ctx.beginPath(); ctx.moveTo(points[0][0], points[0][1]); ctx.lineTo(points[1][0], points[1][1]); ctx.stroke(); ctx.closePath(); ctx.restore(); if (!redraw) { this.stack.push({ type: 'line', object: line, options: options }); } return this; }
[ "function", "(", "line", ",", "options", ",", "redraw", ")", "{", "if", "(", "typeof", "options", "===", "\"undefined\"", ")", "{", "options", "=", "{", "}", ";", "}", "if", "(", "typeof", "redraw", "===", "\"undefined\"", ")", "{", "redraw", "=", "false", ";", "}", "var", "screen", "=", "this", ".", "screen", ",", "points", ",", "ctx", "=", "this", ".", "ctx", ",", "prop", ",", "opts", ";", "ctx", ".", "save", "(", ")", ";", "ctx", ".", "lineWidth", "=", "(", "options", ".", "lineWidth", "||", "4", ")", "/", "(", "screen", ".", "scale", ".", "x", "-", "screen", ".", "scale", ".", "y", ")", ";", "if", "(", "line", ".", "type", "===", "'line'", "&&", "MathLib", ".", "isZero", "(", "line", "[", "0", "]", ")", "&&", "MathLib", ".", "isZero", "(", "line", "[", "1", "]", ")", ")", "{", "return", "this", ";", "}", "else", "{", "points", "=", "this", ".", "screen", ".", "getLineEndPoints", "(", "line", ")", ";", "}", "if", "(", "options", ")", "{", "opts", "=", "MathLib", ".", "Canvas", ".", "convertOptions", "(", "options", ")", ";", "for", "(", "prop", "in", "opts", ")", "{", "if", "(", "opts", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "ctx", "[", "prop", "]", "=", "opts", "[", "prop", "]", ";", "}", "}", "if", "(", "'setLineDash'", "in", "ctx", ")", "{", "ctx", ".", "setLineDash", "(", "(", "'dash'", "in", "options", "?", "options", ".", "dash", ":", "[", "]", ")", ")", ";", "}", "if", "(", "'lineDashOffset'", "in", "ctx", ")", "{", "ctx", ".", "lineDashOffset", "=", "(", "'dashOffset'", "in", "options", "?", "options", ".", "dashOffset", ":", "0", ")", ";", "}", "}", "ctx", ".", "beginPath", "(", ")", ";", "ctx", ".", "moveTo", "(", "points", "[", "0", "]", "[", "0", "]", ",", "points", "[", "0", "]", "[", "1", "]", ")", ";", "ctx", ".", "lineTo", "(", "points", "[", "1", "]", "[", "0", "]", ",", "points", "[", "1", "]", "[", "1", "]", ")", ";", "ctx", ".", "stroke", "(", ")", ";", "ctx", ".", "closePath", "(", ")", ";", "ctx", ".", "restore", "(", ")", ";", "if", "(", "!", "redraw", ")", "{", "this", ".", "stack", ".", "push", "(", "{", "type", ":", "'line'", ",", "object", ":", "line", ",", "options", ":", "options", "}", ")", ";", "}", "return", "this", ";", "}" ]
Draws a line on the screen. @param {Line} line The line to be drawn @param {drawingOptions} options Optional drawing options @param {boolean} redraw Indicates if the current draw call is happening during a redraw @return {Screen} Returns the screen
[ "Draws", "a", "line", "on", "the", "screen", "." ]
43dbd35263da672bd2ca41f93dc447b60da9bdac
https://github.com/alawatthe/MathLib/blob/43dbd35263da672bd2ca41f93dc447b60da9bdac/build/MathLib.js#L4358-L4407
train
alawatthe/MathLib
build/MathLib.js
function (x) { if (x.length === 2) { return new THREE.Vector2(x[0], x[1]); } else if (x.length === 3) { return new THREE.Vector3(x[0], x[1], x[2]); } }
javascript
function (x) { if (x.length === 2) { return new THREE.Vector2(x[0], x[1]); } else if (x.length === 3) { return new THREE.Vector3(x[0], x[1], x[2]); } }
[ "function", "(", "x", ")", "{", "if", "(", "x", ".", "length", "===", "2", ")", "{", "return", "new", "THREE", ".", "Vector2", "(", "x", "[", "0", "]", ",", "x", "[", "1", "]", ")", ";", "}", "else", "if", "(", "x", ".", "length", "===", "3", ")", "{", "return", "new", "THREE", ".", "Vector3", "(", "x", "[", "0", "]", ",", "x", "[", "1", "]", ",", "x", "[", "2", "]", ")", ";", "}", "}" ]
A function converting arrays to THREE.js vectors
[ "A", "function", "converting", "arrays", "to", "THREE", ".", "js", "vectors" ]
43dbd35263da672bd2ca41f93dc447b60da9bdac
https://github.com/alawatthe/MathLib/blob/43dbd35263da672bd2ca41f93dc447b60da9bdac/build/MathLib.js#L5912-L5918
train
bigeasy/udt
index.js
sooner
function sooner (property) { return function (a, b) { if (a[property][0] < b[property][0]) return true; if (a[property][0] > b[property][0]) return false; return a[property][1] < b[property][1]; } }
javascript
function sooner (property) { return function (a, b) { if (a[property][0] < b[property][0]) return true; if (a[property][0] > b[property][0]) return false; return a[property][1] < b[property][1]; } }
[ "function", "sooner", "(", "property", ")", "{", "return", "function", "(", "a", ",", "b", ")", "{", "if", "(", "a", "[", "property", "]", "[", "0", "]", "<", "b", "[", "property", "]", "[", "0", "]", ")", "return", "true", ";", "if", "(", "a", "[", "property", "]", "[", "0", "]", ">", "b", "[", "property", "]", "[", "0", "]", ")", "return", "false", ";", "return", "a", "[", "property", "]", "[", "1", "]", "<", "b", "[", "property", "]", "[", "1", "]", ";", "}", "}" ]
Comparison operator generator for high-resolution time for use with heap.
[ "Comparison", "operator", "generator", "for", "high", "-", "resolution", "time", "for", "use", "with", "heap", "." ]
54e8be61ba263a762cf7db5d4202fbd964c324f5
https://github.com/bigeasy/udt/blob/54e8be61ba263a762cf7db5d4202fbd964c324f5/index.js#L120-L126
train
bigeasy/udt
index.js
EndPoint
function EndPoint (local) { this.listeners = 0; this.dgram = dgram.createSocket('udp4'); this.dgram.on('message', EndPoint.prototype.receive.bind(this)); this.dgram.bind(local.port, local.address); this.local = this.dgram.address(); this.packet = new Buffer(2048); this.sockets = {}; }
javascript
function EndPoint (local) { this.listeners = 0; this.dgram = dgram.createSocket('udp4'); this.dgram.on('message', EndPoint.prototype.receive.bind(this)); this.dgram.bind(local.port, local.address); this.local = this.dgram.address(); this.packet = new Buffer(2048); this.sockets = {}; }
[ "function", "EndPoint", "(", "local", ")", "{", "this", ".", "listeners", "=", "0", ";", "this", ".", "dgram", "=", "dgram", ".", "createSocket", "(", "'udp4'", ")", ";", "this", ".", "dgram", ".", "on", "(", "'message'", ",", "EndPoint", ".", "prototype", ".", "receive", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "dgram", ".", "bind", "(", "local", ".", "port", ",", "local", ".", "address", ")", ";", "this", ".", "local", "=", "this", ".", "dgram", ".", "address", "(", ")", ";", "this", ".", "packet", "=", "new", "Buffer", "(", "2048", ")", ";", "this", ".", "sockets", "=", "{", "}", ";", "}" ]
Wrapper around an underlying UDP datagram socket.
[ "Wrapper", "around", "an", "underlying", "UDP", "datagram", "socket", "." ]
54e8be61ba263a762cf7db5d4202fbd964c324f5
https://github.com/bigeasy/udt/blob/54e8be61ba263a762cf7db5d4202fbd964c324f5/index.js#L221-L229
train
bigeasy/udt
index.js
lookupEndPoint
function lookupEndPoint (local) { // No interfaces bound by the desired port. Note that this would also work for // zero, which indicates an ephemeral binding, but we check for that case // explicitly before calling this function. if (!endPoints[local.port]) return null; // Read datagram socket from cache. var endPoint = endPoints[local.port][local.address]; // If no datagram exists, ensure that we'll be able to create one. This only // inspects ports that have been bound by UDT, not by other protocols, so // there is still an opportunity for error when the UDP bind is invoked. if (!endPoint) { if (endPoints[local.port][0]) { throw new Error('Already bound to all interfaces.'); } if (local.address == 0) { throw new Error('Cannot bind to all interfaces because some interfaces are already bound.'); } } // Return cached datagram socket or nothing. return endPoint; }
javascript
function lookupEndPoint (local) { // No interfaces bound by the desired port. Note that this would also work for // zero, which indicates an ephemeral binding, but we check for that case // explicitly before calling this function. if (!endPoints[local.port]) return null; // Read datagram socket from cache. var endPoint = endPoints[local.port][local.address]; // If no datagram exists, ensure that we'll be able to create one. This only // inspects ports that have been bound by UDT, not by other protocols, so // there is still an opportunity for error when the UDP bind is invoked. if (!endPoint) { if (endPoints[local.port][0]) { throw new Error('Already bound to all interfaces.'); } if (local.address == 0) { throw new Error('Cannot bind to all interfaces because some interfaces are already bound.'); } } // Return cached datagram socket or nothing. return endPoint; }
[ "function", "lookupEndPoint", "(", "local", ")", "{", "if", "(", "!", "endPoints", "[", "local", ".", "port", "]", ")", "return", "null", ";", "var", "endPoint", "=", "endPoints", "[", "local", ".", "port", "]", "[", "local", ".", "address", "]", ";", "if", "(", "!", "endPoint", ")", "{", "if", "(", "endPoints", "[", "local", ".", "port", "]", "[", "0", "]", ")", "{", "throw", "new", "Error", "(", "'Already bound to all interfaces.'", ")", ";", "}", "if", "(", "local", ".", "address", "==", "0", ")", "{", "throw", "new", "Error", "(", "'Cannot bind to all interfaces because some interfaces are already bound.'", ")", ";", "}", "}", "return", "endPoint", ";", "}" ]
Look up an UDP datagram socket in the cache of bound UDP datagram sockets by the user specified port and address.
[ "Look", "up", "an", "UDP", "datagram", "socket", "in", "the", "cache", "of", "bound", "UDP", "datagram", "sockets", "by", "the", "user", "specified", "port", "and", "address", "." ]
54e8be61ba263a762cf7db5d4202fbd964c324f5
https://github.com/bigeasy/udt/blob/54e8be61ba263a762cf7db5d4202fbd964c324f5/index.js#L571-L594
train
bigeasy/udt
index.js
peerResolved
function peerResolved (ip, addressType) { // Possible cancelation during DNS lookup. if (!socket._connecting) return; socket._peer = { address: ip || '127.0.0.1', port: options.port }; // Generate random bytes used to set randomized socket properties. // `crypto.randomBytes` calls OpenSSL `RAND_bytes` to generate the bytes. // // * [RAND_bytes](http://www.openssl.org/docs/crypto/RAND_bytes.html). // * [node_crypto.cc](https://github.com/joyent/node/blob/v0.8/src/node_crypto.cc#L4517) crypto.randomBytes(4, valid(randomzied)); }
javascript
function peerResolved (ip, addressType) { // Possible cancelation during DNS lookup. if (!socket._connecting) return; socket._peer = { address: ip || '127.0.0.1', port: options.port }; // Generate random bytes used to set randomized socket properties. // `crypto.randomBytes` calls OpenSSL `RAND_bytes` to generate the bytes. // // * [RAND_bytes](http://www.openssl.org/docs/crypto/RAND_bytes.html). // * [node_crypto.cc](https://github.com/joyent/node/blob/v0.8/src/node_crypto.cc#L4517) crypto.randomBytes(4, valid(randomzied)); }
[ "function", "peerResolved", "(", "ip", ",", "addressType", ")", "{", "if", "(", "!", "socket", ".", "_connecting", ")", "return", ";", "socket", ".", "_peer", "=", "{", "address", ":", "ip", "||", "'127.0.0.1'", ",", "port", ":", "options", ".", "port", "}", ";", "crypto", ".", "randomBytes", "(", "4", ",", "valid", "(", "randomzied", ")", ")", ";", "}" ]
Record the DNS resolved IP address.
[ "Record", "the", "DNS", "resolved", "IP", "address", "." ]
54e8be61ba263a762cf7db5d4202fbd964c324f5
https://github.com/bigeasy/udt/blob/54e8be61ba263a762cf7db5d4202fbd964c324f5/index.js#L675-L687
train
bigeasy/udt
index.js
randomzied
function randomzied (buffer) { // Randomly generated randomness. socket._sequence = buffer.readUInt32BE(0) % MAX_SEQ_NO; // The end point sends a packet on our behalf. socket._endPoint.shakeHands(socket); }
javascript
function randomzied (buffer) { // Randomly generated randomness. socket._sequence = buffer.readUInt32BE(0) % MAX_SEQ_NO; // The end point sends a packet on our behalf. socket._endPoint.shakeHands(socket); }
[ "function", "randomzied", "(", "buffer", ")", "{", "socket", ".", "_sequence", "=", "buffer", ".", "readUInt32BE", "(", "0", ")", "%", "MAX_SEQ_NO", ";", "socket", ".", "_endPoint", ".", "shakeHands", "(", "socket", ")", ";", "}" ]
Initialize the randomized socket properies.
[ "Initialize", "the", "randomized", "socket", "properies", "." ]
54e8be61ba263a762cf7db5d4202fbd964c324f5
https://github.com/bigeasy/udt/blob/54e8be61ba263a762cf7db5d4202fbd964c324f5/index.js#L690-L696
train
fat/haunt
examples/comment-on-diff.js
findOnLine
function findOnLine(find, patch, cb) { if (find.test(patch)) { var lineNum = 0 patch.split('\n').forEach(function(line) { var range = /\@\@ \-\d+,\d+ \+(\d+),\d+ \@\@/g.exec(line) if (range) { lineNum = Number(range[1]) - 1 } else if (line.substr(0, 1) !== '-') { lineNum++ } if (find.test(line)) { return cb(null, lineNum) } }) } }
javascript
function findOnLine(find, patch, cb) { if (find.test(patch)) { var lineNum = 0 patch.split('\n').forEach(function(line) { var range = /\@\@ \-\d+,\d+ \+(\d+),\d+ \@\@/g.exec(line) if (range) { lineNum = Number(range[1]) - 1 } else if (line.substr(0, 1) !== '-') { lineNum++ } if (find.test(line)) { return cb(null, lineNum) } }) } }
[ "function", "findOnLine", "(", "find", ",", "patch", ",", "cb", ")", "{", "if", "(", "find", ".", "test", "(", "patch", ")", ")", "{", "var", "lineNum", "=", "0", "patch", ".", "split", "(", "'\\n'", ")", ".", "\\n", "forEach", "}", "}" ]
find stuff in a diff and return the line number
[ "find", "stuff", "in", "a", "diff", "and", "return", "the", "line", "number" ]
e7a0f30032f0afec56652dc9ded06b29f0d61509
https://github.com/fat/haunt/blob/e7a0f30032f0afec56652dc9ded06b29f0d61509/examples/comment-on-diff.js#L28-L43
train
lithiumtech/karma-threshold-reporter
istanbul-utils.js
addDerivedInfoForFile
function addDerivedInfoForFile(fileCoverage) { var statementMap = fileCoverage.statementMap, statements = fileCoverage.s, lineMap; if (!fileCoverage.l) { fileCoverage.l = lineMap = {}; Object.keys(statements).forEach(function (st) { var line = statementMap[st].start.line, count = statements[st], prevVal = lineMap[line]; if (count === 0 && statementMap[st].skip) { count = 1; } if (typeof prevVal === 'undefined' || prevVal < count) { lineMap[line] = count; } }); } }
javascript
function addDerivedInfoForFile(fileCoverage) { var statementMap = fileCoverage.statementMap, statements = fileCoverage.s, lineMap; if (!fileCoverage.l) { fileCoverage.l = lineMap = {}; Object.keys(statements).forEach(function (st) { var line = statementMap[st].start.line, count = statements[st], prevVal = lineMap[line]; if (count === 0 && statementMap[st].skip) { count = 1; } if (typeof prevVal === 'undefined' || prevVal < count) { lineMap[line] = count; } }); } }
[ "function", "addDerivedInfoForFile", "(", "fileCoverage", ")", "{", "var", "statementMap", "=", "fileCoverage", ".", "statementMap", ",", "statements", "=", "fileCoverage", ".", "s", ",", "lineMap", ";", "if", "(", "!", "fileCoverage", ".", "l", ")", "{", "fileCoverage", ".", "l", "=", "lineMap", "=", "{", "}", ";", "Object", ".", "keys", "(", "statements", ")", ".", "forEach", "(", "function", "(", "st", ")", "{", "var", "line", "=", "statementMap", "[", "st", "]", ".", "start", ".", "line", ",", "count", "=", "statements", "[", "st", "]", ",", "prevVal", "=", "lineMap", "[", "line", "]", ";", "if", "(", "count", "===", "0", "&&", "statementMap", "[", "st", "]", ".", "skip", ")", "{", "count", "=", "1", ";", "}", "if", "(", "typeof", "prevVal", "===", "'undefined'", "||", "prevVal", "<", "count", ")", "{", "lineMap", "[", "line", "]", "=", "count", ";", "}", "}", ")", ";", "}", "}" ]
adds line coverage information to a file coverage object, reverse-engineering it from statement coverage. The object passed in is updated in place. Note that if line coverage information is already present in the object, it is not recomputed. @method addDerivedInfoForFile @static @param {Object} fileCoverage the coverage object for a single file
[ "adds", "line", "coverage", "information", "to", "a", "file", "coverage", "object", "reverse", "-", "engineering", "it", "from", "statement", "coverage", ".", "The", "object", "passed", "in", "is", "updated", "in", "place", "." ]
fe78c5227819ed1c58eeb5f6b776b64338ab2525
https://github.com/lithiumtech/karma-threshold-reporter/blob/fe78c5227819ed1c58eeb5f6b776b64338ab2525/istanbul-utils.js#L50-L67
train
lithiumtech/karma-threshold-reporter
istanbul-utils.js
addDerivedInfo
function addDerivedInfo(coverage) { Object.keys(coverage).forEach(function (k) { addDerivedInfoForFile(coverage[k]); }); }
javascript
function addDerivedInfo(coverage) { Object.keys(coverage).forEach(function (k) { addDerivedInfoForFile(coverage[k]); }); }
[ "function", "addDerivedInfo", "(", "coverage", ")", "{", "Object", ".", "keys", "(", "coverage", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "addDerivedInfoForFile", "(", "coverage", "[", "k", "]", ")", ";", "}", ")", ";", "}" ]
adds line coverage information to all file coverage objects. @method addDerivedInfo @static @param {Object} coverage the coverage object
[ "adds", "line", "coverage", "information", "to", "all", "file", "coverage", "objects", "." ]
fe78c5227819ed1c58eeb5f6b776b64338ab2525
https://github.com/lithiumtech/karma-threshold-reporter/blob/fe78c5227819ed1c58eeb5f6b776b64338ab2525/istanbul-utils.js#L75-L79
train
lithiumtech/karma-threshold-reporter
istanbul-utils.js
removeDerivedInfo
function removeDerivedInfo(coverage) { Object.keys(coverage).forEach(function (k) { delete coverage[k].l; }); }
javascript
function removeDerivedInfo(coverage) { Object.keys(coverage).forEach(function (k) { delete coverage[k].l; }); }
[ "function", "removeDerivedInfo", "(", "coverage", ")", "{", "Object", ".", "keys", "(", "coverage", ")", ".", "forEach", "(", "function", "(", "k", ")", "{", "delete", "coverage", "[", "k", "]", ".", "l", ";", "}", ")", ";", "}" ]
removes line coverage information from all file coverage objects @method removeDerivedInfo @static @param {Object} coverage the coverage object
[ "removes", "line", "coverage", "information", "from", "all", "file", "coverage", "objects" ]
fe78c5227819ed1c58eeb5f6b776b64338ab2525
https://github.com/lithiumtech/karma-threshold-reporter/blob/fe78c5227819ed1c58eeb5f6b776b64338ab2525/istanbul-utils.js#L86-L90
train
lithiumtech/karma-threshold-reporter
istanbul-utils.js
mergeSummaryObjects
function mergeSummaryObjects() { var ret = blankSummary(), args = Array.prototype.slice.call(arguments), keys = ['lines', 'statements', 'branches', 'functions'], increment = function (obj) { if (obj) { keys.forEach(function (key) { ret[key].total += obj[key].total; ret[key].covered += obj[key].covered; ret[key].skipped += obj[key].skipped; }); } }; args.forEach(function (arg) { increment(arg); }); keys.forEach(function (key) { ret[key].pct = percent(ret[key].covered, ret[key].total); }); return ret; }
javascript
function mergeSummaryObjects() { var ret = blankSummary(), args = Array.prototype.slice.call(arguments), keys = ['lines', 'statements', 'branches', 'functions'], increment = function (obj) { if (obj) { keys.forEach(function (key) { ret[key].total += obj[key].total; ret[key].covered += obj[key].covered; ret[key].skipped += obj[key].skipped; }); } }; args.forEach(function (arg) { increment(arg); }); keys.forEach(function (key) { ret[key].pct = percent(ret[key].covered, ret[key].total); }); return ret; }
[ "function", "mergeSummaryObjects", "(", ")", "{", "var", "ret", "=", "blankSummary", "(", ")", ",", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ",", "keys", "=", "[", "'lines'", ",", "'statements'", ",", "'branches'", ",", "'functions'", "]", ",", "increment", "=", "function", "(", "obj", ")", "{", "if", "(", "obj", ")", "{", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "ret", "[", "key", "]", ".", "total", "+=", "obj", "[", "key", "]", ".", "total", ";", "ret", "[", "key", "]", ".", "covered", "+=", "obj", "[", "key", "]", ".", "covered", ";", "ret", "[", "key", "]", ".", "skipped", "+=", "obj", "[", "key", "]", ".", "skipped", ";", "}", ")", ";", "}", "}", ";", "args", ".", "forEach", "(", "function", "(", "arg", ")", "{", "increment", "(", "arg", ")", ";", "}", ")", ";", "keys", ".", "forEach", "(", "function", "(", "key", ")", "{", "ret", "[", "key", "]", ".", "pct", "=", "percent", "(", "ret", "[", "key", "]", ".", "covered", ",", "ret", "[", "key", "]", ".", "total", ")", ";", "}", ")", ";", "return", "ret", ";", "}" ]
merges multiple summary metrics objects by summing up the `totals` and `covered` fields and recomputing the percentages. This function is generic and can accept any number of arguments. @method mergeSummaryObjects @static @param {Object} summary... multiple summary metrics objects @return {Object} the merged summary metrics
[ "merges", "multiple", "summary", "metrics", "objects", "by", "summing", "up", "the", "totals", "and", "covered", "fields", "and", "recomputing", "the", "percentages", ".", "This", "function", "is", "generic", "and", "can", "accept", "any", "number", "of", "arguments", "." ]
fe78c5227819ed1c58eeb5f6b776b64338ab2525
https://github.com/lithiumtech/karma-threshold-reporter/blob/fe78c5227819ed1c58eeb5f6b776b64338ab2525/istanbul-utils.js#L262-L283
train