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
Sami-Radi/express-vhosts-autoloader
index.js
function (expressServer, settings) { return new Promise((resolve, reject) => { autoloader.run(expressServer, settings).then((success) => { resolve(success); }, (error) => { reject(error); }); }); }
javascript
function (expressServer, settings) { return new Promise((resolve, reject) => { autoloader.run(expressServer, settings).then((success) => { resolve(success); }, (error) => { reject(error); }); }); }
[ "function", "(", "expressServer", ",", "settings", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "autoloader", ".", "run", "(", "expressServer", ",", "settings", ")", ".", "then", "(", "(", "success", ")", "=>", "{", "resolve", "(", "success", ")", ";", "}", ",", "(", "error", ")", "=>", "{", "reject", "(", "error", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Create a new autoloader function
[ "Create", "a", "new", "autoloader", "function" ]
002ba42442b8faf3ae955492b08c0e8c6cea1d6c
https://github.com/Sami-Radi/express-vhosts-autoloader/blob/002ba42442b8faf3ae955492b08c0e8c6cea1d6c/index.js#L351-L359
train
mangonel/mangonel
src/helpers/execute.js
execute
function execute (str, { cwd }) { // command = replace(command, options); // command = prepend(command, options); let args = str.split(' ') const command = args.shift() args = [args.join(' ')] const subprocess = spawn(command, args, { detached: true, stdio: 'ignore', cwd }) subprocess.unref() return subprocess.pid }
javascript
function execute (str, { cwd }) { // command = replace(command, options); // command = prepend(command, options); let args = str.split(' ') const command = args.shift() args = [args.join(' ')] const subprocess = spawn(command, args, { detached: true, stdio: 'ignore', cwd }) subprocess.unref() return subprocess.pid }
[ "function", "execute", "(", "str", ",", "{", "cwd", "}", ")", "{", "let", "args", "=", "str", ".", "split", "(", "' '", ")", "const", "command", "=", "args", ".", "shift", "(", ")", "args", "=", "[", "args", ".", "join", "(", "' '", ")", "]", "const", "subprocess", "=", "spawn", "(", "command", ",", "args", ",", "{", "detached", ":", "true", ",", "stdio", ":", "'ignore'", ",", "cwd", "}", ")", "subprocess", ".", "unref", "(", ")", "return", "subprocess", ".", "pid", "}" ]
Execute an application. @constructor
[ "Execute", "an", "application", "." ]
f41ec456dca21326750cde5bd66bce948060beb8
https://github.com/mangonel/mangonel/blob/f41ec456dca21326750cde5bd66bce948060beb8/src/helpers/execute.js#L8-L25
train
InfinniPlatform/InfinniUI
app/actions/addAction/addAction.js
function() { var editDataSource = this.getProperty( 'editDataSource' ); var destinationDataSource = this.getProperty( 'destinationDataSource' ); var destinationProperty = this.getProperty( 'destinationProperty' ) || ''; if( !destinationDataSource ) { return; } if( this._isObjectDataSource( editDataSource ) ) { var newItem = editDataSource.getSelectedItem(); if( this._isRootElementPath( destinationProperty ) ) { destinationDataSource._includeItemToModifiedSet( newItem ); destinationDataSource.saveItem( newItem, function() { destinationDataSource.updateItems(); } ); } else { var items = destinationDataSource.getProperty( destinationProperty ) || []; items = _.clone( items ); items.push( newItem ); destinationDataSource.setProperty( destinationProperty, items ); } } else { destinationDataSource.updateItems(); } }
javascript
function() { var editDataSource = this.getProperty( 'editDataSource' ); var destinationDataSource = this.getProperty( 'destinationDataSource' ); var destinationProperty = this.getProperty( 'destinationProperty' ) || ''; if( !destinationDataSource ) { return; } if( this._isObjectDataSource( editDataSource ) ) { var newItem = editDataSource.getSelectedItem(); if( this._isRootElementPath( destinationProperty ) ) { destinationDataSource._includeItemToModifiedSet( newItem ); destinationDataSource.saveItem( newItem, function() { destinationDataSource.updateItems(); } ); } else { var items = destinationDataSource.getProperty( destinationProperty ) || []; items = _.clone( items ); items.push( newItem ); destinationDataSource.setProperty( destinationProperty, items ); } } else { destinationDataSource.updateItems(); } }
[ "function", "(", ")", "{", "var", "editDataSource", "=", "this", ".", "getProperty", "(", "'editDataSource'", ")", ";", "var", "destinationDataSource", "=", "this", ".", "getProperty", "(", "'destinationDataSource'", ")", ";", "var", "destinationProperty", "=", "this", ".", "getProperty", "(", "'destinationProperty'", ")", "||", "''", ";", "if", "(", "!", "destinationDataSource", ")", "{", "return", ";", "}", "if", "(", "this", ".", "_isObjectDataSource", "(", "editDataSource", ")", ")", "{", "var", "newItem", "=", "editDataSource", ".", "getSelectedItem", "(", ")", ";", "if", "(", "this", ".", "_isRootElementPath", "(", "destinationProperty", ")", ")", "{", "destinationDataSource", ".", "_includeItemToModifiedSet", "(", "newItem", ")", ";", "destinationDataSource", ".", "saveItem", "(", "newItem", ",", "function", "(", ")", "{", "destinationDataSource", ".", "updateItems", "(", ")", ";", "}", ")", ";", "}", "else", "{", "var", "items", "=", "destinationDataSource", ".", "getProperty", "(", "destinationProperty", ")", "||", "[", "]", ";", "items", "=", "_", ".", "clone", "(", "items", ")", ";", "items", ".", "push", "(", "newItem", ")", ";", "destinationDataSource", ".", "setProperty", "(", "destinationProperty", ",", "items", ")", ";", "}", "}", "else", "{", "destinationDataSource", ".", "updateItems", "(", ")", ";", "}", "}" ]
Save item in destination data source
[ "Save", "item", "in", "destination", "data", "source" ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/app/actions/addAction/addAction.js#L32-L60
train
B2F/Succss
succss.js
function(capture) { // If compareTo{Page|Viewport} option is set, gets the filepath corresponding // to the capture index (page, capture, viewport): if (options.compareToViewport || options.compareToPage) { var pageReference = options.compareToPage || capture.page.name; var viewportReference = options.compareToViewport || capture.viewport.name; return createCaptureState(pageReference, capture.name, viewportReference).filePath; } else { return capture.filePath; } }
javascript
function(capture) { // If compareTo{Page|Viewport} option is set, gets the filepath corresponding // to the capture index (page, capture, viewport): if (options.compareToViewport || options.compareToPage) { var pageReference = options.compareToPage || capture.page.name; var viewportReference = options.compareToViewport || capture.viewport.name; return createCaptureState(pageReference, capture.name, viewportReference).filePath; } else { return capture.filePath; } }
[ "function", "(", "capture", ")", "{", "if", "(", "options", ".", "compareToViewport", "||", "options", ".", "compareToPage", ")", "{", "var", "pageReference", "=", "options", ".", "compareToPage", "||", "capture", ".", "page", ".", "name", ";", "var", "viewportReference", "=", "options", ".", "compareToViewport", "||", "capture", ".", "viewport", ".", "name", ";", "return", "createCaptureState", "(", "pageReference", ",", "capture", ".", "name", ",", "viewportReference", ")", ".", "filePath", ";", "}", "else", "{", "return", "capture", ".", "filePath", ";", "}", "}" ]
Returns a filepath used as image reference. @param {Object} capture state @returns {String} base image filepath
[ "Returns", "a", "filepath", "used", "as", "image", "reference", "." ]
1c25c97e81a11579effabec29552da3bb6d55d59
https://github.com/B2F/Succss/blob/1c25c97e81a11579effabec29552da3bb6d55d59/succss.js#L277-L288
train
JS-MF/jsmf-core
src/Class.js
Class
function Class(name, superClasses, attributes, references, flexible) { /** The generic class instances Class * @constructor * @param {Object} attr The initial values of the instance */ function ClassInstance(attr) { Object.defineProperties(this, { __jsmf__: {value: elementMeta(ClassInstance)} }) createAttributes(this, ClassInstance) createReferences(this, ClassInstance) _.forEach(attr, (v,k) => {this[k] = v}) } Object.defineProperties(ClassInstance.prototype, { conformsTo: {value: function () { return conformsTo(this) }, enumerable: false}, getAssociated : {value: getAssociated, enumerable: false} }) superClasses = superClasses || [] superClasses = _.isArray(superClasses) ? superClasses : [superClasses] Object.assign(ClassInstance, {__name: name, superClasses, attributes: {}, references: {}}) ClassInstance.errorCallback = flexible ? onError.silent : onError.throw Object.defineProperty(ClassInstance, '__jsmf__', {value: classMeta()}) populateClassFunction(ClassInstance) if (attributes !== undefined) { ClassInstance.addAttributes(attributes)} if (references !== undefined) { ClassInstance.addReferences(references)} return ClassInstance }
javascript
function Class(name, superClasses, attributes, references, flexible) { /** The generic class instances Class * @constructor * @param {Object} attr The initial values of the instance */ function ClassInstance(attr) { Object.defineProperties(this, { __jsmf__: {value: elementMeta(ClassInstance)} }) createAttributes(this, ClassInstance) createReferences(this, ClassInstance) _.forEach(attr, (v,k) => {this[k] = v}) } Object.defineProperties(ClassInstance.prototype, { conformsTo: {value: function () { return conformsTo(this) }, enumerable: false}, getAssociated : {value: getAssociated, enumerable: false} }) superClasses = superClasses || [] superClasses = _.isArray(superClasses) ? superClasses : [superClasses] Object.assign(ClassInstance, {__name: name, superClasses, attributes: {}, references: {}}) ClassInstance.errorCallback = flexible ? onError.silent : onError.throw Object.defineProperty(ClassInstance, '__jsmf__', {value: classMeta()}) populateClassFunction(ClassInstance) if (attributes !== undefined) { ClassInstance.addAttributes(attributes)} if (references !== undefined) { ClassInstance.addReferences(references)} return ClassInstance }
[ "function", "Class", "(", "name", ",", "superClasses", ",", "attributes", ",", "references", ",", "flexible", ")", "{", "function", "ClassInstance", "(", "attr", ")", "{", "Object", ".", "defineProperties", "(", "this", ",", "{", "__jsmf__", ":", "{", "value", ":", "elementMeta", "(", "ClassInstance", ")", "}", "}", ")", "createAttributes", "(", "this", ",", "ClassInstance", ")", "createReferences", "(", "this", ",", "ClassInstance", ")", "_", ".", "forEach", "(", "attr", ",", "(", "v", ",", "k", ")", "=>", "{", "this", "[", "k", "]", "=", "v", "}", ")", "}", "Object", ".", "defineProperties", "(", "ClassInstance", ".", "prototype", ",", "{", "conformsTo", ":", "{", "value", ":", "function", "(", ")", "{", "return", "conformsTo", "(", "this", ")", "}", ",", "enumerable", ":", "false", "}", ",", "getAssociated", ":", "{", "value", ":", "getAssociated", ",", "enumerable", ":", "false", "}", "}", ")", "superClasses", "=", "superClasses", "||", "[", "]", "superClasses", "=", "_", ".", "isArray", "(", "superClasses", ")", "?", "superClasses", ":", "[", "superClasses", "]", "Object", ".", "assign", "(", "ClassInstance", ",", "{", "__name", ":", "name", ",", "superClasses", ",", "attributes", ":", "{", "}", ",", "references", ":", "{", "}", "}", ")", "ClassInstance", ".", "errorCallback", "=", "flexible", "?", "onError", ".", "silent", ":", "onError", ".", "throw", "Object", ".", "defineProperty", "(", "ClassInstance", ",", "'__jsmf__'", ",", "{", "value", ":", "classMeta", "(", ")", "}", ")", "populateClassFunction", "(", "ClassInstance", ")", "if", "(", "attributes", "!==", "undefined", ")", "{", "ClassInstance", ".", "addAttributes", "(", "attributes", ")", "}", "if", "(", "references", "!==", "undefined", ")", "{", "ClassInstance", ".", "addReferences", "(", "references", ")", "}", "return", "ClassInstance", "}" ]
Creation of a JSMF Class. The attributes are given in a key value manner: the key is the name of the attribute, the valu its type. The references are also given in a key / value way. The name of the references are the keys, the value can has the following attrivutes: - type: The target type of the reference - cardinality: the cardinality of the reference - opposite: the name of the opposite reference - oppositeCardinality: the cardinality of the opposite reference - associated: the type of the associated data. @constructor @param {string} name - Name of the class @param {Class[]} superClasses - The superclasses of the current class @param {Object} attributes - the attributes of the class. @param {Object} attributes - the references of the class. @property {string} __name the name of the class @property {Class[]} superClasses - the superclasses of this JSMF class @property {Object[]} attributes - the attributes of the class @property {Object[]} references - the references of the class @returns {Class~ClassInstance}
[ "Creation", "of", "a", "JSMF", "Class", "." ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Class.js#L62-L90
train
JS-MF/jsmf-core
src/Class.js
ClassInstance
function ClassInstance(attr) { Object.defineProperties(this, { __jsmf__: {value: elementMeta(ClassInstance)} }) createAttributes(this, ClassInstance) createReferences(this, ClassInstance) _.forEach(attr, (v,k) => {this[k] = v}) }
javascript
function ClassInstance(attr) { Object.defineProperties(this, { __jsmf__: {value: elementMeta(ClassInstance)} }) createAttributes(this, ClassInstance) createReferences(this, ClassInstance) _.forEach(attr, (v,k) => {this[k] = v}) }
[ "function", "ClassInstance", "(", "attr", ")", "{", "Object", ".", "defineProperties", "(", "this", ",", "{", "__jsmf__", ":", "{", "value", ":", "elementMeta", "(", "ClassInstance", ")", "}", "}", ")", "createAttributes", "(", "this", ",", "ClassInstance", ")", "createReferences", "(", "this", ",", "ClassInstance", ")", "_", ".", "forEach", "(", "attr", ",", "(", "v", ",", "k", ")", "=>", "{", "this", "[", "k", "]", "=", "v", "}", ")", "}" ]
The generic class instances Class @constructor @param {Object} attr The initial values of the instance
[ "The", "generic", "class", "instances", "Class" ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Class.js#L67-L74
train
JS-MF/jsmf-core
src/Class.js
getInheritanceChain
function getInheritanceChain() { return _(this.superClasses) .reverse() .reduce((acc, v) => v.getInheritanceChain().concat(acc), [this]) }
javascript
function getInheritanceChain() { return _(this.superClasses) .reverse() .reduce((acc, v) => v.getInheritanceChain().concat(acc), [this]) }
[ "function", "getInheritanceChain", "(", ")", "{", "return", "_", "(", "this", ".", "superClasses", ")", ".", "reverse", "(", ")", ".", "reduce", "(", "(", "acc", ",", "v", ")", "=>", "v", ".", "getInheritanceChain", "(", ")", ".", "concat", "(", "acc", ")", ",", "[", "this", "]", ")", "}" ]
Returns the InheritanceChain of this class @method @memberof Class~ClassInstance
[ "Returns", "the", "InheritanceChain", "of", "this", "class" ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Class.js#L106-L110
train
JS-MF/jsmf-core
src/Class.js
getAllReferences
function getAllReferences() { return _.reduce( this.getInheritanceChain(), (acc, cls) => _.reduce(cls.references, (acc2, v, k) => {acc2[k] = v; return acc2}, acc), {}) }
javascript
function getAllReferences() { return _.reduce( this.getInheritanceChain(), (acc, cls) => _.reduce(cls.references, (acc2, v, k) => {acc2[k] = v; return acc2}, acc), {}) }
[ "function", "getAllReferences", "(", ")", "{", "return", "_", ".", "reduce", "(", "this", ".", "getInheritanceChain", "(", ")", ",", "(", "acc", ",", "cls", ")", "=>", "_", ".", "reduce", "(", "cls", ".", "references", ",", "(", "acc2", ",", "v", ",", "k", ")", "=>", "{", "acc2", "[", "k", "]", "=", "v", ";", "return", "acc2", "}", ",", "acc", ")", ",", "{", "}", ")", "}" ]
Returns the own and inherited references of this class @method @memberof Class~ClassInstance
[ "Returns", "the", "own", "and", "inherited", "references", "of", "this", "class" ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Class.js#L117-L122
train
JS-MF/jsmf-core
src/Class.js
getAllAttributes
function getAllAttributes() { return _.reduce( this.getInheritanceChain(), (acc, cls) => _.reduce(cls.attributes, (acc2, v, k) => {acc2[k] = v; return acc2}, acc), {}) }
javascript
function getAllAttributes() { return _.reduce( this.getInheritanceChain(), (acc, cls) => _.reduce(cls.attributes, (acc2, v, k) => {acc2[k] = v; return acc2}, acc), {}) }
[ "function", "getAllAttributes", "(", ")", "{", "return", "_", ".", "reduce", "(", "this", ".", "getInheritanceChain", "(", ")", ",", "(", "acc", ",", "cls", ")", "=>", "_", ".", "reduce", "(", "cls", ".", "attributes", ",", "(", "acc2", ",", "v", ",", "k", ")", "=>", "{", "acc2", "[", "k", "]", "=", "v", ";", "return", "acc2", "}", ",", "acc", ")", ",", "{", "}", ")", "}" ]
Returns the own and inherited attributes of this class @method @memberof Class~ClassInstance
[ "Returns", "the", "own", "and", "inherited", "attributes", "of", "this", "class" ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Class.js#L129-L134
train
JS-MF/jsmf-core
src/Class.js
getAssociated
function getAssociated(name) { const path = ['__jsmf__', 'associated'] if (name !== undefined) { path.push(name) } return _.get(this, path) }
javascript
function getAssociated(name) { const path = ['__jsmf__', 'associated'] if (name !== undefined) { path.push(name) } return _.get(this, path) }
[ "function", "getAssociated", "(", "name", ")", "{", "const", "path", "=", "[", "'__jsmf__'", ",", "'associated'", "]", "if", "(", "name", "!==", "undefined", ")", "{", "path", ".", "push", "(", "name", ")", "}", "return", "_", ".", "get", "(", "this", ",", "path", ")", "}" ]
Returns the associated data of a reference or of all the references of an object @method @memberof Class~ClassInstance @param {string} name - The name of the reference to explore if undefined, all the references are returned
[ "Returns", "the", "associated", "data", "of", "a", "reference", "or", "of", "all", "the", "references", "of", "an", "object" ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Class.js#L142-L148
train
JS-MF/jsmf-core
src/Class.js
addReferences
function addReferences(descriptor) { _.forEach(descriptor, (desc, k) => this.addReference( k, desc.target || desc.type, desc.cardinality, desc.opposite, desc.oppositeCardinality, desc.associated, desc.errorCallback, desc.oppositeErrorCallback) ) }
javascript
function addReferences(descriptor) { _.forEach(descriptor, (desc, k) => this.addReference( k, desc.target || desc.type, desc.cardinality, desc.opposite, desc.oppositeCardinality, desc.associated, desc.errorCallback, desc.oppositeErrorCallback) ) }
[ "function", "addReferences", "(", "descriptor", ")", "{", "_", ".", "forEach", "(", "descriptor", ",", "(", "desc", ",", "k", ")", "=>", "this", ".", "addReference", "(", "k", ",", "desc", ".", "target", "||", "desc", ".", "type", ",", "desc", ".", "cardinality", ",", "desc", ".", "opposite", ",", "desc", ".", "oppositeCardinality", ",", "desc", ".", "associated", ",", "desc", ".", "errorCallback", ",", "desc", ".", "oppositeErrorCallback", ")", ")", "}" ]
Add several references to the Class @method @memberof Class~ClassInstance @param {Object} descriptor - The definition of the attributes, the keys are the names of the attribute to create. The values contains the description of the attribute. See {@link Class~ClassInstance#addAttribute} parameters name for the supported property name.
[ "Add", "several", "references", "to", "the", "Class" ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Class.js#L160-L172
train
JS-MF/jsmf-core
src/Class.js
addReference
function addReference(name, target, sourceCardinality, opposite, oppositeCardinality, associated, errorCallback, oppositeErrorCallback) { this.references[name] = { type: target || Type.JSMFAny , cardinality: Cardinality.check(sourceCardinality) } if (opposite !== undefined) { this.references[name].opposite = opposite target.references[opposite] = { type: this , cardinality: oppositeCardinality === undefined && target.references[opposite] !== undefined ? target.references[opposite].cardinality : Cardinality.check(oppositeCardinality) , opposite: name , errorCallback: oppositeErrorCallback === undefined && target.references[opposite] !== undefined ? target.references[opposite].oppositeErrorCallback : this.errorCallback } } if (associated !== undefined) { this.references[name].associated = associated if (opposite !== undefined) { target.references[opposite].associated = associated } } this.references[name].errorCallback = errorCallback || this.errorCallback }
javascript
function addReference(name, target, sourceCardinality, opposite, oppositeCardinality, associated, errorCallback, oppositeErrorCallback) { this.references[name] = { type: target || Type.JSMFAny , cardinality: Cardinality.check(sourceCardinality) } if (opposite !== undefined) { this.references[name].opposite = opposite target.references[opposite] = { type: this , cardinality: oppositeCardinality === undefined && target.references[opposite] !== undefined ? target.references[opposite].cardinality : Cardinality.check(oppositeCardinality) , opposite: name , errorCallback: oppositeErrorCallback === undefined && target.references[opposite] !== undefined ? target.references[opposite].oppositeErrorCallback : this.errorCallback } } if (associated !== undefined) { this.references[name].associated = associated if (opposite !== undefined) { target.references[opposite].associated = associated } } this.references[name].errorCallback = errorCallback || this.errorCallback }
[ "function", "addReference", "(", "name", ",", "target", ",", "sourceCardinality", ",", "opposite", ",", "oppositeCardinality", ",", "associated", ",", "errorCallback", ",", "oppositeErrorCallback", ")", "{", "this", ".", "references", "[", "name", "]", "=", "{", "type", ":", "target", "||", "Type", ".", "JSMFAny", ",", "cardinality", ":", "Cardinality", ".", "check", "(", "sourceCardinality", ")", "}", "if", "(", "opposite", "!==", "undefined", ")", "{", "this", ".", "references", "[", "name", "]", ".", "opposite", "=", "opposite", "target", ".", "references", "[", "opposite", "]", "=", "{", "type", ":", "this", ",", "cardinality", ":", "oppositeCardinality", "===", "undefined", "&&", "target", ".", "references", "[", "opposite", "]", "!==", "undefined", "?", "target", ".", "references", "[", "opposite", "]", ".", "cardinality", ":", "Cardinality", ".", "check", "(", "oppositeCardinality", ")", ",", "opposite", ":", "name", ",", "errorCallback", ":", "oppositeErrorCallback", "===", "undefined", "&&", "target", ".", "references", "[", "opposite", "]", "!==", "undefined", "?", "target", ".", "references", "[", "opposite", "]", ".", "oppositeErrorCallback", ":", "this", ".", "errorCallback", "}", "}", "if", "(", "associated", "!==", "undefined", ")", "{", "this", ".", "references", "[", "name", "]", ".", "associated", "=", "associated", "if", "(", "opposite", "!==", "undefined", ")", "{", "target", ".", "references", "[", "opposite", "]", ".", "associated", "=", "associated", "}", "}", "this", ".", "references", "[", "name", "]", ".", "errorCallback", "=", "errorCallback", "||", "this", ".", "errorCallback", "}" ]
Add a reference to the Class @method @memberof Class~ClassInstance @param {string} name - The reference name @param {Class} target - The target class. Note that {@link Class} and {@link Model} can be targeted as well, even if they are not formally instances of {@link Class}. @param {Cardinality} sourceCardinality - The cardinality of the reference @param {string} opposite - The name of the ooposite reference if any, it can be an existing or a new reference name. @param {Cardinality} oppositeCardinality - The cardinality of the opposite reference, not used if opposite is not set. @param {Class} associated - The type of the associated data linked to this reference @param {Function} errorCallback - Defines what to do when wrong types are assigned @param {Function} oppositeErrorCallback - Defines what to do when wrong types are assigned to the opposite reference
[ "Add", "a", "reference", "to", "the", "Class" ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Class.js#L192-L216
train
JS-MF/jsmf-core
src/Class.js
removeReference
function removeReference(name, opposite) { const ref = this.references[name] _.unset(this.references, name) if (ref.opposite !== undefined) { if (opposite) { _.unset(ref.type.references, ref.opposite) } else { _.unset(ref.type.references[ref.opposite], 'opposite') } } }
javascript
function removeReference(name, opposite) { const ref = this.references[name] _.unset(this.references, name) if (ref.opposite !== undefined) { if (opposite) { _.unset(ref.type.references, ref.opposite) } else { _.unset(ref.type.references[ref.opposite], 'opposite') } } }
[ "function", "removeReference", "(", "name", ",", "opposite", ")", "{", "const", "ref", "=", "this", ".", "references", "[", "name", "]", "_", ".", "unset", "(", "this", ".", "references", ",", "name", ")", "if", "(", "ref", ".", "opposite", "!==", "undefined", ")", "{", "if", "(", "opposite", ")", "{", "_", ".", "unset", "(", "ref", ".", "type", ".", "references", ",", "ref", ".", "opposite", ")", "}", "else", "{", "_", ".", "unset", "(", "ref", ".", "type", ".", "references", "[", "ref", ".", "opposite", "]", ",", "'opposite'", ")", "}", "}", "}" ]
Remove a reference from a class @method @memberof Class~ClassInstance @param {string} name - The name of the reference to remove @param {boolean} opposite - true if the opposite reference should be removed as well
[ "Remove", "a", "reference", "from", "a", "class" ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Class.js#L225-L235
train
JS-MF/jsmf-core
src/Class.js
setSuperType
function setSuperType(s) { const ss = _.isArray(s) ? s : [s] this.superClasses = _.uniq(this.superClasses.concat(ss)) }
javascript
function setSuperType(s) { const ss = _.isArray(s) ? s : [s] this.superClasses = _.uniq(this.superClasses.concat(ss)) }
[ "function", "setSuperType", "(", "s", ")", "{", "const", "ss", "=", "_", ".", "isArray", "(", "s", ")", "?", "s", ":", "[", "s", "]", "this", ".", "superClasses", "=", "_", ".", "uniq", "(", "this", ".", "superClasses", ".", "concat", "(", "ss", ")", ")", "}" ]
Change superClasses of this class. @method @memberof Class~ClassInstance @param s - Either a {@link Class} or an array of {@link Class}
[ "Change", "superClasses", "of", "this", "class", "." ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Class.js#L270-L273
train
JS-MF/jsmf-core
src/Class.js
addAttribute
function addAttribute(name, type, mandatory, errorCallback) { this.attributes[name] = { type: Type.normalizeType(type) , mandatory: mandatory || false , errorCallback: errorCallback || this.errorCallback } }
javascript
function addAttribute(name, type, mandatory, errorCallback) { this.attributes[name] = { type: Type.normalizeType(type) , mandatory: mandatory || false , errorCallback: errorCallback || this.errorCallback } }
[ "function", "addAttribute", "(", "name", ",", "type", ",", "mandatory", ",", "errorCallback", ")", "{", "this", ".", "attributes", "[", "name", "]", "=", "{", "type", ":", "Type", ".", "normalizeType", "(", "type", ")", ",", "mandatory", ":", "mandatory", "||", "false", ",", "errorCallback", ":", "errorCallback", "||", "this", ".", "errorCallback", "}", "}" ]
Add an attribute to a class. @method @memberof Class~ClassInstance @param {string} name - The name of the attribute @param {Function} type - In jsmf an attribute Type is a function that returns true if the value is a member of this type, false otherwise. Some predefined types are available in the class {@link Type}. Users can also use builtin JavaScript types, that are replaced on the fly by the corresponding validation function @param {boolean} mandatory - If set to true, the attribute can't be set to undefined. @param {Function} errorCallback - defines what to do if an invalid value is set to this attribute.
[ "Add", "an", "attribute", "to", "a", "class", "." ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Class.js#L287-L293
train
JS-MF/jsmf-core
src/Class.js
addAttributes
function addAttributes(attrs) { _.forEach(attrs, (v, k) => { if (v.type !== undefined) { this.addAttribute(k, v.type, v.mandatory, v.errorCallback) } else { this.addAttribute(k, v) } }) }
javascript
function addAttributes(attrs) { _.forEach(attrs, (v, k) => { if (v.type !== undefined) { this.addAttribute(k, v.type, v.mandatory, v.errorCallback) } else { this.addAttribute(k, v) } }) }
[ "function", "addAttributes", "(", "attrs", ")", "{", "_", ".", "forEach", "(", "attrs", ",", "(", "v", ",", "k", ")", "=>", "{", "if", "(", "v", ".", "type", "!==", "undefined", ")", "{", "this", ".", "addAttribute", "(", "k", ",", "v", ".", "type", ",", "v", ".", "mandatory", ",", "v", ".", "errorCallback", ")", "}", "else", "{", "this", ".", "addAttribute", "(", "k", ",", "v", ")", "}", "}", ")", "}" ]
Add several attributes @method @memberof Class~ClassInstance @param {Object} attrs - The attributes to add. The keys are te attribute name, the values are the attributes descriptors. See {@link Class~ClassInstance#RemoveAttribute} for the supported properties.
[ "Add", "several", "attributes" ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Class.js#L312-L320
train
JS-MF/jsmf-core
src/Class.js
setFlexible
function setFlexible(b) { this.errorCallback = b ? onError.silent : onError.throw _.forEach(this.references, r => r.errorCallback = this.errorCallback) _.forEach(this.attributes, r => r.errorCallback = this.errorCallback) }
javascript
function setFlexible(b) { this.errorCallback = b ? onError.silent : onError.throw _.forEach(this.references, r => r.errorCallback = this.errorCallback) _.forEach(this.attributes, r => r.errorCallback = this.errorCallback) }
[ "function", "setFlexible", "(", "b", ")", "{", "this", ".", "errorCallback", "=", "b", "?", "onError", ".", "silent", ":", "onError", ".", "throw", "_", ".", "forEach", "(", "this", ".", "references", ",", "r", "=>", "r", ".", "errorCallback", "=", "this", ".", "errorCallback", ")", "_", ".", "forEach", "(", "this", ".", "attributes", ",", "r", "=>", "r", ".", "errorCallback", "=", "this", ".", "errorCallback", ")", "}" ]
Decide whether whether or not type will becheck for attributes and references of a whole class. @method @memberof Class~ClassInstance @param {boolean} b - If true, type is not checked on assignement, if false wrong assignement type riase an error.
[ "Decide", "whether", "whether", "or", "not", "type", "will", "becheck", "for", "attributes", "and", "references", "of", "a", "whole", "class", "." ]
3d3703f879c4084099156b96f83671d614128fd2
https://github.com/JS-MF/jsmf-core/blob/3d3703f879c4084099156b96f83671d614128fd2/src/Class.js#L457-L461
train
suguru/cql-client
lib/resultset.js
ResultSet
function ResultSet(conn, query, values, options, rs) { this.query = query; this.metadata = rs.metadata; this.rows = rs.rows; this._conn = conn; this._values = values; this._options = options; }
javascript
function ResultSet(conn, query, values, options, rs) { this.query = query; this.metadata = rs.metadata; this.rows = rs.rows; this._conn = conn; this._values = values; this._options = options; }
[ "function", "ResultSet", "(", "conn", ",", "query", ",", "values", ",", "options", ",", "rs", ")", "{", "this", ".", "query", "=", "query", ";", "this", ".", "metadata", "=", "rs", ".", "metadata", ";", "this", ".", "rows", "=", "rs", ".", "rows", ";", "this", ".", "_conn", "=", "conn", ";", "this", ".", "_values", "=", "values", ";", "this", ".", "_options", "=", "options", ";", "}" ]
Result set wrapper
[ "Result", "set", "wrapper" ]
c80563526827d13505e4821f7091d4db75e556c1
https://github.com/suguru/cql-client/blob/c80563526827d13505e4821f7091d4db75e556c1/lib/resultset.js#L8-L15
train
taskcluster/taskcluster-client
src/client.js
function(client, method, url, payload, query) { // Add query to url if present if (query) { query = querystring.stringify(query); if (query.length > 0) { url += '?' + query; } } // Construct request object var req = request(method.toUpperCase(), url); // Set the http agent for this request, if supported in the current // environment (browser environment doesn't support http.Agent) if (req.agent) { req.agent(client._httpAgent); } // Timeout for each individual request. req.timeout(client._timeout); // Send payload if defined if (payload !== undefined) { req.send(payload); } // Authenticate, if credentials are provided if (client._options.credentials && client._options.credentials.clientId && client._options.credentials.accessToken) { // Create hawk authentication header var header = hawk.client.header(url, method.toUpperCase(), { credentials: { id: client._options.credentials.clientId, key: client._options.credentials.accessToken, algorithm: 'sha256', }, ext: client._extData, }); req.set('Authorization', header.field); } // Return request return req; }
javascript
function(client, method, url, payload, query) { // Add query to url if present if (query) { query = querystring.stringify(query); if (query.length > 0) { url += '?' + query; } } // Construct request object var req = request(method.toUpperCase(), url); // Set the http agent for this request, if supported in the current // environment (browser environment doesn't support http.Agent) if (req.agent) { req.agent(client._httpAgent); } // Timeout for each individual request. req.timeout(client._timeout); // Send payload if defined if (payload !== undefined) { req.send(payload); } // Authenticate, if credentials are provided if (client._options.credentials && client._options.credentials.clientId && client._options.credentials.accessToken) { // Create hawk authentication header var header = hawk.client.header(url, method.toUpperCase(), { credentials: { id: client._options.credentials.clientId, key: client._options.credentials.accessToken, algorithm: 'sha256', }, ext: client._extData, }); req.set('Authorization', header.field); } // Return request return req; }
[ "function", "(", "client", ",", "method", ",", "url", ",", "payload", ",", "query", ")", "{", "if", "(", "query", ")", "{", "query", "=", "querystring", ".", "stringify", "(", "query", ")", ";", "if", "(", "query", ".", "length", ">", "0", ")", "{", "url", "+=", "'?'", "+", "query", ";", "}", "}", "var", "req", "=", "request", "(", "method", ".", "toUpperCase", "(", ")", ",", "url", ")", ";", "if", "(", "req", ".", "agent", ")", "{", "req", ".", "agent", "(", "client", ".", "_httpAgent", ")", ";", "}", "req", ".", "timeout", "(", "client", ".", "_timeout", ")", ";", "if", "(", "payload", "!==", "undefined", ")", "{", "req", ".", "send", "(", "payload", ")", ";", "}", "if", "(", "client", ".", "_options", ".", "credentials", "&&", "client", ".", "_options", ".", "credentials", ".", "clientId", "&&", "client", ".", "_options", ".", "credentials", ".", "accessToken", ")", "{", "var", "header", "=", "hawk", ".", "client", ".", "header", "(", "url", ",", "method", ".", "toUpperCase", "(", ")", ",", "{", "credentials", ":", "{", "id", ":", "client", ".", "_options", ".", "credentials", ".", "clientId", ",", "key", ":", "client", ".", "_options", ".", "credentials", ".", "accessToken", ",", "algorithm", ":", "'sha256'", ",", "}", ",", "ext", ":", "client", ".", "_extData", ",", "}", ")", ";", "req", ".", "set", "(", "'Authorization'", ",", "header", ".", "field", ")", ";", "}", "return", "req", ";", "}" ]
Make a request for a Client instance
[ "Make", "a", "request", "for", "a", "Client", "instance" ]
02d3efff9fdd046daa75b95e0f6a8f957c1abb09
https://github.com/taskcluster/taskcluster-client/blob/02d3efff9fdd046daa75b95e0f6a8f957c1abb09/src/client.js#L76-L119
train
Munawwar/htmlizer
src/Htmlizer.js
function (attr, expr, context, data) { var val = this.exprEvaluator(expr, context, data); if (val || typeof val === 'string' || typeof val === 'number') { return " " + attr + '=' + this.generateAttribute(val + ''); } else { //else if undefined, null, false then don't render attribute. return ''; } }
javascript
function (attr, expr, context, data) { var val = this.exprEvaluator(expr, context, data); if (val || typeof val === 'string' || typeof val === 'number') { return " " + attr + '=' + this.generateAttribute(val + ''); } else { //else if undefined, null, false then don't render attribute. return ''; } }
[ "function", "(", "attr", ",", "expr", ",", "context", ",", "data", ")", "{", "var", "val", "=", "this", ".", "exprEvaluator", "(", "expr", ",", "context", ",", "data", ")", ";", "if", "(", "val", "||", "typeof", "val", "===", "'string'", "||", "typeof", "val", "===", "'number'", ")", "{", "return", "\" \"", "+", "attr", "+", "'='", "+", "this", ".", "generateAttribute", "(", "val", "+", "''", ")", ";", "}", "else", "{", "return", "''", ";", "}", "}" ]
Assuming attr parameter is html encoded.
[ "Assuming", "attr", "parameter", "is", "html", "encoded", "." ]
46cdb8634da308446b24446cc2058882a5079f92
https://github.com/Munawwar/htmlizer/blob/46cdb8634da308446b24446cc2058882a5079f92/src/Htmlizer.js#L624-L632
train
Munawwar/htmlizer
src/Htmlizer.js
function (dom) { var html = ''; dom.forEach(function (node) { if (node.type === 'tag') { var tag = node.name; html += '<' + tag; Object.keys(node.attribs).forEach(function (attr) { html += ' ' + attr + '=' + this.generateAttribute(node.attribs[attr]); }, this); html += (voidTags[tag] ? '/>' : '>'); if (!voidTags[tag]) { html += this.vdomToHtml(node.children); html += '</' + tag + '>'; } } else if (node.type === 'text') { var text = node.data || ''; html += this.htmlEncode(text); //escape <,> and &. } else if (node.type === 'comment') { html += '<!-- ' + node.data.trim() + ' -->'; } else if (node.type === 'script' || node.type === 'style') { //No need to escape text inside script or style tag. html += '<' + node.name; Object.keys(node.attribs).forEach(function (attr) { html += ' ' + attr + '=' + this.generateAttribute(node.attribs[attr]); }, this); html += '>' + ((node.children[0] || {}).data || '') + '</' + node.name + '>'; } else if (node.type === 'directive') { html += '<' + node.data + '>'; } }, this); return html; }
javascript
function (dom) { var html = ''; dom.forEach(function (node) { if (node.type === 'tag') { var tag = node.name; html += '<' + tag; Object.keys(node.attribs).forEach(function (attr) { html += ' ' + attr + '=' + this.generateAttribute(node.attribs[attr]); }, this); html += (voidTags[tag] ? '/>' : '>'); if (!voidTags[tag]) { html += this.vdomToHtml(node.children); html += '</' + tag + '>'; } } else if (node.type === 'text') { var text = node.data || ''; html += this.htmlEncode(text); //escape <,> and &. } else if (node.type === 'comment') { html += '<!-- ' + node.data.trim() + ' -->'; } else if (node.type === 'script' || node.type === 'style') { //No need to escape text inside script or style tag. html += '<' + node.name; Object.keys(node.attribs).forEach(function (attr) { html += ' ' + attr + '=' + this.generateAttribute(node.attribs[attr]); }, this); html += '>' + ((node.children[0] || {}).data || '') + '</' + node.name + '>'; } else if (node.type === 'directive') { html += '<' + node.data + '>'; } }, this); return html; }
[ "function", "(", "dom", ")", "{", "var", "html", "=", "''", ";", "dom", ".", "forEach", "(", "function", "(", "node", ")", "{", "if", "(", "node", ".", "type", "===", "'tag'", ")", "{", "var", "tag", "=", "node", ".", "name", ";", "html", "+=", "'<'", "+", "tag", ";", "Object", ".", "keys", "(", "node", ".", "attribs", ")", ".", "forEach", "(", "function", "(", "attr", ")", "{", "html", "+=", "' '", "+", "attr", "+", "'='", "+", "this", ".", "generateAttribute", "(", "node", ".", "attribs", "[", "attr", "]", ")", ";", "}", ",", "this", ")", ";", "html", "+=", "(", "voidTags", "[", "tag", "]", "?", "'/>'", ":", "'>'", ")", ";", "if", "(", "!", "voidTags", "[", "tag", "]", ")", "{", "html", "+=", "this", ".", "vdomToHtml", "(", "node", ".", "children", ")", ";", "html", "+=", "'</'", "+", "tag", "+", "'>'", ";", "}", "}", "else", "if", "(", "node", ".", "type", "===", "'text'", ")", "{", "var", "text", "=", "node", ".", "data", "||", "''", ";", "html", "+=", "this", ".", "htmlEncode", "(", "text", ")", ";", "}", "else", "if", "(", "node", ".", "type", "===", "'comment'", ")", "{", "html", "+=", "'<!-- '", "+", "node", ".", "data", ".", "trim", "(", ")", "+", "' ", ";", "}", "else", "if", "(", "node", ".", "type", "===", "'script'", "||", "node", ".", "type", "===", "'style'", ")", "{", "html", "+=", "'<'", "+", "node", ".", "name", ";", "Object", ".", "keys", "(", "node", ".", "attribs", ")", ".", "forEach", "(", "function", "(", "attr", ")", "{", "html", "+=", "' '", "+", "attr", "+", "'='", "+", "this", ".", "generateAttribute", "(", "node", ".", "attribs", "[", "attr", "]", ")", ";", "}", ",", "this", ")", ";", "html", "+=", "'>'", "+", "(", "(", "node", ".", "children", "[", "0", "]", "||", "{", "}", ")", ".", "data", "||", "''", ")", "+", "'</'", "+", "node", ".", "name", "+", "'>'", ";", "}", "else", "if", "(", "node", ".", "type", "===", "'directive'", ")", "{", "html", "+=", "'<'", "+", "node", ".", "data", "+", "'>'", ";", "}", "}", ",", "this", ")", ";", "return", "html", ";", "}" ]
Converts vdom from domhandler to HTML.
[ "Converts", "vdom", "from", "domhandler", "to", "HTML", "." ]
46cdb8634da308446b24446cc2058882a5079f92
https://github.com/Munawwar/htmlizer/blob/46cdb8634da308446b24446cc2058882a5079f92/src/Htmlizer.js#L804-L835
train
Munawwar/htmlizer
src/Htmlizer.js
function (nodes, parent) { var copy = nodes.map(function (node, index) { var clone = {}; //Shallow copy Object.keys(node).forEach(function (prop) { clone[prop] = node[prop]; }); return clone; }); copy.forEach(function (cur, i) { cur.prev = copy[i - 1]; cur.next = copy[i + 1]; cur.parent = parent; if (cur.children) { cur.children = this.makeNewFragment(cur.children, cur); } }, this); return copy; }
javascript
function (nodes, parent) { var copy = nodes.map(function (node, index) { var clone = {}; //Shallow copy Object.keys(node).forEach(function (prop) { clone[prop] = node[prop]; }); return clone; }); copy.forEach(function (cur, i) { cur.prev = copy[i - 1]; cur.next = copy[i + 1]; cur.parent = parent; if (cur.children) { cur.children = this.makeNewFragment(cur.children, cur); } }, this); return copy; }
[ "function", "(", "nodes", ",", "parent", ")", "{", "var", "copy", "=", "nodes", ".", "map", "(", "function", "(", "node", ",", "index", ")", "{", "var", "clone", "=", "{", "}", ";", "Object", ".", "keys", "(", "node", ")", ".", "forEach", "(", "function", "(", "prop", ")", "{", "clone", "[", "prop", "]", "=", "node", "[", "prop", "]", ";", "}", ")", ";", "return", "clone", ";", "}", ")", ";", "copy", ".", "forEach", "(", "function", "(", "cur", ",", "i", ")", "{", "cur", ".", "prev", "=", "copy", "[", "i", "-", "1", "]", ";", "cur", ".", "next", "=", "copy", "[", "i", "+", "1", "]", ";", "cur", ".", "parent", "=", "parent", ";", "if", "(", "cur", ".", "children", ")", "{", "cur", ".", "children", "=", "this", ".", "makeNewFragment", "(", "cur", ".", "children", ",", "cur", ")", ";", "}", "}", ",", "this", ")", ";", "return", "copy", ";", "}" ]
Makes a deep copy of a list of nodes; corrects next,prev & parent references and then puts them into an array. This is to detach nodes from their parent. Nodes are considered immutable, hence copy is needed. i.e. Doing node.parent = null, during a traversal could cause traversal logic to behave unexpectedly.
[ "Makes", "a", "deep", "copy", "of", "a", "list", "of", "nodes", ";", "corrects", "next", "prev", "&", "parent", "references", "and", "then", "puts", "them", "into", "an", "array", "." ]
46cdb8634da308446b24446cc2058882a5079f92
https://github.com/Munawwar/htmlizer/blob/46cdb8634da308446b24446cc2058882a5079f92/src/Htmlizer.js#L863-L881
train
Munawwar/htmlizer
src/Htmlizer.js
function (objectLiteral, callback, scope) { if (objectLiteral) { parseObjectLiteral(objectLiteral).some(function (tuple) { return (callback.call(scope, tuple[0], tuple[1]) === true); }); } }
javascript
function (objectLiteral, callback, scope) { if (objectLiteral) { parseObjectLiteral(objectLiteral).some(function (tuple) { return (callback.call(scope, tuple[0], tuple[1]) === true); }); } }
[ "function", "(", "objectLiteral", ",", "callback", ",", "scope", ")", "{", "if", "(", "objectLiteral", ")", "{", "parseObjectLiteral", "(", "objectLiteral", ")", ".", "some", "(", "function", "(", "tuple", ")", "{", "return", "(", "callback", ".", "call", "(", "scope", ",", "tuple", "[", "0", "]", ",", "tuple", "[", "1", "]", ")", "===", "true", ")", ";", "}", ")", ";", "}", "}" ]
Will stop iterating if callback returns true. @private
[ "Will", "stop", "iterating", "if", "callback", "returns", "true", "." ]
46cdb8634da308446b24446cc2058882a5079f92
https://github.com/Munawwar/htmlizer/blob/46cdb8634da308446b24446cc2058882a5079f92/src/Htmlizer.js#L899-L905
train
Munawwar/htmlizer
src/Htmlizer.js
funcToString
function funcToString(func) { var str = func.toString(); return str.slice(str.indexOf('{') + 1, str.lastIndexOf('}')); }
javascript
function funcToString(func) { var str = func.toString(); return str.slice(str.indexOf('{') + 1, str.lastIndexOf('}')); }
[ "function", "funcToString", "(", "func", ")", "{", "var", "str", "=", "func", ".", "toString", "(", ")", ";", "return", "str", ".", "slice", "(", "str", ".", "indexOf", "(", "'{'", ")", "+", "1", ",", "str", ".", "lastIndexOf", "(", "'}'", ")", ")", ";", "}" ]
Convert function body to string.
[ "Convert", "function", "body", "to", "string", "." ]
46cdb8634da308446b24446cc2058882a5079f92
https://github.com/Munawwar/htmlizer/blob/46cdb8634da308446b24446cc2058882a5079f92/src/Htmlizer.js#L1022-L1025
train
dumberjs/ast-matcher
index.js
traverse
function traverse(object, visitor) { let child; if (!object) return; let r = visitor.call(null, object); if (r === STOP) return STOP; // stop whole traverse immediately if (r === SKIP_BRANCH) return; // skip going into AST branch for (let i = 0, keys = Object.keys(object); i < keys.length; i++) { let key = keys[i]; if (IGNORED_KEYS.indexOf(key) !== -1) continue; child = object[key]; if (typeof child === 'object' && child !== null) { if (traverse(child, visitor) === STOP) { return STOP; } } } }
javascript
function traverse(object, visitor) { let child; if (!object) return; let r = visitor.call(null, object); if (r === STOP) return STOP; // stop whole traverse immediately if (r === SKIP_BRANCH) return; // skip going into AST branch for (let i = 0, keys = Object.keys(object); i < keys.length; i++) { let key = keys[i]; if (IGNORED_KEYS.indexOf(key) !== -1) continue; child = object[key]; if (typeof child === 'object' && child !== null) { if (traverse(child, visitor) === STOP) { return STOP; } } } }
[ "function", "traverse", "(", "object", ",", "visitor", ")", "{", "let", "child", ";", "if", "(", "!", "object", ")", "return", ";", "let", "r", "=", "visitor", ".", "call", "(", "null", ",", "object", ")", ";", "if", "(", "r", "===", "STOP", ")", "return", "STOP", ";", "if", "(", "r", "===", "SKIP_BRANCH", ")", "return", ";", "for", "(", "let", "i", "=", "0", ",", "keys", "=", "Object", ".", "keys", "(", "object", ")", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "let", "key", "=", "keys", "[", "i", "]", ";", "if", "(", "IGNORED_KEYS", ".", "indexOf", "(", "key", ")", "!==", "-", "1", ")", "continue", ";", "child", "=", "object", "[", "key", "]", ";", "if", "(", "typeof", "child", "===", "'object'", "&&", "child", "!==", "null", ")", "{", "if", "(", "traverse", "(", "child", ",", "visitor", ")", "===", "STOP", ")", "{", "return", "STOP", ";", "}", "}", "}", "}" ]
From an esprima example for traversing its ast. modified to support branch skip.
[ "From", "an", "esprima", "example", "for", "traversing", "its", "ast", ".", "modified", "to", "support", "branch", "skip", "." ]
c92f7edc9b98a29d406f2b11e0003b3b9b339f57
https://github.com/dumberjs/ast-matcher/blob/c92f7edc9b98a29d406f2b11e0003b3b9b339f57/index.js#L22-L41
train
dumberjs/ast-matcher
index.js
extract
function extract(pattern, part) { if (!pattern) throw new Error('missing pattern'); // no match if (!part) return STOP; let term = matchTerm(pattern); if (term) { // if single __any if (term.type === ANY) { if (term.name) { // if __any_foo // get result {foo: astNode} let r = {}; r[term.name] = part; return r; } // always match return {}; // if single __str_foo } else if (term.type === STR) { if (part.type === 'Literal') { if (term.name) { // get result {foo: value} let r = {}; r[term.name] = part.value; return r; } // always match return {}; } // no match return STOP; } } if (Array.isArray(pattern)) { // no match if (!Array.isArray(part)) return STOP; if (pattern.length === 1) { let arrTerm = matchTerm(pattern[0]); if (arrTerm) { // if single __arr_foo if (arrTerm.type === ARR) { // find all or partial Literals in an array let arr = part.filter(function(it) { return it.type === 'Literal'; }) .map(function(it) { return it.value; }); if (arr.length) { if (arrTerm.name) { // get result {foo: array} let r = {}; r[arrTerm.name] = arr; return r; } // always match return {}; } // no match return STOP; } else if (arrTerm.type === ANL) { if (arrTerm.name) { // get result {foo: nodes array} let r = {}; r[arrTerm.name] = part; return r; } // always match return {}; } } } if (pattern.length !== part.length) { // no match return STOP; } } let allResult = {}; for (let i = 0, keys = Object.keys(pattern); i < keys.length; i++) { let key = keys[i]; if (IGNORED_KEYS.indexOf(key) !== -1) continue; let nextPattern = pattern[key]; let nextPart = part[key]; if (!nextPattern || typeof nextPattern !== 'object') { // primitive value. string or null if (nextPattern === nextPart) continue; // no match return STOP; } const result = extract(nextPattern, nextPart); // no match if (result === STOP) return STOP; if (result) Object.assign(allResult, result); } return allResult; }
javascript
function extract(pattern, part) { if (!pattern) throw new Error('missing pattern'); // no match if (!part) return STOP; let term = matchTerm(pattern); if (term) { // if single __any if (term.type === ANY) { if (term.name) { // if __any_foo // get result {foo: astNode} let r = {}; r[term.name] = part; return r; } // always match return {}; // if single __str_foo } else if (term.type === STR) { if (part.type === 'Literal') { if (term.name) { // get result {foo: value} let r = {}; r[term.name] = part.value; return r; } // always match return {}; } // no match return STOP; } } if (Array.isArray(pattern)) { // no match if (!Array.isArray(part)) return STOP; if (pattern.length === 1) { let arrTerm = matchTerm(pattern[0]); if (arrTerm) { // if single __arr_foo if (arrTerm.type === ARR) { // find all or partial Literals in an array let arr = part.filter(function(it) { return it.type === 'Literal'; }) .map(function(it) { return it.value; }); if (arr.length) { if (arrTerm.name) { // get result {foo: array} let r = {}; r[arrTerm.name] = arr; return r; } // always match return {}; } // no match return STOP; } else if (arrTerm.type === ANL) { if (arrTerm.name) { // get result {foo: nodes array} let r = {}; r[arrTerm.name] = part; return r; } // always match return {}; } } } if (pattern.length !== part.length) { // no match return STOP; } } let allResult = {}; for (let i = 0, keys = Object.keys(pattern); i < keys.length; i++) { let key = keys[i]; if (IGNORED_KEYS.indexOf(key) !== -1) continue; let nextPattern = pattern[key]; let nextPart = part[key]; if (!nextPattern || typeof nextPattern !== 'object') { // primitive value. string or null if (nextPattern === nextPart) continue; // no match return STOP; } const result = extract(nextPattern, nextPart); // no match if (result === STOP) return STOP; if (result) Object.assign(allResult, result); } return allResult; }
[ "function", "extract", "(", "pattern", ",", "part", ")", "{", "if", "(", "!", "pattern", ")", "throw", "new", "Error", "(", "'missing pattern'", ")", ";", "if", "(", "!", "part", ")", "return", "STOP", ";", "let", "term", "=", "matchTerm", "(", "pattern", ")", ";", "if", "(", "term", ")", "{", "if", "(", "term", ".", "type", "===", "ANY", ")", "{", "if", "(", "term", ".", "name", ")", "{", "let", "r", "=", "{", "}", ";", "r", "[", "term", ".", "name", "]", "=", "part", ";", "return", "r", ";", "}", "return", "{", "}", ";", "}", "else", "if", "(", "term", ".", "type", "===", "STR", ")", "{", "if", "(", "part", ".", "type", "===", "'Literal'", ")", "{", "if", "(", "term", ".", "name", ")", "{", "let", "r", "=", "{", "}", ";", "r", "[", "term", ".", "name", "]", "=", "part", ".", "value", ";", "return", "r", ";", "}", "return", "{", "}", ";", "}", "return", "STOP", ";", "}", "}", "if", "(", "Array", ".", "isArray", "(", "pattern", ")", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "part", ")", ")", "return", "STOP", ";", "if", "(", "pattern", ".", "length", "===", "1", ")", "{", "let", "arrTerm", "=", "matchTerm", "(", "pattern", "[", "0", "]", ")", ";", "if", "(", "arrTerm", ")", "{", "if", "(", "arrTerm", ".", "type", "===", "ARR", ")", "{", "let", "arr", "=", "part", ".", "filter", "(", "function", "(", "it", ")", "{", "return", "it", ".", "type", "===", "'Literal'", ";", "}", ")", ".", "map", "(", "function", "(", "it", ")", "{", "return", "it", ".", "value", ";", "}", ")", ";", "if", "(", "arr", ".", "length", ")", "{", "if", "(", "arrTerm", ".", "name", ")", "{", "let", "r", "=", "{", "}", ";", "r", "[", "arrTerm", ".", "name", "]", "=", "arr", ";", "return", "r", ";", "}", "return", "{", "}", ";", "}", "return", "STOP", ";", "}", "else", "if", "(", "arrTerm", ".", "type", "===", "ANL", ")", "{", "if", "(", "arrTerm", ".", "name", ")", "{", "let", "r", "=", "{", "}", ";", "r", "[", "arrTerm", ".", "name", "]", "=", "part", ";", "return", "r", ";", "}", "return", "{", "}", ";", "}", "}", "}", "if", "(", "pattern", ".", "length", "!==", "part", ".", "length", ")", "{", "return", "STOP", ";", "}", "}", "let", "allResult", "=", "{", "}", ";", "for", "(", "let", "i", "=", "0", ",", "keys", "=", "Object", ".", "keys", "(", "pattern", ")", ";", "i", "<", "keys", ".", "length", ";", "i", "++", ")", "{", "let", "key", "=", "keys", "[", "i", "]", ";", "if", "(", "IGNORED_KEYS", ".", "indexOf", "(", "key", ")", "!==", "-", "1", ")", "continue", ";", "let", "nextPattern", "=", "pattern", "[", "key", "]", ";", "let", "nextPart", "=", "part", "[", "key", "]", ";", "if", "(", "!", "nextPattern", "||", "typeof", "nextPattern", "!==", "'object'", ")", "{", "if", "(", "nextPattern", "===", "nextPart", ")", "continue", ";", "return", "STOP", ";", "}", "const", "result", "=", "extract", "(", "nextPattern", ",", "nextPart", ")", ";", "if", "(", "result", "===", "STOP", ")", "return", "STOP", ";", "if", "(", "result", ")", "Object", ".", "assign", "(", "allResult", ",", "result", ")", ";", "}", "return", "allResult", ";", "}" ]
Extract info from a partial estree syntax tree, see astMatcher for pattern format @param pattern The pattern used on matching @param part The target partial syntax tree @return Returns named matches, or false.
[ "Extract", "info", "from", "a", "partial", "estree", "syntax", "tree", "see", "astMatcher", "for", "pattern", "format" ]
c92f7edc9b98a29d406f2b11e0003b3b9b339f57
https://github.com/dumberjs/ast-matcher/blob/c92f7edc9b98a29d406f2b11e0003b3b9b339f57/index.js#L79-L184
train
dumberjs/ast-matcher
index.js
compilePattern
function compilePattern(pattern) { // pass estree syntax tree obj if (pattern && pattern.type) return pattern; if (typeof pattern !== 'string') { throw new Error('input pattern is neither a string nor an estree node.'); } let exp = parser(pattern); if (exp.type !== 'Program' || !exp.body) { throw new Error(`Not a valid expression: "${pattern}".`); } if (exp.body.length === 0) { throw new Error(`There is no statement in pattern "${pattern}".`); } if (exp.body.length > 1) { throw new Error(`Multiple statements is not supported "${pattern}".`); } exp = exp.body[0]; // get the real expression underneath if (exp.type === 'ExpressionStatement') exp = exp.expression; return exp; }
javascript
function compilePattern(pattern) { // pass estree syntax tree obj if (pattern && pattern.type) return pattern; if (typeof pattern !== 'string') { throw new Error('input pattern is neither a string nor an estree node.'); } let exp = parser(pattern); if (exp.type !== 'Program' || !exp.body) { throw new Error(`Not a valid expression: "${pattern}".`); } if (exp.body.length === 0) { throw new Error(`There is no statement in pattern "${pattern}".`); } if (exp.body.length > 1) { throw new Error(`Multiple statements is not supported "${pattern}".`); } exp = exp.body[0]; // get the real expression underneath if (exp.type === 'ExpressionStatement') exp = exp.expression; return exp; }
[ "function", "compilePattern", "(", "pattern", ")", "{", "if", "(", "pattern", "&&", "pattern", ".", "type", ")", "return", "pattern", ";", "if", "(", "typeof", "pattern", "!==", "'string'", ")", "{", "throw", "new", "Error", "(", "'input pattern is neither a string nor an estree node.'", ")", ";", "}", "let", "exp", "=", "parser", "(", "pattern", ")", ";", "if", "(", "exp", ".", "type", "!==", "'Program'", "||", "!", "exp", ".", "body", ")", "{", "throw", "new", "Error", "(", "`", "${", "pattern", "}", "`", ")", ";", "}", "if", "(", "exp", ".", "body", ".", "length", "===", "0", ")", "{", "throw", "new", "Error", "(", "`", "${", "pattern", "}", "`", ")", ";", "}", "if", "(", "exp", ".", "body", ".", "length", ">", "1", ")", "{", "throw", "new", "Error", "(", "`", "${", "pattern", "}", "`", ")", ";", "}", "exp", "=", "exp", ".", "body", "[", "0", "]", ";", "if", "(", "exp", ".", "type", "===", "'ExpressionStatement'", ")", "exp", "=", "exp", ".", "expression", ";", "return", "exp", ";", "}" ]
Compile a pattern into estree syntax tree @param pattern The pattern used on matching, can be a string or estree node @return Returns an estree node to be used as pattern in extract(pattern, part)
[ "Compile", "a", "pattern", "into", "estree", "syntax", "tree" ]
c92f7edc9b98a29d406f2b11e0003b3b9b339f57
https://github.com/dumberjs/ast-matcher/blob/c92f7edc9b98a29d406f2b11e0003b3b9b339f57/index.js#L191-L217
train
uber-archive/nanny
_worker.js
tock
function tock() { var tockPeriod = process.hrtime(tickTime); var tockPeriodMs = hrtimeAsMs(tockPeriod); process.send({ cmd: 'CLUSTER_PULSE', load: tockPeriodMs - pulse, memoryUsage: process.memoryUsage() }); tick(); }
javascript
function tock() { var tockPeriod = process.hrtime(tickTime); var tockPeriodMs = hrtimeAsMs(tockPeriod); process.send({ cmd: 'CLUSTER_PULSE', load: tockPeriodMs - pulse, memoryUsage: process.memoryUsage() }); tick(); }
[ "function", "tock", "(", ")", "{", "var", "tockPeriod", "=", "process", ".", "hrtime", "(", "tickTime", ")", ";", "var", "tockPeriodMs", "=", "hrtimeAsMs", "(", "tockPeriod", ")", ";", "process", ".", "send", "(", "{", "cmd", ":", "'CLUSTER_PULSE'", ",", "load", ":", "tockPeriodMs", "-", "pulse", ",", "memoryUsage", ":", "process", ".", "memoryUsage", "(", ")", "}", ")", ";", "tick", "(", ")", ";", "}" ]
Measures the actual duration of the pulse and transmits health metrics to the supervisor. The load measures the average amount of time that the event loop blocked the scheduled pulse.
[ "Measures", "the", "actual", "duration", "of", "the", "pulse", "and", "transmits", "health", "metrics", "to", "the", "supervisor", ".", "The", "load", "measures", "the", "average", "amount", "of", "time", "that", "the", "event", "loop", "blocked", "the", "scheduled", "pulse", "." ]
2ff8e045eb5f71d1fc49e0b95e6aa425ccb04f11
https://github.com/uber-archive/nanny/blob/2ff8e045eb5f71d1fc49e0b95e6aa425ccb04f11/_worker.js#L149-L158
train
logikum/md-site-engine
source/models/menu-item.js
function( id, text, order, path, hidden, umbel ) { MenuProto.call( this, id, text, order, hidden ); /** * Gets the paths of the menu item. * @type {Array.<string>} */ this.paths = createPathList( path ); /** * Gets whether the menu item is umbrella for more items. * @type {MenuStock} */ this.umbel = umbel; }
javascript
function( id, text, order, path, hidden, umbel ) { MenuProto.call( this, id, text, order, hidden ); /** * Gets the paths of the menu item. * @type {Array.<string>} */ this.paths = createPathList( path ); /** * Gets whether the menu item is umbrella for more items. * @type {MenuStock} */ this.umbel = umbel; }
[ "function", "(", "id", ",", "text", ",", "order", ",", "path", ",", "hidden", ",", "umbel", ")", "{", "MenuProto", ".", "call", "(", "this", ",", "id", ",", "text", ",", "order", ",", "hidden", ")", ";", "this", ".", "paths", "=", "createPathList", "(", "path", ")", ";", "this", ".", "umbel", "=", "umbel", ";", "}" ]
Represents an item in the menu tree. @param {number} id - The identifier of the menu item. @param {string} text - The text of the menu item. @param {number} order - The order of the menu item. @param {string} path - The path of the menu item. @param {Boolean} hidden - Indicates whether the menu item is shown. @param {Boolean} umbel - Indicates whether the menu item is umbrella for more items. @constructor
[ "Represents", "an", "item", "in", "the", "menu", "tree", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/models/menu-item.js#L16-L31
train
vesln/pin
lib/ping.js
Ping
function Ping(url, driver) { if (!(this instanceof Ping)) { return new Ping(url, driver); } driver = driver || request; this.url = url; this.driver = driver; this.successCodes = SUCCESS; this.started = false; this.validators = []; var self = this; var textCheck = function(err, res, body) { if (!self._text) return true; return ~body.indexOf(self._text); }; var errorCheck = function(err, res) { return !err; }; var statusCheck = function(err, res, body) { // If there is no result from the server, assume site is down. if (!res){ return false; } else { return ~self.successCodes.indexOf(res.statusCode); } }; var perfCheck = function(err, res, body, info) { if (typeof self._maxDuration !== 'number') return true; return info.duration <= self._maxDuration; }; this.register(errorCheck, statusCheck, textCheck, perfCheck); }
javascript
function Ping(url, driver) { if (!(this instanceof Ping)) { return new Ping(url, driver); } driver = driver || request; this.url = url; this.driver = driver; this.successCodes = SUCCESS; this.started = false; this.validators = []; var self = this; var textCheck = function(err, res, body) { if (!self._text) return true; return ~body.indexOf(self._text); }; var errorCheck = function(err, res) { return !err; }; var statusCheck = function(err, res, body) { // If there is no result from the server, assume site is down. if (!res){ return false; } else { return ~self.successCodes.indexOf(res.statusCode); } }; var perfCheck = function(err, res, body, info) { if (typeof self._maxDuration !== 'number') return true; return info.duration <= self._maxDuration; }; this.register(errorCheck, statusCheck, textCheck, perfCheck); }
[ "function", "Ping", "(", "url", ",", "driver", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Ping", ")", ")", "{", "return", "new", "Ping", "(", "url", ",", "driver", ")", ";", "}", "driver", "=", "driver", "||", "request", ";", "this", ".", "url", "=", "url", ";", "this", ".", "driver", "=", "driver", ";", "this", ".", "successCodes", "=", "SUCCESS", ";", "this", ".", "started", "=", "false", ";", "this", ".", "validators", "=", "[", "]", ";", "var", "self", "=", "this", ";", "var", "textCheck", "=", "function", "(", "err", ",", "res", ",", "body", ")", "{", "if", "(", "!", "self", ".", "_text", ")", "return", "true", ";", "return", "~", "body", ".", "indexOf", "(", "self", ".", "_text", ")", ";", "}", ";", "var", "errorCheck", "=", "function", "(", "err", ",", "res", ")", "{", "return", "!", "err", ";", "}", ";", "var", "statusCheck", "=", "function", "(", "err", ",", "res", ",", "body", ")", "{", "if", "(", "!", "res", ")", "{", "return", "false", ";", "}", "else", "{", "return", "~", "self", ".", "successCodes", ".", "indexOf", "(", "res", ".", "statusCode", ")", ";", "}", "}", ";", "var", "perfCheck", "=", "function", "(", "err", ",", "res", ",", "body", ",", "info", ")", "{", "if", "(", "typeof", "self", ".", "_maxDuration", "!==", "'number'", ")", "return", "true", ";", "return", "info", ".", "duration", "<=", "self", ".", "_maxDuration", ";", "}", ";", "this", ".", "register", "(", "errorCheck", ",", "statusCheck", ",", "textCheck", ",", "perfCheck", ")", ";", "}" ]
Ping class. @param {String} url @param {Object} driver @constructor
[ "Ping", "class", "." ]
c82d36dc7a8aaa1163ef2fe211c096a87622d871
https://github.com/vesln/pin/blob/c82d36dc7a8aaa1163ef2fe211c096a87622d871/lib/ping.js#L30-L68
train
Runnable/loadenv
index.js
loadEnv
function loadEnv(name) { var fullEnvPath = path.resolve(applicationRoot, './configs/' + name); try { debug('Loaded environment: ' + fullEnvPath); fs.statSync(fullEnvPath); dotenv.config({ path: fullEnvPath }); } catch (e) { debug('Could not load environment "' + fullEnvPath + '"'); } }
javascript
function loadEnv(name) { var fullEnvPath = path.resolve(applicationRoot, './configs/' + name); try { debug('Loaded environment: ' + fullEnvPath); fs.statSync(fullEnvPath); dotenv.config({ path: fullEnvPath }); } catch (e) { debug('Could not load environment "' + fullEnvPath + '"'); } }
[ "function", "loadEnv", "(", "name", ")", "{", "var", "fullEnvPath", "=", "path", ".", "resolve", "(", "applicationRoot", ",", "'./configs/'", "+", "name", ")", ";", "try", "{", "debug", "(", "'Loaded environment: '", "+", "fullEnvPath", ")", ";", "fs", ".", "statSync", "(", "fullEnvPath", ")", ";", "dotenv", ".", "config", "(", "{", "path", ":", "fullEnvPath", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "'Could not load environment \"'", "+", "fullEnvPath", "+", "'\"'", ")", ";", "}", "}" ]
Loads a specific environment with the given name. @param {string} name Name of the environment file to load.
[ "Loads", "a", "specific", "environment", "with", "the", "given", "name", "." ]
11c5b5e024087545bce0b20c06c2be6144ba9c5e
https://github.com/Runnable/loadenv/blob/11c5b5e024087545bce0b20c06c2be6144ba9c5e/index.js#L121-L131
train
steren/attractors
ninis.js
field
function field(x, y) { var ux = 0; var uy = 0; for(var a = 0; a < attractors.length; a++) { var attractor = attractors[a]; var d2 = (x - attractor.x) * (x - attractor.x) + (y - attractor.y) * (y - attractor.y); var d = Math.sqrt(d2); var weight = attractor.weight * Math.exp( -1 * d2 / (attractor.radius * attractor.radius) ); ux += weight * (x - attractor.x) / d; uy += weight * (y - attractor.y) / d; } var norm = Math.sqrt(ux * ux + uy * uy); ux = ux / norm; uy = uy / norm; // If we are near a special attractor, add its contribution to the field if(isNearSpecialAttractor(x,y)) { var closestTextPoint = findClosestPointOnSpecialAttractor(x,y); var textUx = (closestTextPoint.specialAttractor.direction || 1) * (x - closestTextPoint.originX); var textUy = (closestTextPoint.specialAttractor.direction || 1) * (y - closestTextPoint.originY); var norm = Math.sqrt(textUx*textUx + textUy*textUy); textUx = textUx / norm; textUy = textUy / norm; // Combine fields if(closestTextPoint.specialAttractor.type == 'cos') { if(closestTextPoint.distance < closestTextPoint.specialAttractor.impactDistance) { textWeight = 0.5 * (1 + Math.cos(Math.PI * closestTextPoint.distance / (closestTextPoint.specialAttractor.impactDistance))); } else { textWeight = 0; } } else { textWeight = Math.exp( -1 * closestTextPoint.distance * closestTextPoint.distance / (closestTextPoint.specialAttractor.impactDistance * D * D) ); } ux = (1-textWeight)*ux + textWeight * textUx; uy = (1-textWeight)*uy + textWeight * textUy; } return [ux, uy]; }
javascript
function field(x, y) { var ux = 0; var uy = 0; for(var a = 0; a < attractors.length; a++) { var attractor = attractors[a]; var d2 = (x - attractor.x) * (x - attractor.x) + (y - attractor.y) * (y - attractor.y); var d = Math.sqrt(d2); var weight = attractor.weight * Math.exp( -1 * d2 / (attractor.radius * attractor.radius) ); ux += weight * (x - attractor.x) / d; uy += weight * (y - attractor.y) / d; } var norm = Math.sqrt(ux * ux + uy * uy); ux = ux / norm; uy = uy / norm; // If we are near a special attractor, add its contribution to the field if(isNearSpecialAttractor(x,y)) { var closestTextPoint = findClosestPointOnSpecialAttractor(x,y); var textUx = (closestTextPoint.specialAttractor.direction || 1) * (x - closestTextPoint.originX); var textUy = (closestTextPoint.specialAttractor.direction || 1) * (y - closestTextPoint.originY); var norm = Math.sqrt(textUx*textUx + textUy*textUy); textUx = textUx / norm; textUy = textUy / norm; // Combine fields if(closestTextPoint.specialAttractor.type == 'cos') { if(closestTextPoint.distance < closestTextPoint.specialAttractor.impactDistance) { textWeight = 0.5 * (1 + Math.cos(Math.PI * closestTextPoint.distance / (closestTextPoint.specialAttractor.impactDistance))); } else { textWeight = 0; } } else { textWeight = Math.exp( -1 * closestTextPoint.distance * closestTextPoint.distance / (closestTextPoint.specialAttractor.impactDistance * D * D) ); } ux = (1-textWeight)*ux + textWeight * textUx; uy = (1-textWeight)*uy + textWeight * textUy; } return [ux, uy]; }
[ "function", "field", "(", "x", ",", "y", ")", "{", "var", "ux", "=", "0", ";", "var", "uy", "=", "0", ";", "for", "(", "var", "a", "=", "0", ";", "a", "<", "attractors", ".", "length", ";", "a", "++", ")", "{", "var", "attractor", "=", "attractors", "[", "a", "]", ";", "var", "d2", "=", "(", "x", "-", "attractor", ".", "x", ")", "*", "(", "x", "-", "attractor", ".", "x", ")", "+", "(", "y", "-", "attractor", ".", "y", ")", "*", "(", "y", "-", "attractor", ".", "y", ")", ";", "var", "d", "=", "Math", ".", "sqrt", "(", "d2", ")", ";", "var", "weight", "=", "attractor", ".", "weight", "*", "Math", ".", "exp", "(", "-", "1", "*", "d2", "/", "(", "attractor", ".", "radius", "*", "attractor", ".", "radius", ")", ")", ";", "ux", "+=", "weight", "*", "(", "x", "-", "attractor", ".", "x", ")", "/", "d", ";", "uy", "+=", "weight", "*", "(", "y", "-", "attractor", ".", "y", ")", "/", "d", ";", "}", "var", "norm", "=", "Math", ".", "sqrt", "(", "ux", "*", "ux", "+", "uy", "*", "uy", ")", ";", "ux", "=", "ux", "/", "norm", ";", "uy", "=", "uy", "/", "norm", ";", "if", "(", "isNearSpecialAttractor", "(", "x", ",", "y", ")", ")", "{", "var", "closestTextPoint", "=", "findClosestPointOnSpecialAttractor", "(", "x", ",", "y", ")", ";", "var", "textUx", "=", "(", "closestTextPoint", ".", "specialAttractor", ".", "direction", "||", "1", ")", "*", "(", "x", "-", "closestTextPoint", ".", "originX", ")", ";", "var", "textUy", "=", "(", "closestTextPoint", ".", "specialAttractor", ".", "direction", "||", "1", ")", "*", "(", "y", "-", "closestTextPoint", ".", "originY", ")", ";", "var", "norm", "=", "Math", ".", "sqrt", "(", "textUx", "*", "textUx", "+", "textUy", "*", "textUy", ")", ";", "textUx", "=", "textUx", "/", "norm", ";", "textUy", "=", "textUy", "/", "norm", ";", "if", "(", "closestTextPoint", ".", "specialAttractor", ".", "type", "==", "'cos'", ")", "{", "if", "(", "closestTextPoint", ".", "distance", "<", "closestTextPoint", ".", "specialAttractor", ".", "impactDistance", ")", "{", "textWeight", "=", "0.5", "*", "(", "1", "+", "Math", ".", "cos", "(", "Math", ".", "PI", "*", "closestTextPoint", ".", "distance", "/", "(", "closestTextPoint", ".", "specialAttractor", ".", "impactDistance", ")", ")", ")", ";", "}", "else", "{", "textWeight", "=", "0", ";", "}", "}", "else", "{", "textWeight", "=", "Math", ".", "exp", "(", "-", "1", "*", "closestTextPoint", ".", "distance", "*", "closestTextPoint", ".", "distance", "/", "(", "closestTextPoint", ".", "specialAttractor", ".", "impactDistance", "*", "D", "*", "D", ")", ")", ";", "}", "ux", "=", "(", "1", "-", "textWeight", ")", "*", "ux", "+", "textWeight", "*", "textUx", ";", "uy", "=", "(", "1", "-", "textWeight", ")", "*", "uy", "+", "textWeight", "*", "textUy", ";", "}", "return", "[", "ux", ",", "uy", "]", ";", "}" ]
Vector of the field at a given point
[ "Vector", "of", "the", "field", "at", "a", "given", "point" ]
01cd22d17a1ae84827989d2912d829ffa2361b5d
https://github.com/steren/attractors/blob/01cd22d17a1ae84827989d2912d829ffa2361b5d/ninis.js#L264-L309
train
steren/attractors
ninis.js
createNoGoCircleSpecialAttractors
function createNoGoCircleSpecialAttractors(x, y, radius, impactDistance, type, direction) { var circleSubDiv = radius * SUBDIVISE_NOGO / 20; for( var i = 0; i < circleSubDiv; i++ ) { var specialAttractor = {}; specialAttractor.x1 = (x + radius * Math.cos(2*Math.PI / circleSubDiv * i)) * pixelRatio; specialAttractor.y1 = (y + radius * Math.sin(2*Math.PI / circleSubDiv * i)) * pixelRatio; specialAttractor.x2 = (x + radius * Math.cos(2*Math.PI / circleSubDiv * (i+1))) * pixelRatio; specialAttractor.y2 = (y + radius * Math.sin(2*Math.PI / circleSubDiv * (i+1))) * pixelRatio; specialAttractor.impactDistance = impactDistance * pixelRatio; specialAttractor.type = type; specialAttractor.direction = direction; specialAttractors.push(specialAttractor); if(DEBUG_FLAG) { drawHelperCircle(specialAttractor.x1, specialAttractor.y1, 1); } } var bbox = { topLeft: { x: (x - radius) * pixelRatio, y: (y - radius) * pixelRatio, }, bottomRight: { x: (x + radius) * pixelRatio, y: (y + radius) * pixelRatio, }, }; specialAttractorsBoundingBoxes.push(bbox); noGoBBoxes.push(bbox); }
javascript
function createNoGoCircleSpecialAttractors(x, y, radius, impactDistance, type, direction) { var circleSubDiv = radius * SUBDIVISE_NOGO / 20; for( var i = 0; i < circleSubDiv; i++ ) { var specialAttractor = {}; specialAttractor.x1 = (x + radius * Math.cos(2*Math.PI / circleSubDiv * i)) * pixelRatio; specialAttractor.y1 = (y + radius * Math.sin(2*Math.PI / circleSubDiv * i)) * pixelRatio; specialAttractor.x2 = (x + radius * Math.cos(2*Math.PI / circleSubDiv * (i+1))) * pixelRatio; specialAttractor.y2 = (y + radius * Math.sin(2*Math.PI / circleSubDiv * (i+1))) * pixelRatio; specialAttractor.impactDistance = impactDistance * pixelRatio; specialAttractor.type = type; specialAttractor.direction = direction; specialAttractors.push(specialAttractor); if(DEBUG_FLAG) { drawHelperCircle(specialAttractor.x1, specialAttractor.y1, 1); } } var bbox = { topLeft: { x: (x - radius) * pixelRatio, y: (y - radius) * pixelRatio, }, bottomRight: { x: (x + radius) * pixelRatio, y: (y + radius) * pixelRatio, }, }; specialAttractorsBoundingBoxes.push(bbox); noGoBBoxes.push(bbox); }
[ "function", "createNoGoCircleSpecialAttractors", "(", "x", ",", "y", ",", "radius", ",", "impactDistance", ",", "type", ",", "direction", ")", "{", "var", "circleSubDiv", "=", "radius", "*", "SUBDIVISE_NOGO", "/", "20", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "circleSubDiv", ";", "i", "++", ")", "{", "var", "specialAttractor", "=", "{", "}", ";", "specialAttractor", ".", "x1", "=", "(", "x", "+", "radius", "*", "Math", ".", "cos", "(", "2", "*", "Math", ".", "PI", "/", "circleSubDiv", "*", "i", ")", ")", "*", "pixelRatio", ";", "specialAttractor", ".", "y1", "=", "(", "y", "+", "radius", "*", "Math", ".", "sin", "(", "2", "*", "Math", ".", "PI", "/", "circleSubDiv", "*", "i", ")", ")", "*", "pixelRatio", ";", "specialAttractor", ".", "x2", "=", "(", "x", "+", "radius", "*", "Math", ".", "cos", "(", "2", "*", "Math", ".", "PI", "/", "circleSubDiv", "*", "(", "i", "+", "1", ")", ")", ")", "*", "pixelRatio", ";", "specialAttractor", ".", "y2", "=", "(", "y", "+", "radius", "*", "Math", ".", "sin", "(", "2", "*", "Math", ".", "PI", "/", "circleSubDiv", "*", "(", "i", "+", "1", ")", ")", ")", "*", "pixelRatio", ";", "specialAttractor", ".", "impactDistance", "=", "impactDistance", "*", "pixelRatio", ";", "specialAttractor", ".", "type", "=", "type", ";", "specialAttractor", ".", "direction", "=", "direction", ";", "specialAttractors", ".", "push", "(", "specialAttractor", ")", ";", "if", "(", "DEBUG_FLAG", ")", "{", "drawHelperCircle", "(", "specialAttractor", ".", "x1", ",", "specialAttractor", ".", "y1", ",", "1", ")", ";", "}", "}", "var", "bbox", "=", "{", "topLeft", ":", "{", "x", ":", "(", "x", "-", "radius", ")", "*", "pixelRatio", ",", "y", ":", "(", "y", "-", "radius", ")", "*", "pixelRatio", ",", "}", ",", "bottomRight", ":", "{", "x", ":", "(", "x", "+", "radius", ")", "*", "pixelRatio", ",", "y", ":", "(", "y", "+", "radius", ")", "*", "pixelRatio", ",", "}", ",", "}", ";", "specialAttractorsBoundingBoxes", ".", "push", "(", "bbox", ")", ";", "noGoBBoxes", ".", "push", "(", "bbox", ")", ";", "}" ]
Creates a circular no go zone
[ "Creates", "a", "circular", "no", "go", "zone" ]
01cd22d17a1ae84827989d2912d829ffa2361b5d
https://github.com/steren/attractors/blob/01cd22d17a1ae84827989d2912d829ffa2361b5d/ninis.js#L530-L560
train
steren/attractors
ninis.js
findClosestPointOnSpecialAttractor
function findClosestPointOnSpecialAttractor(x,y) { var nSpecialAttractor = specialAttractors.length; var currentMinDistance = 0; var currentSpecialAttractor; var ox = 0; var oy = 0; for(var a=0; a<nSpecialAttractor; a++) { var specialAttractor = specialAttractors[a]; var closestSegmentPoint = distanceToSegment(specialAttractor.x1, specialAttractor.y1, specialAttractor.x2, specialAttractor.y2, x, y); if(a == 0 || (closestSegmentPoint.distance) < currentMinDistance) { currentMinDistance = closestSegmentPoint.distance; currentSpecialAttractor = specialAttractor; ox = closestSegmentPoint.originX; oy = closestSegmentPoint.originY; } } return { distance: currentMinDistance, specialAttractor: currentSpecialAttractor, originX: ox, originY: oy } }
javascript
function findClosestPointOnSpecialAttractor(x,y) { var nSpecialAttractor = specialAttractors.length; var currentMinDistance = 0; var currentSpecialAttractor; var ox = 0; var oy = 0; for(var a=0; a<nSpecialAttractor; a++) { var specialAttractor = specialAttractors[a]; var closestSegmentPoint = distanceToSegment(specialAttractor.x1, specialAttractor.y1, specialAttractor.x2, specialAttractor.y2, x, y); if(a == 0 || (closestSegmentPoint.distance) < currentMinDistance) { currentMinDistance = closestSegmentPoint.distance; currentSpecialAttractor = specialAttractor; ox = closestSegmentPoint.originX; oy = closestSegmentPoint.originY; } } return { distance: currentMinDistance, specialAttractor: currentSpecialAttractor, originX: ox, originY: oy } }
[ "function", "findClosestPointOnSpecialAttractor", "(", "x", ",", "y", ")", "{", "var", "nSpecialAttractor", "=", "specialAttractors", ".", "length", ";", "var", "currentMinDistance", "=", "0", ";", "var", "currentSpecialAttractor", ";", "var", "ox", "=", "0", ";", "var", "oy", "=", "0", ";", "for", "(", "var", "a", "=", "0", ";", "a", "<", "nSpecialAttractor", ";", "a", "++", ")", "{", "var", "specialAttractor", "=", "specialAttractors", "[", "a", "]", ";", "var", "closestSegmentPoint", "=", "distanceToSegment", "(", "specialAttractor", ".", "x1", ",", "specialAttractor", ".", "y1", ",", "specialAttractor", ".", "x2", ",", "specialAttractor", ".", "y2", ",", "x", ",", "y", ")", ";", "if", "(", "a", "==", "0", "||", "(", "closestSegmentPoint", ".", "distance", ")", "<", "currentMinDistance", ")", "{", "currentMinDistance", "=", "closestSegmentPoint", ".", "distance", ";", "currentSpecialAttractor", "=", "specialAttractor", ";", "ox", "=", "closestSegmentPoint", ".", "originX", ";", "oy", "=", "closestSegmentPoint", ".", "originY", ";", "}", "}", "return", "{", "distance", ":", "currentMinDistance", ",", "specialAttractor", ":", "currentSpecialAttractor", ",", "originX", ":", "ox", ",", "originY", ":", "oy", "}", "}" ]
Finds the closest point to any special attractor segment
[ "Finds", "the", "closest", "point", "to", "any", "special", "attractor", "segment" ]
01cd22d17a1ae84827989d2912d829ffa2361b5d
https://github.com/steren/attractors/blob/01cd22d17a1ae84827989d2912d829ffa2361b5d/ninis.js#L683-L705
train
JohnMcLear/ep_email_notifications
static/js/ep_email.js
initPopupForm
function initPopupForm(){ var popUpIsAlreadyVisible = $('#ep_email_form_popup').is(":visible"); if(!popUpIsAlreadyVisible){ // if the popup isn't already visible var cookieVal = pad.getPadId() + "email"; if(cookie.getPref(cookieVal) !== "true"){ // if this user hasn't already subscribed askClientToEnterEmail(); // ask the client to register TODO uncomment me for a pop up } } }
javascript
function initPopupForm(){ var popUpIsAlreadyVisible = $('#ep_email_form_popup').is(":visible"); if(!popUpIsAlreadyVisible){ // if the popup isn't already visible var cookieVal = pad.getPadId() + "email"; if(cookie.getPref(cookieVal) !== "true"){ // if this user hasn't already subscribed askClientToEnterEmail(); // ask the client to register TODO uncomment me for a pop up } } }
[ "function", "initPopupForm", "(", ")", "{", "var", "popUpIsAlreadyVisible", "=", "$", "(", "'#ep_email_form_popup'", ")", ".", "is", "(", "\":visible\"", ")", ";", "if", "(", "!", "popUpIsAlreadyVisible", ")", "{", "var", "cookieVal", "=", "pad", ".", "getPadId", "(", ")", "+", "\"email\"", ";", "if", "(", "cookie", ".", "getPref", "(", "cookieVal", ")", "!==", "\"true\"", ")", "{", "askClientToEnterEmail", "(", ")", ";", "}", "}", "}" ]
Initialize the popup panel form for subscription
[ "Initialize", "the", "popup", "panel", "form", "for", "subscription" ]
68fabc173bcb44b0936690d59767bf1f927c951a
https://github.com/JohnMcLear/ep_email_notifications/blob/68fabc173bcb44b0936690d59767bf1f927c951a/static/js/ep_email.js#L153-L161
train
JohnMcLear/ep_email_notifications
static/js/ep_email.js
function(e){ $('#ep_email_form_popup').submit(function(){ sendEmailToServer('ep_email_form_popup'); return false; }); // Prepare subscription before submit form $('#ep_email_form_popup [name=ep_email_subscribe]').on('click', function(e) { $('#ep_email_form_popup [name=ep_email_option]').val('subscribe'); checkAndSend(e); }); // Prepare unsubscription before submit form $('#ep_email_form_popup [name=ep_email_unsubscribe]').on('click', function(e) { $('#ep_email_form_popup [name=ep_email_option]').val('unsubscribe'); checkAndSend(e); }); if (optionsAlreadyRecovered == false) { getDataForUserId('ep_email_form_popup'); } else { // Get datas from form in mysettings menu $('#ep_email_form_popup [name=ep_email]').val($('#ep_email_form_mysettings [name=ep_email]').val()); $('#ep_email_form_popup [name=ep_email_onStart]').prop('checked', $('#ep_email_form_mysettings [name=ep_email_onStart]').prop('checked')); $('#ep_email_form_popup [name=ep_email_onEnd]').prop('checked', $('#ep_email_form_mysettings [name=ep_email_onEnd]').prop('checked')); } }
javascript
function(e){ $('#ep_email_form_popup').submit(function(){ sendEmailToServer('ep_email_form_popup'); return false; }); // Prepare subscription before submit form $('#ep_email_form_popup [name=ep_email_subscribe]').on('click', function(e) { $('#ep_email_form_popup [name=ep_email_option]').val('subscribe'); checkAndSend(e); }); // Prepare unsubscription before submit form $('#ep_email_form_popup [name=ep_email_unsubscribe]').on('click', function(e) { $('#ep_email_form_popup [name=ep_email_option]').val('unsubscribe'); checkAndSend(e); }); if (optionsAlreadyRecovered == false) { getDataForUserId('ep_email_form_popup'); } else { // Get datas from form in mysettings menu $('#ep_email_form_popup [name=ep_email]').val($('#ep_email_form_mysettings [name=ep_email]').val()); $('#ep_email_form_popup [name=ep_email_onStart]').prop('checked', $('#ep_email_form_mysettings [name=ep_email_onStart]').prop('checked')); $('#ep_email_form_popup [name=ep_email_onEnd]').prop('checked', $('#ep_email_form_mysettings [name=ep_email_onEnd]').prop('checked')); } }
[ "function", "(", "e", ")", "{", "$", "(", "'#ep_email_form_popup'", ")", ".", "submit", "(", "function", "(", ")", "{", "sendEmailToServer", "(", "'ep_email_form_popup'", ")", ";", "return", "false", ";", "}", ")", ";", "$", "(", "'#ep_email_form_popup [name=ep_email_subscribe]'", ")", ".", "on", "(", "'click'", ",", "function", "(", "e", ")", "{", "$", "(", "'#ep_email_form_popup [name=ep_email_option]'", ")", ".", "val", "(", "'subscribe'", ")", ";", "checkAndSend", "(", "e", ")", ";", "}", ")", ";", "$", "(", "'#ep_email_form_popup [name=ep_email_unsubscribe]'", ")", ".", "on", "(", "'click'", ",", "function", "(", "e", ")", "{", "$", "(", "'#ep_email_form_popup [name=ep_email_option]'", ")", ".", "val", "(", "'unsubscribe'", ")", ";", "checkAndSend", "(", "e", ")", ";", "}", ")", ";", "if", "(", "optionsAlreadyRecovered", "==", "false", ")", "{", "getDataForUserId", "(", "'ep_email_form_popup'", ")", ";", "}", "else", "{", "$", "(", "'#ep_email_form_popup [name=ep_email]'", ")", ".", "val", "(", "$", "(", "'#ep_email_form_mysettings [name=ep_email]'", ")", ".", "val", "(", ")", ")", ";", "$", "(", "'#ep_email_form_popup [name=ep_email_onStart]'", ")", ".", "prop", "(", "'checked'", ",", "$", "(", "'#ep_email_form_mysettings [name=ep_email_onStart]'", ")", ".", "prop", "(", "'checked'", ")", ")", ";", "$", "(", "'#ep_email_form_popup [name=ep_email_onEnd]'", ")", ".", "prop", "(", "'checked'", ",", "$", "(", "'#ep_email_form_mysettings [name=ep_email_onEnd]'", ")", ".", "prop", "(", "'checked'", ")", ")", ";", "}", "}" ]
the function to bind to the form
[ "the", "function", "to", "bind", "to", "the", "form" ]
68fabc173bcb44b0936690d59767bf1f927c951a
https://github.com/JohnMcLear/ep_email_notifications/blob/68fabc173bcb44b0936690d59767bf1f927c951a/static/js/ep_email.js#L190-L216
train
JohnMcLear/ep_email_notifications
static/js/ep_email.js
checkAndSend
function checkAndSend(e) { var formName = $(e.currentTarget.parentNode).attr('id'); var email = $('#' + formName + ' [name=ep_email]').val(); if (email && $('#' + formName + ' [name=ep_email_option]').val() == 'subscribe' && !$('#' + formName + ' [name=ep_email_onStart]').is(':checked') && !$('#' + formName + ' [name=ep_email_onEnd]').is(':checked')) { $.gritter.add({ // (string | mandatory) the heading of the notification title: window._('ep_email_notifications.titleGritterError'), // (string | mandatory) the text inside the notification text: window._('ep_email_notifications.msgOptionsNotChecked'), // (string | optional) add a class name to the gritter msg class_name: "emailNotificationsSubscrOptionsMissing" }); } else if (email) { $('#' + formName).submit(); } return false; }
javascript
function checkAndSend(e) { var formName = $(e.currentTarget.parentNode).attr('id'); var email = $('#' + formName + ' [name=ep_email]').val(); if (email && $('#' + formName + ' [name=ep_email_option]').val() == 'subscribe' && !$('#' + formName + ' [name=ep_email_onStart]').is(':checked') && !$('#' + formName + ' [name=ep_email_onEnd]').is(':checked')) { $.gritter.add({ // (string | mandatory) the heading of the notification title: window._('ep_email_notifications.titleGritterError'), // (string | mandatory) the text inside the notification text: window._('ep_email_notifications.msgOptionsNotChecked'), // (string | optional) add a class name to the gritter msg class_name: "emailNotificationsSubscrOptionsMissing" }); } else if (email) { $('#' + formName).submit(); } return false; }
[ "function", "checkAndSend", "(", "e", ")", "{", "var", "formName", "=", "$", "(", "e", ".", "currentTarget", ".", "parentNode", ")", ".", "attr", "(", "'id'", ")", ";", "var", "email", "=", "$", "(", "'#'", "+", "formName", "+", "' [name=ep_email]'", ")", ".", "val", "(", ")", ";", "if", "(", "email", "&&", "$", "(", "'#'", "+", "formName", "+", "' [name=ep_email_option]'", ")", ".", "val", "(", ")", "==", "'subscribe'", "&&", "!", "$", "(", "'#'", "+", "formName", "+", "' [name=ep_email_onStart]'", ")", ".", "is", "(", "':checked'", ")", "&&", "!", "$", "(", "'#'", "+", "formName", "+", "' [name=ep_email_onEnd]'", ")", ".", "is", "(", "':checked'", ")", ")", "{", "$", ".", "gritter", ".", "add", "(", "{", "title", ":", "window", ".", "_", "(", "'ep_email_notifications.titleGritterError'", ")", ",", "text", ":", "window", ".", "_", "(", "'ep_email_notifications.msgOptionsNotChecked'", ")", ",", "class_name", ":", "\"emailNotificationsSubscrOptionsMissing\"", "}", ")", ";", "}", "else", "if", "(", "email", ")", "{", "$", "(", "'#'", "+", "formName", ")", ".", "submit", "(", ")", ";", "}", "return", "false", ";", "}" ]
Control options before submitting the form
[ "Control", "options", "before", "submitting", "the", "form" ]
68fabc173bcb44b0936690d59767bf1f927c951a
https://github.com/JohnMcLear/ep_email_notifications/blob/68fabc173bcb44b0936690d59767bf1f927c951a/static/js/ep_email.js#L223-L243
train
JohnMcLear/ep_email_notifications
static/js/ep_email.js
sendEmailToServer
function sendEmailToServer(formName){ var email = $('#' + formName + ' [name=ep_email]').val(); var userId = pad.getUserId(); var message = {}; message.type = 'USERINFO_UPDATE'; message.userInfo = {}; message.padId = pad.getPadId(); message.userInfo.email = email; message.userInfo.email_option = $('#' + formName + ' [name=ep_email_option]').val(); message.userInfo.email_onStart = $('#' + formName + ' [name=ep_email_onStart]').is(':checked'); message.userInfo.email_onEnd = $('#' + formName + ' [name=ep_email_onEnd]').is(':checked'); message.userInfo.formName = formName; message.userInfo.userId = userId; if(email){ pad.collabClient.sendMessage(message); } }
javascript
function sendEmailToServer(formName){ var email = $('#' + formName + ' [name=ep_email]').val(); var userId = pad.getUserId(); var message = {}; message.type = 'USERINFO_UPDATE'; message.userInfo = {}; message.padId = pad.getPadId(); message.userInfo.email = email; message.userInfo.email_option = $('#' + formName + ' [name=ep_email_option]').val(); message.userInfo.email_onStart = $('#' + formName + ' [name=ep_email_onStart]').is(':checked'); message.userInfo.email_onEnd = $('#' + formName + ' [name=ep_email_onEnd]').is(':checked'); message.userInfo.formName = formName; message.userInfo.userId = userId; if(email){ pad.collabClient.sendMessage(message); } }
[ "function", "sendEmailToServer", "(", "formName", ")", "{", "var", "email", "=", "$", "(", "'#'", "+", "formName", "+", "' [name=ep_email]'", ")", ".", "val", "(", ")", ";", "var", "userId", "=", "pad", ".", "getUserId", "(", ")", ";", "var", "message", "=", "{", "}", ";", "message", ".", "type", "=", "'USERINFO_UPDATE'", ";", "message", ".", "userInfo", "=", "{", "}", ";", "message", ".", "padId", "=", "pad", ".", "getPadId", "(", ")", ";", "message", ".", "userInfo", ".", "email", "=", "email", ";", "message", ".", "userInfo", ".", "email_option", "=", "$", "(", "'#'", "+", "formName", "+", "' [name=ep_email_option]'", ")", ".", "val", "(", ")", ";", "message", ".", "userInfo", ".", "email_onStart", "=", "$", "(", "'#'", "+", "formName", "+", "' [name=ep_email_onStart]'", ")", ".", "is", "(", "':checked'", ")", ";", "message", ".", "userInfo", ".", "email_onEnd", "=", "$", "(", "'#'", "+", "formName", "+", "' [name=ep_email_onEnd]'", ")", ".", "is", "(", "':checked'", ")", ";", "message", ".", "userInfo", ".", "formName", "=", "formName", ";", "message", ".", "userInfo", ".", "userId", "=", "userId", ";", "if", "(", "email", ")", "{", "pad", ".", "collabClient", ".", "sendMessage", "(", "message", ")", ";", "}", "}" ]
Ask the server to register the email
[ "Ask", "the", "server", "to", "register", "the", "email" ]
68fabc173bcb44b0936690d59767bf1f927c951a
https://github.com/JohnMcLear/ep_email_notifications/blob/68fabc173bcb44b0936690d59767bf1f927c951a/static/js/ep_email.js#L248-L264
train
JohnMcLear/ep_email_notifications
static/js/ep_email.js
getDataForUserId
function getDataForUserId(formName) { var userId = pad.getUserId(); var message = {}; message.type = 'USERINFO_GET'; message.padId = pad.getPadId(); message.userInfo = {}; message.userInfo.userId = userId; message.userInfo.formName = formName; pad.collabClient.sendMessage(message); }
javascript
function getDataForUserId(formName) { var userId = pad.getUserId(); var message = {}; message.type = 'USERINFO_GET'; message.padId = pad.getPadId(); message.userInfo = {}; message.userInfo.userId = userId; message.userInfo.formName = formName; pad.collabClient.sendMessage(message); }
[ "function", "getDataForUserId", "(", "formName", ")", "{", "var", "userId", "=", "pad", ".", "getUserId", "(", ")", ";", "var", "message", "=", "{", "}", ";", "message", ".", "type", "=", "'USERINFO_GET'", ";", "message", ".", "padId", "=", "pad", ".", "getPadId", "(", ")", ";", "message", ".", "userInfo", "=", "{", "}", ";", "message", ".", "userInfo", ".", "userId", "=", "userId", ";", "message", ".", "userInfo", ".", "formName", "=", "formName", ";", "pad", ".", "collabClient", ".", "sendMessage", "(", "message", ")", ";", "}" ]
Thanks to the userId, we can get back from the Db the options set for this user and fill the fields with them
[ "Thanks", "to", "the", "userId", "we", "can", "get", "back", "from", "the", "Db", "the", "options", "set", "for", "this", "user", "and", "fill", "the", "fields", "with", "them" ]
68fabc173bcb44b0936690d59767bf1f927c951a
https://github.com/JohnMcLear/ep_email_notifications/blob/68fabc173bcb44b0936690d59767bf1f927c951a/static/js/ep_email.js#L270-L280
train
JohnMcLear/ep_email_notifications
static/js/ep_email.js
showAlreadyRegistered
function showAlreadyRegistered(type){ if (type == "malformedEmail") { var msg = window._('ep_email_notifications.msgEmailMalformed'); } else if (type == "alreadyRegistered") { var msg = window._('ep_email_notifications.msgAlreadySubscr'); } else { var msg = window._('ep_email_notifications.msgUnknownErr'); } $.gritter.add({ // (string | mandatory) the heading of the notification title: window._('ep_email_notifications.titleGritterSubscr'), // (string | mandatory) the text inside the notification text: msg, // (int | optional) the time you want it to be alive for before fading out time: 7000, // (string | optional) add a class name to the gritter msg class_name: "emailNotificationsSubscrResponseBad" }); }
javascript
function showAlreadyRegistered(type){ if (type == "malformedEmail") { var msg = window._('ep_email_notifications.msgEmailMalformed'); } else if (type == "alreadyRegistered") { var msg = window._('ep_email_notifications.msgAlreadySubscr'); } else { var msg = window._('ep_email_notifications.msgUnknownErr'); } $.gritter.add({ // (string | mandatory) the heading of the notification title: window._('ep_email_notifications.titleGritterSubscr'), // (string | mandatory) the text inside the notification text: msg, // (int | optional) the time you want it to be alive for before fading out time: 7000, // (string | optional) add a class name to the gritter msg class_name: "emailNotificationsSubscrResponseBad" }); }
[ "function", "showAlreadyRegistered", "(", "type", ")", "{", "if", "(", "type", "==", "\"malformedEmail\"", ")", "{", "var", "msg", "=", "window", ".", "_", "(", "'ep_email_notifications.msgEmailMalformed'", ")", ";", "}", "else", "if", "(", "type", "==", "\"alreadyRegistered\"", ")", "{", "var", "msg", "=", "window", ".", "_", "(", "'ep_email_notifications.msgAlreadySubscr'", ")", ";", "}", "else", "{", "var", "msg", "=", "window", ".", "_", "(", "'ep_email_notifications.msgUnknownErr'", ")", ";", "}", "$", ".", "gritter", ".", "add", "(", "{", "title", ":", "window", ".", "_", "(", "'ep_email_notifications.titleGritterSubscr'", ")", ",", "text", ":", "msg", ",", "time", ":", "7000", ",", "class_name", ":", "\"emailNotificationsSubscrResponseBad\"", "}", ")", ";", "}" ]
The client already registered for emails on this pad so notify the UI
[ "The", "client", "already", "registered", "for", "emails", "on", "this", "pad", "so", "notify", "the", "UI" ]
68fabc173bcb44b0936690d59767bf1f927c951a
https://github.com/JohnMcLear/ep_email_notifications/blob/68fabc173bcb44b0936690d59767bf1f927c951a/static/js/ep_email.js#L305-L324
train
base/base-app
lib/cli.js
resolveBase
function resolveBase(app) { const paths = [ { name: 'base', path: path.resolve(cwd, 'node_modules/base') }, { name: 'base-app', path: path.resolve(cwd, 'node_modules/base-app') }, { name: 'assemble-core', path: path.resolve(cwd, 'node_modules/assemble-core') }, { name: 'assemble', path: path.resolve(cwd, 'node_modules/assemble') }, { name: 'generate', path: path.resolve(cwd, 'node_modules/generate') }, { name: 'update', path: path.resolve(cwd, 'node_modules/update') }, { name: 'verb', path: path.resolve(cwd, 'node_modules/verb') }, { name: 'core', path: path.resolve(__dirname, '..') } ]; for (const file of paths) { if (opts.app && file.name === opts.app && (app = resolveApp(file))) { return app; } } if (opts.app) { app = resolveApp({ name: opts.app, path: path.resolve(cwd, 'node_modules', opts.app) }); } return app; }
javascript
function resolveBase(app) { const paths = [ { name: 'base', path: path.resolve(cwd, 'node_modules/base') }, { name: 'base-app', path: path.resolve(cwd, 'node_modules/base-app') }, { name: 'assemble-core', path: path.resolve(cwd, 'node_modules/assemble-core') }, { name: 'assemble', path: path.resolve(cwd, 'node_modules/assemble') }, { name: 'generate', path: path.resolve(cwd, 'node_modules/generate') }, { name: 'update', path: path.resolve(cwd, 'node_modules/update') }, { name: 'verb', path: path.resolve(cwd, 'node_modules/verb') }, { name: 'core', path: path.resolve(__dirname, '..') } ]; for (const file of paths) { if (opts.app && file.name === opts.app && (app = resolveApp(file))) { return app; } } if (opts.app) { app = resolveApp({ name: opts.app, path: path.resolve(cwd, 'node_modules', opts.app) }); } return app; }
[ "function", "resolveBase", "(", "app", ")", "{", "const", "paths", "=", "[", "{", "name", ":", "'base'", ",", "path", ":", "path", ".", "resolve", "(", "cwd", ",", "'node_modules/base'", ")", "}", ",", "{", "name", ":", "'base-app'", ",", "path", ":", "path", ".", "resolve", "(", "cwd", ",", "'node_modules/base-app'", ")", "}", ",", "{", "name", ":", "'assemble-core'", ",", "path", ":", "path", ".", "resolve", "(", "cwd", ",", "'node_modules/assemble-core'", ")", "}", ",", "{", "name", ":", "'assemble'", ",", "path", ":", "path", ".", "resolve", "(", "cwd", ",", "'node_modules/assemble'", ")", "}", ",", "{", "name", ":", "'generate'", ",", "path", ":", "path", ".", "resolve", "(", "cwd", ",", "'node_modules/generate'", ")", "}", ",", "{", "name", ":", "'update'", ",", "path", ":", "path", ".", "resolve", "(", "cwd", ",", "'node_modules/update'", ")", "}", ",", "{", "name", ":", "'verb'", ",", "path", ":", "path", ".", "resolve", "(", "cwd", ",", "'node_modules/verb'", ")", "}", ",", "{", "name", ":", "'core'", ",", "path", ":", "path", ".", "resolve", "(", "__dirname", ",", "'..'", ")", "}", "]", ";", "for", "(", "const", "file", "of", "paths", ")", "{", "if", "(", "opts", ".", "app", "&&", "file", ".", "name", "===", "opts", ".", "app", "&&", "(", "app", "=", "resolveApp", "(", "file", ")", ")", ")", "{", "return", "app", ";", "}", "}", "if", "(", "opts", ".", "app", ")", "{", "app", "=", "resolveApp", "(", "{", "name", ":", "opts", ".", "app", ",", "path", ":", "path", ".", "resolve", "(", "cwd", ",", "'node_modules'", ",", "opts", ".", "app", ")", "}", ")", ";", "}", "return", "app", ";", "}" ]
Resolve the "app" to use
[ "Resolve", "the", "app", "to", "use" ]
f070c91573d6c8c98fbccf24fcffd93741319575
https://github.com/base/base-app/blob/f070c91573d6c8c98fbccf24fcffd93741319575/lib/cli.js#L123-L148
train
base/base-app
lib/cli.js
resolveApp
function resolveApp(file) { if (fs.existsSync(file.path)) { const Base = require(file.path); const base = new Base(null, opts); base.define('log', log); if (typeof base.name === 'undefined') { base.name = file.name; } // if this is not an instance of base-app, load // app-base plugins onto the instance // if (file.name !== 'core') { // Core.plugins(base); // } return base; } }
javascript
function resolveApp(file) { if (fs.existsSync(file.path)) { const Base = require(file.path); const base = new Base(null, opts); base.define('log', log); if (typeof base.name === 'undefined') { base.name = file.name; } // if this is not an instance of base-app, load // app-base plugins onto the instance // if (file.name !== 'core') { // Core.plugins(base); // } return base; } }
[ "function", "resolveApp", "(", "file", ")", "{", "if", "(", "fs", ".", "existsSync", "(", "file", ".", "path", ")", ")", "{", "const", "Base", "=", "require", "(", "file", ".", "path", ")", ";", "const", "base", "=", "new", "Base", "(", "null", ",", "opts", ")", ";", "base", ".", "define", "(", "'log'", ",", "log", ")", ";", "if", "(", "typeof", "base", ".", "name", "===", "'undefined'", ")", "{", "base", ".", "name", "=", "file", ".", "name", ";", "}", "return", "base", ";", "}", "}" ]
Try to resolve the path to the given module, require it, and create an instance
[ "Try", "to", "resolve", "the", "path", "to", "the", "given", "module", "require", "it", "and", "create", "an", "instance" ]
f070c91573d6c8c98fbccf24fcffd93741319575
https://github.com/base/base-app/blob/f070c91573d6c8c98fbccf24fcffd93741319575/lib/cli.js#L155-L172
train
juttle/juttle-viz
src/lib/layout/simple.js
function(svg, options) { // the svg element to render charts to this._svg = svg; this._attributes = options || {}; // outer margins this._margin = { top: 20, bottom: 75, left: this._attributes.yScales.primary.displayOnAxis === 'left' ? 75 : 25, right: this._attributes.yScales.primary.displayOnAxis === 'left' ? 25 : 75 }; }
javascript
function(svg, options) { // the svg element to render charts to this._svg = svg; this._attributes = options || {}; // outer margins this._margin = { top: 20, bottom: 75, left: this._attributes.yScales.primary.displayOnAxis === 'left' ? 75 : 25, right: this._attributes.yScales.primary.displayOnAxis === 'left' ? 25 : 75 }; }
[ "function", "(", "svg", ",", "options", ")", "{", "this", ".", "_svg", "=", "svg", ";", "this", ".", "_attributes", "=", "options", "||", "{", "}", ";", "this", ".", "_margin", "=", "{", "top", ":", "20", ",", "bottom", ":", "75", ",", "left", ":", "this", ".", "_attributes", ".", "yScales", ".", "primary", ".", "displayOnAxis", "===", "'left'", "?", "75", ":", "25", ",", "right", ":", "this", ".", "_attributes", ".", "yScales", ".", "primary", ".", "displayOnAxis", "===", "'left'", "?", "25", ":", "75", "}", ";", "}" ]
Single Chart Layout @param {Object} svg the element @param {Object} options
[ "Single", "Chart", "Layout" ]
834d13a66256d9c9177f46968b0ef05b8143e762
https://github.com/juttle/juttle-viz/blob/834d13a66256d9c9177f46968b0ef05b8143e762/src/lib/layout/simple.js#L6-L20
train
nexdrew/all-stars
index.js
allStars
function allStars (query) { if (typeof query === 'string') return lookupString(query) else if (Array.isArray(query)) return lookupArray(query) else if (typeof query === 'object') return lookupObject(query) return null }
javascript
function allStars (query) { if (typeof query === 'string') return lookupString(query) else if (Array.isArray(query)) return lookupArray(query) else if (typeof query === 'object') return lookupObject(query) return null }
[ "function", "allStars", "(", "query", ")", "{", "if", "(", "typeof", "query", "===", "'string'", ")", "return", "lookupString", "(", "query", ")", "else", "if", "(", "Array", ".", "isArray", "(", "query", ")", ")", "return", "lookupArray", "(", "query", ")", "else", "if", "(", "typeof", "query", "===", "'object'", ")", "return", "lookupObject", "(", "query", ")", "return", "null", "}" ]
main API for querying
[ "main", "API", "for", "querying" ]
039c10840f95f6a099522aa494aa0734b3c9a5ba
https://github.com/nexdrew/all-stars/blob/039c10840f95f6a099522aa494aa0734b3c9a5ba/index.js#L12-L17
train
RiseVision/old-rise-js
lib/api/parseTransaction.js
ParseOfflineRequest
function ParseOfflineRequest (requestType, options) { if (!(this instanceof ParseOfflineRequest)) { return new ParseOfflineRequest(requestType, options); } this.requestType = requestType; this.options = options; this.requestMethod = this.httpGETPUTorPOST(requestType); this.params = ''; return this; }
javascript
function ParseOfflineRequest (requestType, options) { if (!(this instanceof ParseOfflineRequest)) { return new ParseOfflineRequest(requestType, options); } this.requestType = requestType; this.options = options; this.requestMethod = this.httpGETPUTorPOST(requestType); this.params = ''; return this; }
[ "function", "ParseOfflineRequest", "(", "requestType", ",", "options", ")", "{", "if", "(", "!", "(", "this", "instanceof", "ParseOfflineRequest", ")", ")", "{", "return", "new", "ParseOfflineRequest", "(", "requestType", ",", "options", ")", ";", "}", "this", ".", "requestType", "=", "requestType", ";", "this", ".", "options", "=", "options", ";", "this", ".", "requestMethod", "=", "this", ".", "httpGETPUTorPOST", "(", "requestType", ")", ";", "this", ".", "params", "=", "''", ";", "return", "this", ";", "}" ]
ParseOfflineRequest module provides automatic routing of new transaction requests which can be signed locally, and then broadcast without any passphrases being transmitted. @method ParseOfflineRequest @param requestType @param options @main lisk
[ "ParseOfflineRequest", "module", "provides", "automatic", "routing", "of", "new", "transaction", "requests", "which", "can", "be", "signed", "locally", "and", "then", "broadcast", "without", "any", "passphrases", "being", "transmitted", "." ]
71c5f60948439ef41fda8faba9bc0185808b9173
https://github.com/RiseVision/old-rise-js/blob/71c5f60948439ef41fda8faba9bc0185808b9173/lib/api/parseTransaction.js#L35-L46
train
pandell/gulp-jslint-simple
lib/run.js
requireJslint
function requireJslint(jslintFileName) { /*jslint stupid: true */// JSLint doesn't like "*Sync" functions, but in this require-like function async would be overkill var jslintCode = bufferToScript( fs.readFileSync( path.join(__dirname, jslintFileName) ) ); /*jslint stupid: false */ var sandbox = {}; vm.runInNewContext(jslintCode, sandbox, jslintFileName); return sandbox.JSLINT; }
javascript
function requireJslint(jslintFileName) { /*jslint stupid: true */// JSLint doesn't like "*Sync" functions, but in this require-like function async would be overkill var jslintCode = bufferToScript( fs.readFileSync( path.join(__dirname, jslintFileName) ) ); /*jslint stupid: false */ var sandbox = {}; vm.runInNewContext(jslintCode, sandbox, jslintFileName); return sandbox.JSLINT; }
[ "function", "requireJslint", "(", "jslintFileName", ")", "{", "var", "jslintCode", "=", "bufferToScript", "(", "fs", ".", "readFileSync", "(", "path", ".", "join", "(", "__dirname", ",", "jslintFileName", ")", ")", ")", ";", "var", "sandbox", "=", "{", "}", ";", "vm", ".", "runInNewContext", "(", "jslintCode", ",", "sandbox", ",", "jslintFileName", ")", ";", "return", "sandbox", ".", "JSLINT", ";", "}" ]
Return JSLINT loaded from the specified file. File name is assumed to be relative to this script's directory.
[ "Return", "JSLINT", "loaded", "from", "the", "specified", "file", ".", "File", "name", "is", "assumed", "to", "be", "relative", "to", "this", "script", "s", "directory", "." ]
d1f125aaacb60e6d9b108dc15281fed3759b9e51
https://github.com/pandell/gulp-jslint-simple/blob/d1f125aaacb60e6d9b108dc15281fed3759b9e51/lib/run.js#L32-L44
train
localvoid/pck
examples/js/hn/pck.js
unpckItem
function unpckItem(reader) { const bitSet0 = pck.readU8(reader); const time = pck.readU32(reader); const descendants = pck.readUVar(reader); const id = pck.readUVar(reader); const score = pck.readUVar(reader); const by = pck.readUtf8(reader); const title = pck.readUtf8(reader); const url = (bitSet0 & (1 << 1)) !== 0 ? pck.readUtf8(reader) : ""; const kids = (bitSet0 & (1 << 0)) !== 0 ? pck.readArray(reader, pck.readUVar) : null; return new Item( by, descendants, id, kids, score, time, title, url, ); }
javascript
function unpckItem(reader) { const bitSet0 = pck.readU8(reader); const time = pck.readU32(reader); const descendants = pck.readUVar(reader); const id = pck.readUVar(reader); const score = pck.readUVar(reader); const by = pck.readUtf8(reader); const title = pck.readUtf8(reader); const url = (bitSet0 & (1 << 1)) !== 0 ? pck.readUtf8(reader) : ""; const kids = (bitSet0 & (1 << 0)) !== 0 ? pck.readArray(reader, pck.readUVar) : null; return new Item( by, descendants, id, kids, score, time, title, url, ); }
[ "function", "unpckItem", "(", "reader", ")", "{", "const", "bitSet0", "=", "pck", ".", "readU8", "(", "reader", ")", ";", "const", "time", "=", "pck", ".", "readU32", "(", "reader", ")", ";", "const", "descendants", "=", "pck", ".", "readUVar", "(", "reader", ")", ";", "const", "id", "=", "pck", ".", "readUVar", "(", "reader", ")", ";", "const", "score", "=", "pck", ".", "readUVar", "(", "reader", ")", ";", "const", "by", "=", "pck", ".", "readUtf8", "(", "reader", ")", ";", "const", "title", "=", "pck", ".", "readUtf8", "(", "reader", ")", ";", "const", "url", "=", "(", "bitSet0", "&", "(", "1", "<<", "1", ")", ")", "!==", "0", "?", "pck", ".", "readUtf8", "(", "reader", ")", ":", "\"\"", ";", "const", "kids", "=", "(", "bitSet0", "&", "(", "1", "<<", "0", ")", ")", "!==", "0", "?", "pck", ".", "readArray", "(", "reader", ",", "pck", ".", "readUVar", ")", ":", "null", ";", "return", "new", "Item", "(", "by", ",", "descendants", ",", "id", ",", "kids", ",", "score", ",", "time", ",", "title", ",", "url", ",", ")", ";", "}" ]
unpckItem is an automatically generated deserialization function. @param reader Read buffer. @returns Deserialized object.
[ "unpckItem", "is", "an", "automatically", "generated", "deserialization", "function", "." ]
95c98bab06e919a0277e696965b6888ca7c245c4
https://github.com/localvoid/pck/blob/95c98bab06e919a0277e696965b6888ca7c245c4/examples/js/hn/pck.js#L60-L81
train
taoyuan/sira-core
lib/accessing.js
AccessContext
function AccessContext(context, app) { if (!(this instanceof AccessContext)) { return new AccessContext(context, app); } context = context || {}; this.app = app; this.principals = context.principals || []; var model = context.model; model = ('string' === typeof model) ? app.model(model) : model; this.model = model; this.modelName = model && model.modelName; this.modelId = context.id || context.modelId; this.property = context.property || AccessContext.ALL; this.method = context.method; this.sharedMethod = context.sharedMethod; this.sharedClass = this.sharedMethod && this.sharedMethod.sharedClass; if(this.sharedMethod) { this.methodNames = this.sharedMethod.aliases.concat([this.sharedMethod.name]); } else { this.methodNames = []; } if(this.sharedMethod) { this.accessType = sec.getAccessTypeForMethod(this.sharedMethod); } this.accessType = context.accessType || AccessContext.ALL; this.accessToken = context.accessToken || app.model('AccessToken').ANONYMOUS; var principalType = context.principalType || Principal.USER; var principalId = context.principalId || undefined; var principalName = context.principalName || undefined; if (principalId) { this.addPrincipal(principalType, principalId, principalName); } var token = this.accessToken || {}; if (token.userId) { this.addPrincipal(Principal.USER, token.userId); } if (token.appId) { this.addPrincipal(Principal.APPLICATION, token.appId); } this.remoteContext = context.remoteContext; }
javascript
function AccessContext(context, app) { if (!(this instanceof AccessContext)) { return new AccessContext(context, app); } context = context || {}; this.app = app; this.principals = context.principals || []; var model = context.model; model = ('string' === typeof model) ? app.model(model) : model; this.model = model; this.modelName = model && model.modelName; this.modelId = context.id || context.modelId; this.property = context.property || AccessContext.ALL; this.method = context.method; this.sharedMethod = context.sharedMethod; this.sharedClass = this.sharedMethod && this.sharedMethod.sharedClass; if(this.sharedMethod) { this.methodNames = this.sharedMethod.aliases.concat([this.sharedMethod.name]); } else { this.methodNames = []; } if(this.sharedMethod) { this.accessType = sec.getAccessTypeForMethod(this.sharedMethod); } this.accessType = context.accessType || AccessContext.ALL; this.accessToken = context.accessToken || app.model('AccessToken').ANONYMOUS; var principalType = context.principalType || Principal.USER; var principalId = context.principalId || undefined; var principalName = context.principalName || undefined; if (principalId) { this.addPrincipal(principalType, principalId, principalName); } var token = this.accessToken || {}; if (token.userId) { this.addPrincipal(Principal.USER, token.userId); } if (token.appId) { this.addPrincipal(Principal.APPLICATION, token.appId); } this.remoteContext = context.remoteContext; }
[ "function", "AccessContext", "(", "context", ",", "app", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AccessContext", ")", ")", "{", "return", "new", "AccessContext", "(", "context", ",", "app", ")", ";", "}", "context", "=", "context", "||", "{", "}", ";", "this", ".", "app", "=", "app", ";", "this", ".", "principals", "=", "context", ".", "principals", "||", "[", "]", ";", "var", "model", "=", "context", ".", "model", ";", "model", "=", "(", "'string'", "===", "typeof", "model", ")", "?", "app", ".", "model", "(", "model", ")", ":", "model", ";", "this", ".", "model", "=", "model", ";", "this", ".", "modelName", "=", "model", "&&", "model", ".", "modelName", ";", "this", ".", "modelId", "=", "context", ".", "id", "||", "context", ".", "modelId", ";", "this", ".", "property", "=", "context", ".", "property", "||", "AccessContext", ".", "ALL", ";", "this", ".", "method", "=", "context", ".", "method", ";", "this", ".", "sharedMethod", "=", "context", ".", "sharedMethod", ";", "this", ".", "sharedClass", "=", "this", ".", "sharedMethod", "&&", "this", ".", "sharedMethod", ".", "sharedClass", ";", "if", "(", "this", ".", "sharedMethod", ")", "{", "this", ".", "methodNames", "=", "this", ".", "sharedMethod", ".", "aliases", ".", "concat", "(", "[", "this", ".", "sharedMethod", ".", "name", "]", ")", ";", "}", "else", "{", "this", ".", "methodNames", "=", "[", "]", ";", "}", "if", "(", "this", ".", "sharedMethod", ")", "{", "this", ".", "accessType", "=", "sec", ".", "getAccessTypeForMethod", "(", "this", ".", "sharedMethod", ")", ";", "}", "this", ".", "accessType", "=", "context", ".", "accessType", "||", "AccessContext", ".", "ALL", ";", "this", ".", "accessToken", "=", "context", ".", "accessToken", "||", "app", ".", "model", "(", "'AccessToken'", ")", ".", "ANONYMOUS", ";", "var", "principalType", "=", "context", ".", "principalType", "||", "Principal", ".", "USER", ";", "var", "principalId", "=", "context", ".", "principalId", "||", "undefined", ";", "var", "principalName", "=", "context", ".", "principalName", "||", "undefined", ";", "if", "(", "principalId", ")", "{", "this", ".", "addPrincipal", "(", "principalType", ",", "principalId", ",", "principalName", ")", ";", "}", "var", "token", "=", "this", ".", "accessToken", "||", "{", "}", ";", "if", "(", "token", ".", "userId", ")", "{", "this", ".", "addPrincipal", "(", "Principal", ".", "USER", ",", "token", ".", "userId", ")", ";", "}", "if", "(", "token", ".", "appId", ")", "{", "this", ".", "addPrincipal", "(", "Principal", ".", "APPLICATION", ",", "token", ".", "appId", ")", ";", "}", "this", ".", "remoteContext", "=", "context", ".", "remoteContext", ";", "}" ]
Access context represents the context for a request to access protected resources @class @param {Object} context The context object @param {Principal[]} context.principals An array of principals @param {Function} context.model The model class @param {String} context.modelName The model name @param {String} context.modelId The model id @param {String} context.property The model property/method/relation name @param {String} context.method The model method to be invoked @param {String} context.accessType The access type @param {Object} context.accessToken The access token @param {Application} app The sira app instance @returns {AccessContext} @constructor
[ "Access", "context", "represents", "the", "context", "for", "a", "request", "to", "access", "protected", "resources" ]
34025751c4a2427535e67b838af05fca2b5fe250
https://github.com/taoyuan/sira-core/blob/34025751c4a2427535e67b838af05fca2b5fe250/lib/accessing.js#L25-L74
train
taoyuan/sira-core
lib/accessing.js
Principal
function Principal(type, id, name) { if (!(this instanceof Principal)) { return new Principal(type, id, name); } this.type = type; this.id = id; this.name = name; }
javascript
function Principal(type, id, name) { if (!(this instanceof Principal)) { return new Principal(type, id, name); } this.type = type; this.id = id; this.name = name; }
[ "function", "Principal", "(", "type", ",", "id", ",", "name", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Principal", ")", ")", "{", "return", "new", "Principal", "(", "type", ",", "id", ",", "name", ")", ";", "}", "this", ".", "type", "=", "type", ";", "this", ".", "id", "=", "id", ";", "this", ".", "name", "=", "name", ";", "}" ]
This class represents the abstract notion of a principal, which can be used to represent any entity, such as an individual, a corporation, and a login id @param {String} type The principal type @param {*} id The princiapl id @param {String} [name] The principal name @returns {Principal} @class
[ "This", "class", "represents", "the", "abstract", "notion", "of", "a", "principal", "which", "can", "be", "used", "to", "represent", "any", "entity", "such", "as", "an", "individual", "a", "corporation", "and", "a", "login", "id" ]
34025751c4a2427535e67b838af05fca2b5fe250
https://github.com/taoyuan/sira-core/blob/34025751c4a2427535e67b838af05fca2b5fe250/lib/accessing.js#L193-L200
train
taoyuan/sira-core
lib/accessing.js
AccessRequest
function AccessRequest(model, property, accessType, permission, methodNames) { if (!(this instanceof AccessRequest)) { return new AccessRequest(model, property, accessType, permission, methodNames); } if (arguments.length === 1 && typeof model === 'object') { // The argument is an object that contains all required properties var obj = model || {}; this.model = obj.model || AccessContext.ALL; this.property = obj.property || AccessContext.ALL; this.accessType = obj.accessType || AccessContext.ALL; this.permission = obj.permission || AccessContext.DEFAULT; this.methodNames = methodNames || []; } else { this.model = model || AccessContext.ALL; this.property = property || AccessContext.ALL; this.accessType = accessType || AccessContext.ALL; this.permission = permission || AccessContext.DEFAULT; this.methodNames = methodNames || []; } }
javascript
function AccessRequest(model, property, accessType, permission, methodNames) { if (!(this instanceof AccessRequest)) { return new AccessRequest(model, property, accessType, permission, methodNames); } if (arguments.length === 1 && typeof model === 'object') { // The argument is an object that contains all required properties var obj = model || {}; this.model = obj.model || AccessContext.ALL; this.property = obj.property || AccessContext.ALL; this.accessType = obj.accessType || AccessContext.ALL; this.permission = obj.permission || AccessContext.DEFAULT; this.methodNames = methodNames || []; } else { this.model = model || AccessContext.ALL; this.property = property || AccessContext.ALL; this.accessType = accessType || AccessContext.ALL; this.permission = permission || AccessContext.DEFAULT; this.methodNames = methodNames || []; } }
[ "function", "AccessRequest", "(", "model", ",", "property", ",", "accessType", ",", "permission", ",", "methodNames", ")", "{", "if", "(", "!", "(", "this", "instanceof", "AccessRequest", ")", ")", "{", "return", "new", "AccessRequest", "(", "model", ",", "property", ",", "accessType", ",", "permission", ",", "methodNames", ")", ";", "}", "if", "(", "arguments", ".", "length", "===", "1", "&&", "typeof", "model", "===", "'object'", ")", "{", "var", "obj", "=", "model", "||", "{", "}", ";", "this", ".", "model", "=", "obj", ".", "model", "||", "AccessContext", ".", "ALL", ";", "this", ".", "property", "=", "obj", ".", "property", "||", "AccessContext", ".", "ALL", ";", "this", ".", "accessType", "=", "obj", ".", "accessType", "||", "AccessContext", ".", "ALL", ";", "this", ".", "permission", "=", "obj", ".", "permission", "||", "AccessContext", ".", "DEFAULT", ";", "this", ".", "methodNames", "=", "methodNames", "||", "[", "]", ";", "}", "else", "{", "this", ".", "model", "=", "model", "||", "AccessContext", ".", "ALL", ";", "this", ".", "property", "=", "property", "||", "AccessContext", ".", "ALL", ";", "this", ".", "accessType", "=", "accessType", "||", "AccessContext", ".", "ALL", ";", "this", ".", "permission", "=", "permission", "||", "AccessContext", ".", "DEFAULT", ";", "this", ".", "methodNames", "=", "methodNames", "||", "[", "]", ";", "}", "}" ]
A request to access protected resources. @param {String} model The model name @param {String} property @param {String} accessType The access type @param {String} permission The requested permission @param {String} methodNames The method names @returns {AccessRequest} @class
[ "A", "request", "to", "access", "protected", "resources", "." ]
34025751c4a2427535e67b838af05fca2b5fe250
https://github.com/taoyuan/sira-core/blob/34025751c4a2427535e67b838af05fca2b5fe250/lib/accessing.js#L230-L249
train
chip-js/differences-js
src/diff.js
ChangeRecord
function ChangeRecord(object, type, name, oldValue) { this.object = object; this.type = type; this.name = name; this.oldValue = oldValue; }
javascript
function ChangeRecord(object, type, name, oldValue) { this.object = object; this.type = type; this.name = name; this.oldValue = oldValue; }
[ "function", "ChangeRecord", "(", "object", ",", "type", ",", "name", ",", "oldValue", ")", "{", "this", ".", "object", "=", "object", ";", "this", ".", "type", "=", "type", ";", "this", ".", "name", "=", "name", ";", "this", ".", "oldValue", "=", "oldValue", ";", "}" ]
A change record for the object changes
[ "A", "change", "record", "for", "the", "object", "changes" ]
9b06274d353691c53f3a25950194fcc1bb709303
https://github.com/chip-js/differences-js/blob/9b06274d353691c53f3a25950194fcc1bb709303/src/diff.js#L38-L43
train
chip-js/differences-js
src/diff.js
Splice
function Splice(object, index, removed, addedCount) { ChangeRecord.call(this, object, 'splice', String(index)); this.index = index; this.removed = removed; this.addedCount = addedCount; }
javascript
function Splice(object, index, removed, addedCount) { ChangeRecord.call(this, object, 'splice', String(index)); this.index = index; this.removed = removed; this.addedCount = addedCount; }
[ "function", "Splice", "(", "object", ",", "index", ",", "removed", ",", "addedCount", ")", "{", "ChangeRecord", ".", "call", "(", "this", ",", "object", ",", "'splice'", ",", "String", "(", "index", ")", ")", ";", "this", ".", "index", "=", "index", ";", "this", ".", "removed", "=", "removed", ";", "this", ".", "addedCount", "=", "addedCount", ";", "}" ]
A splice record for the array changes
[ "A", "splice", "record", "for", "the", "array", "changes" ]
9b06274d353691c53f3a25950194fcc1bb709303
https://github.com/chip-js/differences-js/blob/9b06274d353691c53f3a25950194fcc1bb709303/src/diff.js#L46-L51
train
chip-js/differences-js
src/diff.js
diffBasic
function diffBasic(value, oldValue) { if (value && oldValue && typeof value === 'object' && typeof oldValue === 'object') { // Allow dates and Number/String objects to be compared var valueValue = value.valueOf(); var oldValueValue = oldValue.valueOf(); // Allow dates and Number/String objects to be compared if (typeof valueValue !== 'object' && typeof oldValueValue !== 'object') { return diffBasic(valueValue, oldValueValue); } } // If a value has changed call the callback if (typeof value === 'number' && typeof oldValue === 'number' && isNaN(value) && isNaN(oldValue)) { return false; } else { return value !== oldValue; } }
javascript
function diffBasic(value, oldValue) { if (value && oldValue && typeof value === 'object' && typeof oldValue === 'object') { // Allow dates and Number/String objects to be compared var valueValue = value.valueOf(); var oldValueValue = oldValue.valueOf(); // Allow dates and Number/String objects to be compared if (typeof valueValue !== 'object' && typeof oldValueValue !== 'object') { return diffBasic(valueValue, oldValueValue); } } // If a value has changed call the callback if (typeof value === 'number' && typeof oldValue === 'number' && isNaN(value) && isNaN(oldValue)) { return false; } else { return value !== oldValue; } }
[ "function", "diffBasic", "(", "value", ",", "oldValue", ")", "{", "if", "(", "value", "&&", "oldValue", "&&", "typeof", "value", "===", "'object'", "&&", "typeof", "oldValue", "===", "'object'", ")", "{", "var", "valueValue", "=", "value", ".", "valueOf", "(", ")", ";", "var", "oldValueValue", "=", "oldValue", ".", "valueOf", "(", ")", ";", "if", "(", "typeof", "valueValue", "!==", "'object'", "&&", "typeof", "oldValueValue", "!==", "'object'", ")", "{", "return", "diffBasic", "(", "valueValue", ",", "oldValueValue", ")", ";", "}", "}", "if", "(", "typeof", "value", "===", "'number'", "&&", "typeof", "oldValue", "===", "'number'", "&&", "isNaN", "(", "value", ")", "&&", "isNaN", "(", "oldValue", ")", ")", "{", "return", "false", ";", "}", "else", "{", "return", "value", "!==", "oldValue", ";", "}", "}" ]
Diffs two basic types, returning true if changed or false if not
[ "Diffs", "two", "basic", "types", "returning", "true", "if", "changed", "or", "false", "if", "not" ]
9b06274d353691c53f3a25950194fcc1bb709303
https://github.com/chip-js/differences-js/blob/9b06274d353691c53f3a25950194fcc1bb709303/src/diff.js#L119-L137
train
chip-js/differences-js
src/diff.js
sharedPrefix
function sharedPrefix(current, old, searchLength) { for (var i = 0; i < searchLength; i++) { if (diffBasic(current[i], old[i])) { return i; } } return searchLength; }
javascript
function sharedPrefix(current, old, searchLength) { for (var i = 0; i < searchLength; i++) { if (diffBasic(current[i], old[i])) { return i; } } return searchLength; }
[ "function", "sharedPrefix", "(", "current", ",", "old", ",", "searchLength", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "searchLength", ";", "i", "++", ")", "{", "if", "(", "diffBasic", "(", "current", "[", "i", "]", ",", "old", "[", "i", "]", ")", ")", "{", "return", "i", ";", "}", "}", "return", "searchLength", ";", "}" ]
find the number of items at the beginning that are the same
[ "find", "the", "number", "of", "items", "at", "the", "beginning", "that", "are", "the", "same" ]
9b06274d353691c53f3a25950194fcc1bb709303
https://github.com/chip-js/differences-js/blob/9b06274d353691c53f3a25950194fcc1bb709303/src/diff.js#L297-L304
train
logikum/md-site-engine
source/readers/read-controls.js
readControls
function readControls( controlPath, filingCabinet ) { logger.showInfo( '*** Reading controls...' ); // Initialize the store - engine controls. logger.showInfo( 'Engine controls:' ); getControls( '/node_modules/md-site-engine/controls', '', filingCabinet.controls ); // Initialize the store - user controls. logger.showInfo( 'Site controls:' ); getControls( controlPath, '', filingCabinet.controls ); }
javascript
function readControls( controlPath, filingCabinet ) { logger.showInfo( '*** Reading controls...' ); // Initialize the store - engine controls. logger.showInfo( 'Engine controls:' ); getControls( '/node_modules/md-site-engine/controls', '', filingCabinet.controls ); // Initialize the store - user controls. logger.showInfo( 'Site controls:' ); getControls( controlPath, '', filingCabinet.controls ); }
[ "function", "readControls", "(", "controlPath", ",", "filingCabinet", ")", "{", "logger", ".", "showInfo", "(", "'*** Reading controls...'", ")", ";", "logger", ".", "showInfo", "(", "'Engine controls:'", ")", ";", "getControls", "(", "'/node_modules/md-site-engine/controls'", ",", "''", ",", "filingCabinet", ".", "controls", ")", ";", "logger", ".", "showInfo", "(", "'Site controls:'", ")", ";", "getControls", "(", "controlPath", ",", "''", ",", "filingCabinet", ".", "controls", ")", ";", "}" ]
Reads all controls, including engine's predefined controls. @param {string} controlPath - The path of the controls directory. @param {FilingCabinet} filingCabinet - The file manager object.
[ "Reads", "all", "controls", "including", "engine", "s", "predefined", "controls", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/readers/read-controls.js#L12-L31
train
Evo-Forge/Crux
lib/util/util.js
stopSeries
function stopSeries(err) { if(err instanceof Error || (typeof err === 'object' && (err.code || err.error))) { stopErr = err; } isStopped = true; }
javascript
function stopSeries(err) { if(err instanceof Error || (typeof err === 'object' && (err.code || err.error))) { stopErr = err; } isStopped = true; }
[ "function", "stopSeries", "(", "err", ")", "{", "if", "(", "err", "instanceof", "Error", "||", "(", "typeof", "err", "===", "'object'", "&&", "(", "err", ".", "code", "||", "err", ".", "error", ")", ")", ")", "{", "stopErr", "=", "err", ";", "}", "isStopped", "=", "true", ";", "}" ]
The function can be called inside a promise call, that will stop the series chain.
[ "The", "function", "can", "be", "called", "inside", "a", "promise", "call", "that", "will", "stop", "the", "series", "chain", "." ]
f5264fbc2eb053e3170cf2b7b38d46d08f779feb
https://github.com/Evo-Forge/Crux/blob/f5264fbc2eb053e3170cf2b7b38d46d08f779feb/lib/util/util.js#L27-L32
train
InfinniPlatform/InfinniUI
app/actions/editAction/editAction.js
function() { var editDataSource = this.getProperty( 'editDataSource' ); var destinationDataSource = this.getProperty( 'destinationDataSource' ); var destinationProperty = this.getProperty( 'destinationProperty' ); if( this._isObjectDataSource( editDataSource ) ) { var editedItem = editDataSource.getSelectedItem(); var originItem = destinationDataSource.getProperty( destinationProperty ); if( this._isRootElementPath( destinationProperty ) ) { this._overrideOriginItem( originItem, editedItem ); destinationDataSource._includeItemToModifiedSet( originItem ); destinationDataSource.saveItem( originItem, function() { destinationDataSource.updateItems(); } ); } else { destinationDataSource.setProperty( destinationProperty, editedItem ); } } else { destinationDataSource.updateItems(); } }
javascript
function() { var editDataSource = this.getProperty( 'editDataSource' ); var destinationDataSource = this.getProperty( 'destinationDataSource' ); var destinationProperty = this.getProperty( 'destinationProperty' ); if( this._isObjectDataSource( editDataSource ) ) { var editedItem = editDataSource.getSelectedItem(); var originItem = destinationDataSource.getProperty( destinationProperty ); if( this._isRootElementPath( destinationProperty ) ) { this._overrideOriginItem( originItem, editedItem ); destinationDataSource._includeItemToModifiedSet( originItem ); destinationDataSource.saveItem( originItem, function() { destinationDataSource.updateItems(); } ); } else { destinationDataSource.setProperty( destinationProperty, editedItem ); } } else { destinationDataSource.updateItems(); } }
[ "function", "(", ")", "{", "var", "editDataSource", "=", "this", ".", "getProperty", "(", "'editDataSource'", ")", ";", "var", "destinationDataSource", "=", "this", ".", "getProperty", "(", "'destinationDataSource'", ")", ";", "var", "destinationProperty", "=", "this", ".", "getProperty", "(", "'destinationProperty'", ")", ";", "if", "(", "this", ".", "_isObjectDataSource", "(", "editDataSource", ")", ")", "{", "var", "editedItem", "=", "editDataSource", ".", "getSelectedItem", "(", ")", ";", "var", "originItem", "=", "destinationDataSource", ".", "getProperty", "(", "destinationProperty", ")", ";", "if", "(", "this", ".", "_isRootElementPath", "(", "destinationProperty", ")", ")", "{", "this", ".", "_overrideOriginItem", "(", "originItem", ",", "editedItem", ")", ";", "destinationDataSource", ".", "_includeItemToModifiedSet", "(", "originItem", ")", ";", "destinationDataSource", ".", "saveItem", "(", "originItem", ",", "function", "(", ")", "{", "destinationDataSource", ".", "updateItems", "(", ")", ";", "}", ")", ";", "}", "else", "{", "destinationDataSource", ".", "setProperty", "(", "destinationProperty", ",", "editedItem", ")", ";", "}", "}", "else", "{", "destinationDataSource", ".", "updateItems", "(", ")", ";", "}", "}" ]
save item in destination data source
[ "save", "item", "in", "destination", "data", "source" ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/app/actions/editAction/editAction.js#L93-L115
train
logikum/md-site-engine
source/readers/get-content.js
getContent
function getContent( contentFile, source ) { // Determine the path. var contentPath = path.join( process.cwd(), contentFile ); // Get the file content. var html = fs.readFileSync( contentPath, { encoding: 'utf-8' } ); // Find tokens. var re = /(\{\{\s*[=#.]?[\w-\/]+\s*}})/g; var tokens = [ ]; var j = 0; for (var matches = re.exec( html ); matches !== null; matches = re.exec( html )) { tokens[ j++ ] = new Token( matches[ 1 ] ); } // Create and return the content. return new Content( html, tokens, source ); }
javascript
function getContent( contentFile, source ) { // Determine the path. var contentPath = path.join( process.cwd(), contentFile ); // Get the file content. var html = fs.readFileSync( contentPath, { encoding: 'utf-8' } ); // Find tokens. var re = /(\{\{\s*[=#.]?[\w-\/]+\s*}})/g; var tokens = [ ]; var j = 0; for (var matches = re.exec( html ); matches !== null; matches = re.exec( html )) { tokens[ j++ ] = new Token( matches[ 1 ] ); } // Create and return the content. return new Content( html, tokens, source ); }
[ "function", "getContent", "(", "contentFile", ",", "source", ")", "{", "var", "contentPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "contentFile", ")", ";", "var", "html", "=", "fs", ".", "readFileSync", "(", "contentPath", ",", "{", "encoding", ":", "'utf-8'", "}", ")", ";", "var", "re", "=", "/", "(\\{\\{\\s*[=#.]?[\\w-\\/]+\\s*}})", "/", "g", ";", "var", "tokens", "=", "[", "]", ";", "var", "j", "=", "0", ";", "for", "(", "var", "matches", "=", "re", ".", "exec", "(", "html", ")", ";", "matches", "!==", "null", ";", "matches", "=", "re", ".", "exec", "(", "html", ")", ")", "{", "tokens", "[", "j", "++", "]", "=", "new", "Token", "(", "matches", "[", "1", "]", ")", ";", "}", "return", "new", "Content", "(", "html", ",", "tokens", ",", "source", ")", ";", "}" ]
Reads the content of a content file. @param {string} contentFile - The path of the content file. @param {string} source - The type of the content file (html|markdown). @returns {Content} The content object.
[ "Reads", "the", "content", "of", "a", "content", "file", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/readers/get-content.js#L14-L32
train
cainus/verity
index.js
function(uri, _method){ if (!(this instanceof Verity)) { return new Verity(uri, _method); } this.uri = urlgrey(uri || 'http://localhost:80'); this._method = _method || 'GET'; this._body = ''; this.cookieJar = request.jar(); this.client = request.defaults({ timeout:3000, jar: this.cookieJar }); this.headers = {}; this.cookies = {}; this.shouldLog = true; this.expectedBody = null; this.jsonModeOn = false; this._expectedHeaders = {}; this._expectedCookies = {}; this._expectations = {}; this._unnamedExpectationCount = 0; }
javascript
function(uri, _method){ if (!(this instanceof Verity)) { return new Verity(uri, _method); } this.uri = urlgrey(uri || 'http://localhost:80'); this._method = _method || 'GET'; this._body = ''; this.cookieJar = request.jar(); this.client = request.defaults({ timeout:3000, jar: this.cookieJar }); this.headers = {}; this.cookies = {}; this.shouldLog = true; this.expectedBody = null; this.jsonModeOn = false; this._expectedHeaders = {}; this._expectedCookies = {}; this._expectations = {}; this._unnamedExpectationCount = 0; }
[ "function", "(", "uri", ",", "_method", ")", "{", "if", "(", "!", "(", "this", "instanceof", "Verity", ")", ")", "{", "return", "new", "Verity", "(", "uri", ",", "_method", ")", ";", "}", "this", ".", "uri", "=", "urlgrey", "(", "uri", "||", "'http://localhost:80'", ")", ";", "this", ".", "_method", "=", "_method", "||", "'GET'", ";", "this", ".", "_body", "=", "''", ";", "this", ".", "cookieJar", "=", "request", ".", "jar", "(", ")", ";", "this", ".", "client", "=", "request", ".", "defaults", "(", "{", "timeout", ":", "3000", ",", "jar", ":", "this", ".", "cookieJar", "}", ")", ";", "this", ".", "headers", "=", "{", "}", ";", "this", ".", "cookies", "=", "{", "}", ";", "this", ".", "shouldLog", "=", "true", ";", "this", ".", "expectedBody", "=", "null", ";", "this", ".", "jsonModeOn", "=", "false", ";", "this", ".", "_expectedHeaders", "=", "{", "}", ";", "this", ".", "_expectedCookies", "=", "{", "}", ";", "this", ".", "_expectations", "=", "{", "}", ";", "this", ".", "_unnamedExpectationCount", "=", "0", ";", "}" ]
checks a response holistically, rather than in parts, which results in better error output.
[ "checks", "a", "response", "holistically", "rather", "than", "in", "parts", "which", "results", "in", "better", "error", "output", "." ]
b379144a8decaf9b3ee30bf13ef7fece3c563f7b
https://github.com/cainus/verity/blob/b379144a8decaf9b3ee30bf13ef7fece3c563f7b/index.js#L32-L55
train
jonschlinkert/config-file
index.js
type
function type(filename, opts) { opts = opts || {}; if (opts.parse && typeof opts.parse === 'string') { return opts.parse; } var ext = path.extname(filename); return ext || 'json'; }
javascript
function type(filename, opts) { opts = opts || {}; if (opts.parse && typeof opts.parse === 'string') { return opts.parse; } var ext = path.extname(filename); return ext || 'json'; }
[ "function", "type", "(", "filename", ",", "opts", ")", "{", "opts", "=", "opts", "||", "{", "}", ";", "if", "(", "opts", ".", "parse", "&&", "typeof", "opts", ".", "parse", "===", "'string'", ")", "{", "return", "opts", ".", "parse", ";", "}", "var", "ext", "=", "path", ".", "extname", "(", "filename", ")", ";", "return", "ext", "||", "'json'", ";", "}" ]
Detect the type to parse, JSON or YAML. Sometimes this is based on file extension, other times it must be specified on the options. @param {String} `filename` @param {Object} `opts` If `filename` does not have an extension, specify the type on the `parse` option. @return {String} The type to parse.
[ "Detect", "the", "type", "to", "parse", "JSON", "or", "YAML", ".", "Sometimes", "this", "is", "based", "on", "file", "extension", "other", "times", "it", "must", "be", "specified", "on", "the", "options", "." ]
19929953f43d7d039d07a9f803a4a625ec67846f
https://github.com/jonschlinkert/config-file/blob/19929953f43d7d039d07a9f803a4a625ec67846f/index.js#L161-L168
train
kengz/dokker
gulpfile.js
startServer
function startServer() { var defer = q.defer(); var serverConfig = { server: { baseDir: wpath, directory: true }, startPath: 'docs/index.html', // browser: "google chrome", logPrefix: 'SERVER' }; browserSync.init(serverConfig, defer.resolve); return defer.promise; }
javascript
function startServer() { var defer = q.defer(); var serverConfig = { server: { baseDir: wpath, directory: true }, startPath: 'docs/index.html', // browser: "google chrome", logPrefix: 'SERVER' }; browserSync.init(serverConfig, defer.resolve); return defer.promise; }
[ "function", "startServer", "(", ")", "{", "var", "defer", "=", "q", ".", "defer", "(", ")", ";", "var", "serverConfig", "=", "{", "server", ":", "{", "baseDir", ":", "wpath", ",", "directory", ":", "true", "}", ",", "startPath", ":", "'docs/index.html'", ",", "logPrefix", ":", "'SERVER'", "}", ";", "browserSync", ".", "init", "(", "serverConfig", ",", "defer", ".", "resolve", ")", ";", "return", "defer", ".", "promise", ";", "}" ]
start a browserSync server to index.html directly
[ "start", "a", "browserSync", "server", "to", "index", ".", "html", "directly" ]
34e15326023bf6f27fe87135e02c1d4b2b080780
https://github.com/kengz/dokker/blob/34e15326023bf6f27fe87135e02c1d4b2b080780/gulpfile.js#L39-L54
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
ChunkedStreamManager_requestRange
function ChunkedStreamManager_requestRange( begin, end, callback) { end = Math.min(end, this.length); var beginChunk = this.getBeginChunk(begin); var endChunk = this.getEndChunk(end); var chunks = []; for (var chunk = beginChunk; chunk < endChunk; ++chunk) { chunks.push(chunk); } this.requestChunks(chunks, callback); }
javascript
function ChunkedStreamManager_requestRange( begin, end, callback) { end = Math.min(end, this.length); var beginChunk = this.getBeginChunk(begin); var endChunk = this.getEndChunk(end); var chunks = []; for (var chunk = beginChunk; chunk < endChunk; ++chunk) { chunks.push(chunk); } this.requestChunks(chunks, callback); }
[ "function", "ChunkedStreamManager_requestRange", "(", "begin", ",", "end", ",", "callback", ")", "{", "end", "=", "Math", ".", "min", "(", "end", ",", "this", ".", "length", ")", ";", "var", "beginChunk", "=", "this", ".", "getBeginChunk", "(", "begin", ")", ";", "var", "endChunk", "=", "this", ".", "getEndChunk", "(", "end", ")", ";", "var", "chunks", "=", "[", "]", ";", "for", "(", "var", "chunk", "=", "beginChunk", ";", "chunk", "<", "endChunk", ";", "++", "chunk", ")", "{", "chunks", ".", "push", "(", "chunk", ")", ";", "}", "this", ".", "requestChunks", "(", "chunks", ",", "callback", ")", ";", "}" ]
Loads any chunks in the requested range that are not yet loaded
[ "Loads", "any", "chunks", "in", "the", "requested", "range", "that", "are", "not", "yet", "loaded" ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L2209-L2223
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
ChunkedStreamManager_groupChunks
function ChunkedStreamManager_groupChunks(chunks) { var groupedChunks = []; var beginChunk = -1; var prevChunk = -1; for (var i = 0; i < chunks.length; ++i) { var chunk = chunks[i]; if (beginChunk < 0) { beginChunk = chunk; } if (prevChunk >= 0 && prevChunk + 1 !== chunk) { groupedChunks.push({ beginChunk: beginChunk, endChunk: prevChunk + 1 }); beginChunk = chunk; } if (i + 1 === chunks.length) { groupedChunks.push({ beginChunk: beginChunk, endChunk: chunk + 1 }); } prevChunk = chunk; } return groupedChunks; }
javascript
function ChunkedStreamManager_groupChunks(chunks) { var groupedChunks = []; var beginChunk = -1; var prevChunk = -1; for (var i = 0; i < chunks.length; ++i) { var chunk = chunks[i]; if (beginChunk < 0) { beginChunk = chunk; } if (prevChunk >= 0 && prevChunk + 1 !== chunk) { groupedChunks.push({ beginChunk: beginChunk, endChunk: prevChunk + 1 }); beginChunk = chunk; } if (i + 1 === chunks.length) { groupedChunks.push({ beginChunk: beginChunk, endChunk: chunk + 1 }); } prevChunk = chunk; } return groupedChunks; }
[ "function", "ChunkedStreamManager_groupChunks", "(", "chunks", ")", "{", "var", "groupedChunks", "=", "[", "]", ";", "var", "beginChunk", "=", "-", "1", ";", "var", "prevChunk", "=", "-", "1", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "chunks", ".", "length", ";", "++", "i", ")", "{", "var", "chunk", "=", "chunks", "[", "i", "]", ";", "if", "(", "beginChunk", "<", "0", ")", "{", "beginChunk", "=", "chunk", ";", "}", "if", "(", "prevChunk", ">=", "0", "&&", "prevChunk", "+", "1", "!==", "chunk", ")", "{", "groupedChunks", ".", "push", "(", "{", "beginChunk", ":", "beginChunk", ",", "endChunk", ":", "prevChunk", "+", "1", "}", ")", ";", "beginChunk", "=", "chunk", ";", "}", "if", "(", "i", "+", "1", "===", "chunks", ".", "length", ")", "{", "groupedChunks", ".", "push", "(", "{", "beginChunk", ":", "beginChunk", ",", "endChunk", ":", "chunk", "+", "1", "}", ")", ";", "}", "prevChunk", "=", "chunk", ";", "}", "return", "groupedChunks", ";", "}" ]
Groups a sorted array of chunks into as few continguous larger chunks as possible
[ "Groups", "a", "sorted", "array", "of", "chunks", "into", "as", "few", "continguous", "larger", "chunks", "as", "possible" ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L2246-L2270
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
PDFDocument_checkHeader
function PDFDocument_checkHeader() { var stream = this.stream; stream.reset(); if (find(stream, '%PDF-', 1024)) { // Found the header, trim off any garbage before it. stream.moveStart(); // Reading file format version var MAX_VERSION_LENGTH = 12; var version = '', ch; while ((ch = stream.getByte()) > 0x20) { // SPACE if (version.length >= MAX_VERSION_LENGTH) { break; } version += String.fromCharCode(ch); } if (!this.pdfFormatVersion) { // removing "%PDF-"-prefix this.pdfFormatVersion = version.substring(5); } return; } // May not be a PDF file, continue anyway. }
javascript
function PDFDocument_checkHeader() { var stream = this.stream; stream.reset(); if (find(stream, '%PDF-', 1024)) { // Found the header, trim off any garbage before it. stream.moveStart(); // Reading file format version var MAX_VERSION_LENGTH = 12; var version = '', ch; while ((ch = stream.getByte()) > 0x20) { // SPACE if (version.length >= MAX_VERSION_LENGTH) { break; } version += String.fromCharCode(ch); } if (!this.pdfFormatVersion) { // removing "%PDF-"-prefix this.pdfFormatVersion = version.substring(5); } return; } // May not be a PDF file, continue anyway. }
[ "function", "PDFDocument_checkHeader", "(", ")", "{", "var", "stream", "=", "this", ".", "stream", ";", "stream", ".", "reset", "(", ")", ";", "if", "(", "find", "(", "stream", ",", "'%PDF-'", ",", "1024", ")", ")", "{", "stream", ".", "moveStart", "(", ")", ";", "var", "MAX_VERSION_LENGTH", "=", "12", ";", "var", "version", "=", "''", ",", "ch", ";", "while", "(", "(", "ch", "=", "stream", ".", "getByte", "(", ")", ")", ">", "0x20", ")", "{", "if", "(", "version", ".", "length", ">=", "MAX_VERSION_LENGTH", ")", "{", "break", ";", "}", "version", "+=", "String", ".", "fromCharCode", "(", "ch", ")", ";", "}", "if", "(", "!", "this", ".", "pdfFormatVersion", ")", "{", "this", ".", "pdfFormatVersion", "=", "version", ".", "substring", "(", "5", ")", ";", "}", "return", ";", "}", "}" ]
Find the header, remove leading garbage and setup the stream starting from the header.
[ "Find", "the", "header", "remove", "leading", "garbage", "and", "setup", "the", "stream", "starting", "from", "the", "header", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L3014-L3036
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
Dict
function Dict(xref) { // Map should only be used internally, use functions below to access. this.map = Object.create(null); this.xref = xref; this.objId = null; this.__nonSerializable__ = nonSerializable; // disable cloning of the Dict }
javascript
function Dict(xref) { // Map should only be used internally, use functions below to access. this.map = Object.create(null); this.xref = xref; this.objId = null; this.__nonSerializable__ = nonSerializable; // disable cloning of the Dict }
[ "function", "Dict", "(", "xref", ")", "{", "this", ".", "map", "=", "Object", ".", "create", "(", "null", ")", ";", "this", ".", "xref", "=", "xref", ";", "this", ".", "objId", "=", "null", ";", "this", ".", "__nonSerializable__", "=", "nonSerializable", ";", "}" ]
xref is optional
[ "xref", "is", "optional" ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L3177-L3183
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
Dict_get
function Dict_get(key1, key2, key3) { var value; var xref = this.xref; if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map || typeof key2 === 'undefined') { return xref ? xref.fetchIfRef(value) : value; } if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map || typeof key3 === 'undefined') { return xref ? xref.fetchIfRef(value) : value; } value = this.map[key3] || null; return xref ? xref.fetchIfRef(value) : value; }
javascript
function Dict_get(key1, key2, key3) { var value; var xref = this.xref; if (typeof (value = this.map[key1]) !== 'undefined' || key1 in this.map || typeof key2 === 'undefined') { return xref ? xref.fetchIfRef(value) : value; } if (typeof (value = this.map[key2]) !== 'undefined' || key2 in this.map || typeof key3 === 'undefined') { return xref ? xref.fetchIfRef(value) : value; } value = this.map[key3] || null; return xref ? xref.fetchIfRef(value) : value; }
[ "function", "Dict_get", "(", "key1", ",", "key2", ",", "key3", ")", "{", "var", "value", ";", "var", "xref", "=", "this", ".", "xref", ";", "if", "(", "typeof", "(", "value", "=", "this", ".", "map", "[", "key1", "]", ")", "!==", "'undefined'", "||", "key1", "in", "this", ".", "map", "||", "typeof", "key2", "===", "'undefined'", ")", "{", "return", "xref", "?", "xref", ".", "fetchIfRef", "(", "value", ")", ":", "value", ";", "}", "if", "(", "typeof", "(", "value", "=", "this", ".", "map", "[", "key2", "]", ")", "!==", "'undefined'", "||", "key2", "in", "this", ".", "map", "||", "typeof", "key3", "===", "'undefined'", ")", "{", "return", "xref", "?", "xref", ".", "fetchIfRef", "(", "value", ")", ":", "value", ";", "}", "value", "=", "this", ".", "map", "[", "key3", "]", "||", "null", ";", "return", "xref", "?", "xref", ".", "fetchIfRef", "(", "value", ")", ":", "value", ";", "}" ]
automatically dereferences Ref objects
[ "automatically", "dereferences", "Ref", "objects" ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L3191-L3204
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
Dict_getAll
function Dict_getAll() { var all = Object.create(null); var queue = null; var key, obj; for (key in this.map) { obj = this.get(key); if (obj instanceof Dict) { if (isRecursionAllowedFor(obj)) { (queue || (queue = [])).push({target: all, key: key, obj: obj}); } else { all[key] = this.getRaw(key); } } else { all[key] = obj; } } if (!queue) { return all; } // trying to take cyclic references into the account var processed = Object.create(null); while (queue.length > 0) { var item = queue.shift(); var itemObj = item.obj; var objId = itemObj.objId; if (objId && objId in processed) { item.target[item.key] = processed[objId]; continue; } var dereferenced = Object.create(null); for (key in itemObj.map) { obj = itemObj.get(key); if (obj instanceof Dict) { if (isRecursionAllowedFor(obj)) { queue.push({target: dereferenced, key: key, obj: obj}); } else { dereferenced[key] = itemObj.getRaw(key); } } else { dereferenced[key] = obj; } } if (objId) { processed[objId] = dereferenced; } item.target[item.key] = dereferenced; } return all; }
javascript
function Dict_getAll() { var all = Object.create(null); var queue = null; var key, obj; for (key in this.map) { obj = this.get(key); if (obj instanceof Dict) { if (isRecursionAllowedFor(obj)) { (queue || (queue = [])).push({target: all, key: key, obj: obj}); } else { all[key] = this.getRaw(key); } } else { all[key] = obj; } } if (!queue) { return all; } // trying to take cyclic references into the account var processed = Object.create(null); while (queue.length > 0) { var item = queue.shift(); var itemObj = item.obj; var objId = itemObj.objId; if (objId && objId in processed) { item.target[item.key] = processed[objId]; continue; } var dereferenced = Object.create(null); for (key in itemObj.map) { obj = itemObj.get(key); if (obj instanceof Dict) { if (isRecursionAllowedFor(obj)) { queue.push({target: dereferenced, key: key, obj: obj}); } else { dereferenced[key] = itemObj.getRaw(key); } } else { dereferenced[key] = obj; } } if (objId) { processed[objId] = dereferenced; } item.target[item.key] = dereferenced; } return all; }
[ "function", "Dict_getAll", "(", ")", "{", "var", "all", "=", "Object", ".", "create", "(", "null", ")", ";", "var", "queue", "=", "null", ";", "var", "key", ",", "obj", ";", "for", "(", "key", "in", "this", ".", "map", ")", "{", "obj", "=", "this", ".", "get", "(", "key", ")", ";", "if", "(", "obj", "instanceof", "Dict", ")", "{", "if", "(", "isRecursionAllowedFor", "(", "obj", ")", ")", "{", "(", "queue", "||", "(", "queue", "=", "[", "]", ")", ")", ".", "push", "(", "{", "target", ":", "all", ",", "key", ":", "key", ",", "obj", ":", "obj", "}", ")", ";", "}", "else", "{", "all", "[", "key", "]", "=", "this", ".", "getRaw", "(", "key", ")", ";", "}", "}", "else", "{", "all", "[", "key", "]", "=", "obj", ";", "}", "}", "if", "(", "!", "queue", ")", "{", "return", "all", ";", "}", "var", "processed", "=", "Object", ".", "create", "(", "null", ")", ";", "while", "(", "queue", ".", "length", ">", "0", ")", "{", "var", "item", "=", "queue", ".", "shift", "(", ")", ";", "var", "itemObj", "=", "item", ".", "obj", ";", "var", "objId", "=", "itemObj", ".", "objId", ";", "if", "(", "objId", "&&", "objId", "in", "processed", ")", "{", "item", ".", "target", "[", "item", ".", "key", "]", "=", "processed", "[", "objId", "]", ";", "continue", ";", "}", "var", "dereferenced", "=", "Object", ".", "create", "(", "null", ")", ";", "for", "(", "key", "in", "itemObj", ".", "map", ")", "{", "obj", "=", "itemObj", ".", "get", "(", "key", ")", ";", "if", "(", "obj", "instanceof", "Dict", ")", "{", "if", "(", "isRecursionAllowedFor", "(", "obj", ")", ")", "{", "queue", ".", "push", "(", "{", "target", ":", "dereferenced", ",", "key", ":", "key", ",", "obj", ":", "obj", "}", ")", ";", "}", "else", "{", "dereferenced", "[", "key", "]", "=", "itemObj", ".", "getRaw", "(", "key", ")", ";", "}", "}", "else", "{", "dereferenced", "[", "key", "]", "=", "obj", ";", "}", "}", "if", "(", "objId", ")", "{", "processed", "[", "objId", "]", "=", "dereferenced", ";", "}", "item", ".", "target", "[", "item", ".", "key", "]", "=", "dereferenced", ";", "}", "return", "all", ";", "}" ]
creates new map and dereferences all Refs
[ "creates", "new", "map", "and", "dereferences", "all", "Refs" ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L3237-L3286
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
readToken
function readToken(data, offset) { var token = '', ch = data[offset]; while (ch !== 13 && ch !== 10) { if (++offset >= data.length) { break; } token += String.fromCharCode(ch); ch = data[offset]; } return token; }
javascript
function readToken(data, offset) { var token = '', ch = data[offset]; while (ch !== 13 && ch !== 10) { if (++offset >= data.length) { break; } token += String.fromCharCode(ch); ch = data[offset]; } return token; }
[ "function", "readToken", "(", "data", ",", "offset", ")", "{", "var", "token", "=", "''", ",", "ch", "=", "data", "[", "offset", "]", ";", "while", "(", "ch", "!==", "13", "&&", "ch", "!==", "10", ")", "{", "if", "(", "++", "offset", ">=", "data", ".", "length", ")", "{", "break", ";", "}", "token", "+=", "String", ".", "fromCharCode", "(", "ch", ")", ";", "ch", "=", "data", "[", "offset", "]", ";", "}", "return", "token", ";", "}" ]
Simple scan through the PDF content to find objects, trailers and XRef streams.
[ "Simple", "scan", "through", "the", "PDF", "content", "to", "find", "objects", "trailers", "and", "XRef", "streams", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L4113-L4123
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
convertToRgb
function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) { // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax] // not the usual [0, 1]. If a command like setFillColor is used the src // values will already be within the correct range. However, if we are // converting an image we have to map the values to the correct range given // above. // Ls,as,bs <---> L*,a*,b* in the spec var Ls = src[srcOffset]; var as = src[srcOffset + 1]; var bs = src[srcOffset + 2]; if (maxVal !== false) { Ls = decode(Ls, maxVal, 0, 100); as = decode(as, maxVal, cs.amin, cs.amax); bs = decode(bs, maxVal, cs.bmin, cs.bmax); } // Adjust limits of 'as' and 'bs' as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as; bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs; // Computes intermediate variables X,Y,Z as per spec var M = (Ls + 16) / 116; var L = M + (as / 500); var N = M - (bs / 200); var X = cs.XW * fn_g(L); var Y = cs.YW * fn_g(M); var Z = cs.ZW * fn_g(N); var r, g, b; // Using different conversions for D50 and D65 white points, // per http://www.color.org/srgb.pdf if (cs.ZW < 1) { // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249) r = X * 3.1339 + Y * -1.6170 + Z * -0.4906; g = X * -0.9785 + Y * 1.9160 + Z * 0.0333; b = X * 0.0720 + Y * -0.2290 + Z * 1.4057; } else { // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888) r = X * 3.2406 + Y * -1.5372 + Z * -0.4986; g = X * -0.9689 + Y * 1.8758 + Z * 0.0415; b = X * 0.0557 + Y * -0.2040 + Z * 1.0570; } // clamp color values to [0,1] range then convert to [0,255] range. dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0; dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0; dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0; }
javascript
function convertToRgb(cs, src, srcOffset, maxVal, dest, destOffset) { // XXX: Lab input is in the range of [0, 100], [amin, amax], [bmin, bmax] // not the usual [0, 1]. If a command like setFillColor is used the src // values will already be within the correct range. However, if we are // converting an image we have to map the values to the correct range given // above. // Ls,as,bs <---> L*,a*,b* in the spec var Ls = src[srcOffset]; var as = src[srcOffset + 1]; var bs = src[srcOffset + 2]; if (maxVal !== false) { Ls = decode(Ls, maxVal, 0, 100); as = decode(as, maxVal, cs.amin, cs.amax); bs = decode(bs, maxVal, cs.bmin, cs.bmax); } // Adjust limits of 'as' and 'bs' as = as > cs.amax ? cs.amax : as < cs.amin ? cs.amin : as; bs = bs > cs.bmax ? cs.bmax : bs < cs.bmin ? cs.bmin : bs; // Computes intermediate variables X,Y,Z as per spec var M = (Ls + 16) / 116; var L = M + (as / 500); var N = M - (bs / 200); var X = cs.XW * fn_g(L); var Y = cs.YW * fn_g(M); var Z = cs.ZW * fn_g(N); var r, g, b; // Using different conversions for D50 and D65 white points, // per http://www.color.org/srgb.pdf if (cs.ZW < 1) { // Assuming D50 (X=0.9642, Y=1.00, Z=0.8249) r = X * 3.1339 + Y * -1.6170 + Z * -0.4906; g = X * -0.9785 + Y * 1.9160 + Z * 0.0333; b = X * 0.0720 + Y * -0.2290 + Z * 1.4057; } else { // Assuming D65 (X=0.9505, Y=1.00, Z=1.0888) r = X * 3.2406 + Y * -1.5372 + Z * -0.4986; g = X * -0.9689 + Y * 1.8758 + Z * 0.0415; b = X * 0.0557 + Y * -0.2040 + Z * 1.0570; } // clamp color values to [0,1] range then convert to [0,255] range. dest[destOffset] = r <= 0 ? 0 : r >= 1 ? 255 : Math.sqrt(r) * 255 | 0; dest[destOffset + 1] = g <= 0 ? 0 : g >= 1 ? 255 : Math.sqrt(g) * 255 | 0; dest[destOffset + 2] = b <= 0 ? 0 : b >= 1 ? 255 : Math.sqrt(b) * 255 | 0; }
[ "function", "convertToRgb", "(", "cs", ",", "src", ",", "srcOffset", ",", "maxVal", ",", "dest", ",", "destOffset", ")", "{", "var", "Ls", "=", "src", "[", "srcOffset", "]", ";", "var", "as", "=", "src", "[", "srcOffset", "+", "1", "]", ";", "var", "bs", "=", "src", "[", "srcOffset", "+", "2", "]", ";", "if", "(", "maxVal", "!==", "false", ")", "{", "Ls", "=", "decode", "(", "Ls", ",", "maxVal", ",", "0", ",", "100", ")", ";", "as", "=", "decode", "(", "as", ",", "maxVal", ",", "cs", ".", "amin", ",", "cs", ".", "amax", ")", ";", "bs", "=", "decode", "(", "bs", ",", "maxVal", ",", "cs", ".", "bmin", ",", "cs", ".", "bmax", ")", ";", "}", "as", "=", "as", ">", "cs", ".", "amax", "?", "cs", ".", "amax", ":", "as", "<", "cs", ".", "amin", "?", "cs", ".", "amin", ":", "as", ";", "bs", "=", "bs", ">", "cs", ".", "bmax", "?", "cs", ".", "bmax", ":", "bs", "<", "cs", ".", "bmin", "?", "cs", ".", "bmin", ":", "bs", ";", "var", "M", "=", "(", "Ls", "+", "16", ")", "/", "116", ";", "var", "L", "=", "M", "+", "(", "as", "/", "500", ")", ";", "var", "N", "=", "M", "-", "(", "bs", "/", "200", ")", ";", "var", "X", "=", "cs", ".", "XW", "*", "fn_g", "(", "L", ")", ";", "var", "Y", "=", "cs", ".", "YW", "*", "fn_g", "(", "M", ")", ";", "var", "Z", "=", "cs", ".", "ZW", "*", "fn_g", "(", "N", ")", ";", "var", "r", ",", "g", ",", "b", ";", "if", "(", "cs", ".", "ZW", "<", "1", ")", "{", "r", "=", "X", "*", "3.1339", "+", "Y", "*", "-", "1.6170", "+", "Z", "*", "-", "0.4906", ";", "g", "=", "X", "*", "-", "0.9785", "+", "Y", "*", "1.9160", "+", "Z", "*", "0.0333", ";", "b", "=", "X", "*", "0.0720", "+", "Y", "*", "-", "0.2290", "+", "Z", "*", "1.4057", ";", "}", "else", "{", "r", "=", "X", "*", "3.2406", "+", "Y", "*", "-", "1.5372", "+", "Z", "*", "-", "0.4986", ";", "g", "=", "X", "*", "-", "0.9689", "+", "Y", "*", "1.8758", "+", "Z", "*", "0.0415", ";", "b", "=", "X", "*", "0.0557", "+", "Y", "*", "-", "0.2040", "+", "Z", "*", "1.0570", ";", "}", "dest", "[", "destOffset", "]", "=", "r", "<=", "0", "?", "0", ":", "r", ">=", "1", "?", "255", ":", "Math", ".", "sqrt", "(", "r", ")", "*", "255", "|", "0", ";", "dest", "[", "destOffset", "+", "1", "]", "=", "g", "<=", "0", "?", "0", ":", "g", ">=", "1", "?", "255", ":", "Math", ".", "sqrt", "(", "g", ")", "*", "255", "|", "0", ";", "dest", "[", "destOffset", "+", "2", "]", "=", "b", "<=", "0", "?", "0", ":", "b", ">=", "1", "?", "255", ":", "Math", ".", "sqrt", "(", "b", ")", "*", "255", "|", "0", ";", "}" ]
If decoding is needed maxVal should be 2^bits per component - 1.
[ "If", "decoding", "is", "needed", "maxVal", "should", "be", "2^bits", "per", "component", "-", "1", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L7730-L7777
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
getTransfers
function getTransfers(queue) { var transfers = []; var fnArray = queue.fnArray, argsArray = queue.argsArray; for (var i = 0, ii = queue.length; i < ii; i++) { switch (fnArray[i]) { case OPS.paintInlineImageXObject: case OPS.paintInlineImageXObjectGroup: case OPS.paintImageMaskXObject: var arg = argsArray[i][0]; // first param in imgData if (!arg.cached) { transfers.push(arg.data.buffer); } break; } } return transfers; }
javascript
function getTransfers(queue) { var transfers = []; var fnArray = queue.fnArray, argsArray = queue.argsArray; for (var i = 0, ii = queue.length; i < ii; i++) { switch (fnArray[i]) { case OPS.paintInlineImageXObject: case OPS.paintInlineImageXObjectGroup: case OPS.paintImageMaskXObject: var arg = argsArray[i][0]; // first param in imgData if (!arg.cached) { transfers.push(arg.data.buffer); } break; } } return transfers; }
[ "function", "getTransfers", "(", "queue", ")", "{", "var", "transfers", "=", "[", "]", ";", "var", "fnArray", "=", "queue", ".", "fnArray", ",", "argsArray", "=", "queue", ".", "argsArray", ";", "for", "(", "var", "i", "=", "0", ",", "ii", "=", "queue", ".", "length", ";", "i", "<", "ii", ";", "i", "++", ")", "{", "switch", "(", "fnArray", "[", "i", "]", ")", "{", "case", "OPS", ".", "paintInlineImageXObject", ":", "case", "OPS", ".", "paintInlineImageXObjectGroup", ":", "case", "OPS", ".", "paintImageMaskXObject", ":", "var", "arg", "=", "argsArray", "[", "i", "]", "[", "0", "]", ";", "if", "(", "!", "arg", ".", "cached", ")", "{", "transfers", ".", "push", "(", "arg", ".", "data", ".", "buffer", ")", ";", "}", "break", ";", "}", "}", "return", "transfers", ";", "}" ]
close to chunk size
[ "close", "to", "chunk", "size" ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L12455-L12471
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
isProblematicUnicodeLocation
function isProblematicUnicodeLocation(code) { if (code <= 0x1F) { // Control chars return true; } if (code >= 0x80 && code <= 0x9F) { // Control chars return true; } if ((code >= 0x2000 && code <= 0x200F) || // General punctuation chars (code >= 0x2028 && code <= 0x202F) || (code >= 0x2060 && code <= 0x206F)) { return true; } if (code >= 0xFFF0 && code <= 0xFFFF) { // Specials Unicode block return true; } switch (code) { case 0x7F: // Control char case 0xA0: // Non breaking space case 0xAD: // Soft hyphen case 0x2011: // Non breaking hyphen case 0x205F: // Medium mathematical space case 0x25CC: // Dotted circle (combining mark) return true; } if ((code & ~0xFF) === 0x0E00) { // Thai/Lao chars (with combining mark) return true; } return false; }
javascript
function isProblematicUnicodeLocation(code) { if (code <= 0x1F) { // Control chars return true; } if (code >= 0x80 && code <= 0x9F) { // Control chars return true; } if ((code >= 0x2000 && code <= 0x200F) || // General punctuation chars (code >= 0x2028 && code <= 0x202F) || (code >= 0x2060 && code <= 0x206F)) { return true; } if (code >= 0xFFF0 && code <= 0xFFFF) { // Specials Unicode block return true; } switch (code) { case 0x7F: // Control char case 0xA0: // Non breaking space case 0xAD: // Soft hyphen case 0x2011: // Non breaking hyphen case 0x205F: // Medium mathematical space case 0x25CC: // Dotted circle (combining mark) return true; } if ((code & ~0xFF) === 0x0E00) { // Thai/Lao chars (with combining mark) return true; } return false; }
[ "function", "isProblematicUnicodeLocation", "(", "code", ")", "{", "if", "(", "code", "<=", "0x1F", ")", "{", "return", "true", ";", "}", "if", "(", "code", ">=", "0x80", "&&", "code", "<=", "0x9F", ")", "{", "return", "true", ";", "}", "if", "(", "(", "code", ">=", "0x2000", "&&", "code", "<=", "0x200F", ")", "||", "(", "code", ">=", "0x2028", "&&", "code", "<=", "0x202F", ")", "||", "(", "code", ">=", "0x2060", "&&", "code", "<=", "0x206F", ")", ")", "{", "return", "true", ";", "}", "if", "(", "code", ">=", "0xFFF0", "&&", "code", "<=", "0xFFFF", ")", "{", "return", "true", ";", "}", "switch", "(", "code", ")", "{", "case", "0x7F", ":", "case", "0xA0", ":", "case", "0xAD", ":", "case", "0x2011", ":", "case", "0x205F", ":", "case", "0x25CC", ":", "return", "true", ";", "}", "if", "(", "(", "code", "&", "~", "0xFF", ")", "===", "0x0E00", ")", "{", "return", "true", ";", "}", "return", "false", ";", "}" ]
Helper function for |adjustMapping|. @return {boolean}
[ "Helper", "function", "for", "|adjustMapping|", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L16916-L16944
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
type1FontGlyphMapping
function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) { var charCodeToGlyphId = Object.create(null); var glyphId, charCode, baseEncoding; if (properties.baseEncodingName) { // If a valid base encoding name was used, the mapping is initialized with // that. baseEncoding = Encodings[properties.baseEncodingName]; for (charCode = 0; charCode < baseEncoding.length; charCode++) { glyphId = glyphNames.indexOf(baseEncoding[charCode]); if (glyphId >= 0) { charCodeToGlyphId[charCode] = glyphId; } else { charCodeToGlyphId[charCode] = 0; // notdef } } } else if (!!(properties.flags & FontFlags.Symbolic)) { // For a symbolic font the encoding should be the fonts built-in // encoding. for (charCode in builtInEncoding) { charCodeToGlyphId[charCode] = builtInEncoding[charCode]; } } else { // For non-symbolic fonts that don't have a base encoding the standard // encoding should be used. baseEncoding = Encodings.StandardEncoding; for (charCode = 0; charCode < baseEncoding.length; charCode++) { glyphId = glyphNames.indexOf(baseEncoding[charCode]); if (glyphId >= 0) { charCodeToGlyphId[charCode] = glyphId; } else { charCodeToGlyphId[charCode] = 0; // notdef } } } // Lastly, merge in the differences. var differences = properties.differences; if (differences) { for (charCode in differences) { var glyphName = differences[charCode]; glyphId = glyphNames.indexOf(glyphName); if (glyphId >= 0) { charCodeToGlyphId[charCode] = glyphId; } else { charCodeToGlyphId[charCode] = 0; // notdef } } } return charCodeToGlyphId; }
javascript
function type1FontGlyphMapping(properties, builtInEncoding, glyphNames) { var charCodeToGlyphId = Object.create(null); var glyphId, charCode, baseEncoding; if (properties.baseEncodingName) { // If a valid base encoding name was used, the mapping is initialized with // that. baseEncoding = Encodings[properties.baseEncodingName]; for (charCode = 0; charCode < baseEncoding.length; charCode++) { glyphId = glyphNames.indexOf(baseEncoding[charCode]); if (glyphId >= 0) { charCodeToGlyphId[charCode] = glyphId; } else { charCodeToGlyphId[charCode] = 0; // notdef } } } else if (!!(properties.flags & FontFlags.Symbolic)) { // For a symbolic font the encoding should be the fonts built-in // encoding. for (charCode in builtInEncoding) { charCodeToGlyphId[charCode] = builtInEncoding[charCode]; } } else { // For non-symbolic fonts that don't have a base encoding the standard // encoding should be used. baseEncoding = Encodings.StandardEncoding; for (charCode = 0; charCode < baseEncoding.length; charCode++) { glyphId = glyphNames.indexOf(baseEncoding[charCode]); if (glyphId >= 0) { charCodeToGlyphId[charCode] = glyphId; } else { charCodeToGlyphId[charCode] = 0; // notdef } } } // Lastly, merge in the differences. var differences = properties.differences; if (differences) { for (charCode in differences) { var glyphName = differences[charCode]; glyphId = glyphNames.indexOf(glyphName); if (glyphId >= 0) { charCodeToGlyphId[charCode] = glyphId; } else { charCodeToGlyphId[charCode] = 0; // notdef } } } return charCodeToGlyphId; }
[ "function", "type1FontGlyphMapping", "(", "properties", ",", "builtInEncoding", ",", "glyphNames", ")", "{", "var", "charCodeToGlyphId", "=", "Object", ".", "create", "(", "null", ")", ";", "var", "glyphId", ",", "charCode", ",", "baseEncoding", ";", "if", "(", "properties", ".", "baseEncodingName", ")", "{", "baseEncoding", "=", "Encodings", "[", "properties", ".", "baseEncodingName", "]", ";", "for", "(", "charCode", "=", "0", ";", "charCode", "<", "baseEncoding", ".", "length", ";", "charCode", "++", ")", "{", "glyphId", "=", "glyphNames", ".", "indexOf", "(", "baseEncoding", "[", "charCode", "]", ")", ";", "if", "(", "glyphId", ">=", "0", ")", "{", "charCodeToGlyphId", "[", "charCode", "]", "=", "glyphId", ";", "}", "else", "{", "charCodeToGlyphId", "[", "charCode", "]", "=", "0", ";", "}", "}", "}", "else", "if", "(", "!", "!", "(", "properties", ".", "flags", "&", "FontFlags", ".", "Symbolic", ")", ")", "{", "for", "(", "charCode", "in", "builtInEncoding", ")", "{", "charCodeToGlyphId", "[", "charCode", "]", "=", "builtInEncoding", "[", "charCode", "]", ";", "}", "}", "else", "{", "baseEncoding", "=", "Encodings", ".", "StandardEncoding", ";", "for", "(", "charCode", "=", "0", ";", "charCode", "<", "baseEncoding", ".", "length", ";", "charCode", "++", ")", "{", "glyphId", "=", "glyphNames", ".", "indexOf", "(", "baseEncoding", "[", "charCode", "]", ")", ";", "if", "(", "glyphId", ">=", "0", ")", "{", "charCodeToGlyphId", "[", "charCode", "]", "=", "glyphId", ";", "}", "else", "{", "charCodeToGlyphId", "[", "charCode", "]", "=", "0", ";", "}", "}", "}", "var", "differences", "=", "properties", ".", "differences", ";", "if", "(", "differences", ")", "{", "for", "(", "charCode", "in", "differences", ")", "{", "var", "glyphName", "=", "differences", "[", "charCode", "]", ";", "glyphId", "=", "glyphNames", ".", "indexOf", "(", "glyphName", ")", ";", "if", "(", "glyphId", ">=", "0", ")", "{", "charCodeToGlyphId", "[", "charCode", "]", "=", "glyphId", ";", "}", "else", "{", "charCodeToGlyphId", "[", "charCode", "]", "=", "0", ";", "}", "}", "}", "return", "charCodeToGlyphId", ";", "}" ]
Shared logic for building a char code to glyph id mapping for Type1 and simple CFF fonts. See section 9.6.6.2 of the spec. @param {Object} properties Font properties object. @param {Object} builtInEncoding The encoding contained within the actual font data. @param {Array} Array of glyph names where the index is the glyph ID. @returns {Object} A char code to glyph ID map.
[ "Shared", "logic", "for", "building", "a", "char", "code", "to", "glyph", "id", "mapping", "for", "Type1", "and", "simple", "CFF", "fonts", ".", "See", "section", "9", ".", "6", ".", "6", ".", "2", "of", "the", "spec", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L19037-L19087
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
Type1Font
function Type1Font(name, file, properties) { // Some bad generators embed pfb file as is, we have to strip 6-byte headers. // Also, length1 and length2 might be off by 6 bytes as well. // http://www.math.ubc.ca/~cass/piscript/type1.pdf var PFB_HEADER_SIZE = 6; var headerBlockLength = properties.length1; var eexecBlockLength = properties.length2; var pfbHeader = file.peekBytes(PFB_HEADER_SIZE); var pfbHeaderPresent = pfbHeader[0] === 0x80 && pfbHeader[1] === 0x01; if (pfbHeaderPresent) { file.skip(PFB_HEADER_SIZE); headerBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) | (pfbHeader[3] << 8) | pfbHeader[2]; } // Get the data block containing glyphs and subrs informations var headerBlock = new Stream(file.getBytes(headerBlockLength)); var headerBlockParser = new Type1Parser(headerBlock); headerBlockParser.extractFontHeader(properties); if (pfbHeaderPresent) { pfbHeader = file.getBytes(PFB_HEADER_SIZE); eexecBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) | (pfbHeader[3] << 8) | pfbHeader[2]; } // Decrypt the data blocks and retrieve it's content var eexecBlock = new Stream(file.getBytes(eexecBlockLength)); var eexecBlockParser = new Type1Parser(eexecBlock, true); var data = eexecBlockParser.extractFontProgram(); for (var info in data.properties) { properties[info] = data.properties[info]; } var charstrings = data.charstrings; var type2Charstrings = this.getType2Charstrings(charstrings); var subrs = this.getType2Subrs(data.subrs); this.charstrings = charstrings; this.data = this.wrap(name, type2Charstrings, this.charstrings, subrs, properties); this.seacs = this.getSeacs(data.charstrings); }
javascript
function Type1Font(name, file, properties) { // Some bad generators embed pfb file as is, we have to strip 6-byte headers. // Also, length1 and length2 might be off by 6 bytes as well. // http://www.math.ubc.ca/~cass/piscript/type1.pdf var PFB_HEADER_SIZE = 6; var headerBlockLength = properties.length1; var eexecBlockLength = properties.length2; var pfbHeader = file.peekBytes(PFB_HEADER_SIZE); var pfbHeaderPresent = pfbHeader[0] === 0x80 && pfbHeader[1] === 0x01; if (pfbHeaderPresent) { file.skip(PFB_HEADER_SIZE); headerBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) | (pfbHeader[3] << 8) | pfbHeader[2]; } // Get the data block containing glyphs and subrs informations var headerBlock = new Stream(file.getBytes(headerBlockLength)); var headerBlockParser = new Type1Parser(headerBlock); headerBlockParser.extractFontHeader(properties); if (pfbHeaderPresent) { pfbHeader = file.getBytes(PFB_HEADER_SIZE); eexecBlockLength = (pfbHeader[5] << 24) | (pfbHeader[4] << 16) | (pfbHeader[3] << 8) | pfbHeader[2]; } // Decrypt the data blocks and retrieve it's content var eexecBlock = new Stream(file.getBytes(eexecBlockLength)); var eexecBlockParser = new Type1Parser(eexecBlock, true); var data = eexecBlockParser.extractFontProgram(); for (var info in data.properties) { properties[info] = data.properties[info]; } var charstrings = data.charstrings; var type2Charstrings = this.getType2Charstrings(charstrings); var subrs = this.getType2Subrs(data.subrs); this.charstrings = charstrings; this.data = this.wrap(name, type2Charstrings, this.charstrings, subrs, properties); this.seacs = this.getSeacs(data.charstrings); }
[ "function", "Type1Font", "(", "name", ",", "file", ",", "properties", ")", "{", "var", "PFB_HEADER_SIZE", "=", "6", ";", "var", "headerBlockLength", "=", "properties", ".", "length1", ";", "var", "eexecBlockLength", "=", "properties", ".", "length2", ";", "var", "pfbHeader", "=", "file", ".", "peekBytes", "(", "PFB_HEADER_SIZE", ")", ";", "var", "pfbHeaderPresent", "=", "pfbHeader", "[", "0", "]", "===", "0x80", "&&", "pfbHeader", "[", "1", "]", "===", "0x01", ";", "if", "(", "pfbHeaderPresent", ")", "{", "file", ".", "skip", "(", "PFB_HEADER_SIZE", ")", ";", "headerBlockLength", "=", "(", "pfbHeader", "[", "5", "]", "<<", "24", ")", "|", "(", "pfbHeader", "[", "4", "]", "<<", "16", ")", "|", "(", "pfbHeader", "[", "3", "]", "<<", "8", ")", "|", "pfbHeader", "[", "2", "]", ";", "}", "var", "headerBlock", "=", "new", "Stream", "(", "file", ".", "getBytes", "(", "headerBlockLength", ")", ")", ";", "var", "headerBlockParser", "=", "new", "Type1Parser", "(", "headerBlock", ")", ";", "headerBlockParser", ".", "extractFontHeader", "(", "properties", ")", ";", "if", "(", "pfbHeaderPresent", ")", "{", "pfbHeader", "=", "file", ".", "getBytes", "(", "PFB_HEADER_SIZE", ")", ";", "eexecBlockLength", "=", "(", "pfbHeader", "[", "5", "]", "<<", "24", ")", "|", "(", "pfbHeader", "[", "4", "]", "<<", "16", ")", "|", "(", "pfbHeader", "[", "3", "]", "<<", "8", ")", "|", "pfbHeader", "[", "2", "]", ";", "}", "var", "eexecBlock", "=", "new", "Stream", "(", "file", ".", "getBytes", "(", "eexecBlockLength", ")", ")", ";", "var", "eexecBlockParser", "=", "new", "Type1Parser", "(", "eexecBlock", ",", "true", ")", ";", "var", "data", "=", "eexecBlockParser", ".", "extractFontProgram", "(", ")", ";", "for", "(", "var", "info", "in", "data", ".", "properties", ")", "{", "properties", "[", "info", "]", "=", "data", ".", "properties", "[", "info", "]", ";", "}", "var", "charstrings", "=", "data", ".", "charstrings", ";", "var", "type2Charstrings", "=", "this", ".", "getType2Charstrings", "(", "charstrings", ")", ";", "var", "subrs", "=", "this", ".", "getType2Subrs", "(", "data", ".", "subrs", ")", ";", "this", ".", "charstrings", "=", "charstrings", ";", "this", ".", "data", "=", "this", ".", "wrap", "(", "name", ",", "type2Charstrings", ",", "this", ".", "charstrings", ",", "subrs", ",", "properties", ")", ";", "this", ".", "seacs", "=", "this", ".", "getSeacs", "(", "data", ".", "charstrings", ")", ";", "}" ]
Type1Font is also a CIDFontType0.
[ "Type1Font", "is", "also", "a", "CIDFontType0", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L19831-L19873
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
CFFDict_setByKey
function CFFDict_setByKey(key, value) { if (!(key in this.keyToNameMap)) { return false; } // ignore empty values if (value.length === 0) { return true; } var type = this.types[key]; // remove the array wrapping these types of values if (type === 'num' || type === 'sid' || type === 'offset') { value = value[0]; } this.values[key] = value; return true; }
javascript
function CFFDict_setByKey(key, value) { if (!(key in this.keyToNameMap)) { return false; } // ignore empty values if (value.length === 0) { return true; } var type = this.types[key]; // remove the array wrapping these types of values if (type === 'num' || type === 'sid' || type === 'offset') { value = value[0]; } this.values[key] = value; return true; }
[ "function", "CFFDict_setByKey", "(", "key", ",", "value", ")", "{", "if", "(", "!", "(", "key", "in", "this", ".", "keyToNameMap", ")", ")", "{", "return", "false", ";", "}", "if", "(", "value", ".", "length", "===", "0", ")", "{", "return", "true", ";", "}", "var", "type", "=", "this", ".", "types", "[", "key", "]", ";", "if", "(", "type", "===", "'num'", "||", "type", "===", "'sid'", "||", "type", "===", "'offset'", ")", "{", "value", "=", "value", "[", "0", "]", ";", "}", "this", ".", "values", "[", "key", "]", "=", "value", ";", "return", "true", ";", "}" ]
value should always be an array
[ "value", "should", "always", "be", "an", "array" ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L20892-L20907
train
InfinniPlatform/InfinniUI
extensions/pdfViewer/pdf/build/pdf.worker.js
handleImageData
function handleImageData(handler, xref, res, image) { if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) { // For natively supported jpegs send them to the main thread for decoding. var dict = image.dict; var colorSpace = dict.get('ColorSpace', 'CS'); colorSpace = ColorSpace.parse(colorSpace, xref, res); var numComps = colorSpace.numComps; var decodePromise = handler.sendWithPromise('JpegDecode', [image.getIR(), numComps]); return decodePromise.then(function (message) { var data = message.data; return new Stream(data, 0, data.length, image.dict); }); } else { return Promise.resolve(image); } }
javascript
function handleImageData(handler, xref, res, image) { if (image instanceof JpegStream && image.isNativelyDecodable(xref, res)) { // For natively supported jpegs send them to the main thread for decoding. var dict = image.dict; var colorSpace = dict.get('ColorSpace', 'CS'); colorSpace = ColorSpace.parse(colorSpace, xref, res); var numComps = colorSpace.numComps; var decodePromise = handler.sendWithPromise('JpegDecode', [image.getIR(), numComps]); return decodePromise.then(function (message) { var data = message.data; return new Stream(data, 0, data.length, image.dict); }); } else { return Promise.resolve(image); } }
[ "function", "handleImageData", "(", "handler", ",", "xref", ",", "res", ",", "image", ")", "{", "if", "(", "image", "instanceof", "JpegStream", "&&", "image", ".", "isNativelyDecodable", "(", "xref", ",", "res", ")", ")", "{", "var", "dict", "=", "image", ".", "dict", ";", "var", "colorSpace", "=", "dict", ".", "get", "(", "'ColorSpace'", ",", "'CS'", ")", ";", "colorSpace", "=", "ColorSpace", ".", "parse", "(", "colorSpace", ",", "xref", ",", "res", ")", ";", "var", "numComps", "=", "colorSpace", ".", "numComps", ";", "var", "decodePromise", "=", "handler", ".", "sendWithPromise", "(", "'JpegDecode'", ",", "[", "image", ".", "getIR", "(", ")", ",", "numComps", "]", ")", ";", "return", "decodePromise", ".", "then", "(", "function", "(", "message", ")", "{", "var", "data", "=", "message", ".", "data", ";", "return", "new", "Stream", "(", "data", ",", "0", ",", "data", ".", "length", ",", "image", ".", "dict", ")", ";", "}", ")", ";", "}", "else", "{", "return", "Promise", ".", "resolve", "(", "image", ")", ";", "}", "}" ]
Decode the image in the main thread if it supported. Resovles the promise when the image data is ready.
[ "Decode", "the", "image", "in", "the", "main", "thread", "if", "it", "supported", ".", "Resovles", "the", "promise", "when", "the", "image", "data", "is", "ready", "." ]
fb14898a843da70f9117fa197b8aca07c858f49f
https://github.com/InfinniPlatform/InfinniUI/blob/fb14898a843da70f9117fa197b8aca07c858f49f/extensions/pdfViewer/pdf/build/pdf.worker.js#L26663-L26679
train
Alhadis/GetOptions
index.js
formatName
function formatName(input, noCamelCase){ input = input.replace(/^-+/, ""); // Convert kebab-case to camelCase if(!noCamelCase && /-/.test(input)) input = input.toLowerCase().replace(/([a-z])-+([a-z])/g, (_, a, b) => a + b.toUpperCase()); return input; }
javascript
function formatName(input, noCamelCase){ input = input.replace(/^-+/, ""); // Convert kebab-case to camelCase if(!noCamelCase && /-/.test(input)) input = input.toLowerCase().replace(/([a-z])-+([a-z])/g, (_, a, b) => a + b.toUpperCase()); return input; }
[ "function", "formatName", "(", "input", ",", "noCamelCase", ")", "{", "input", "=", "input", ".", "replace", "(", "/", "^-+", "/", ",", "\"\"", ")", ";", "if", "(", "!", "noCamelCase", "&&", "/", "-", "/", ".", "test", "(", "input", ")", ")", "input", "=", "input", ".", "toLowerCase", "(", ")", ".", "replace", "(", "/", "([a-z])-+([a-z])", "/", "g", ",", "(", "_", ",", "a", ",", "b", ")", "=>", "a", "+", "b", ".", "toUpperCase", "(", ")", ")", ";", "return", "input", ";", "}" ]
Strip leading dashes from an option name and convert it to camelCase. @param {String} input - An option's name, such as "--write-to" @param {Boolean} noCamelCase - Strip leading dashes only @return {String} @internal
[ "Strip", "leading", "dashes", "from", "an", "option", "name", "and", "convert", "it", "to", "camelCase", "." ]
246e2fadf0ecae27e20864baf3620565f0be7415
https://github.com/Alhadis/GetOptions/blob/246e2fadf0ecae27e20864baf3620565f0be7415/index.js#L150-L158
train
Alhadis/GetOptions
index.js
match
function match(input, patterns = []){ if(!patterns || 0 === patterns.length) return false; input = String(input); patterns = arrayify(patterns).filter(Boolean); for(const pattern of patterns) if((pattern === input && "string" === typeof pattern) || (pattern instanceof RegExp) && pattern.test(input)) return true; return false; }
javascript
function match(input, patterns = []){ if(!patterns || 0 === patterns.length) return false; input = String(input); patterns = arrayify(patterns).filter(Boolean); for(const pattern of patterns) if((pattern === input && "string" === typeof pattern) || (pattern instanceof RegExp) && pattern.test(input)) return true; return false; }
[ "function", "match", "(", "input", ",", "patterns", "=", "[", "]", ")", "{", "if", "(", "!", "patterns", "||", "0", "===", "patterns", ".", "length", ")", "return", "false", ";", "input", "=", "String", "(", "input", ")", ";", "patterns", "=", "arrayify", "(", "patterns", ")", ".", "filter", "(", "Boolean", ")", ";", "for", "(", "const", "pattern", "of", "patterns", ")", "if", "(", "(", "pattern", "===", "input", "&&", "\"string\"", "===", "typeof", "pattern", ")", "||", "(", "pattern", "instanceof", "RegExp", ")", "&&", "pattern", ".", "test", "(", "input", ")", ")", "return", "true", ";", "return", "false", ";", "}" ]
Test a string against a list of patterns. @param {String} input @param {String[]|RegExp[]} patterns @return {Boolean} @internal
[ "Test", "a", "string", "against", "a", "list", "of", "patterns", "." ]
246e2fadf0ecae27e20864baf3620565f0be7415
https://github.com/Alhadis/GetOptions/blob/246e2fadf0ecae27e20864baf3620565f0be7415/index.js#L169-L180
train
Alhadis/GetOptions
index.js
uniqueStrings
function uniqueStrings(input){ const output = {}; for(let i = 0, l = input.length; i < l; ++i) output[input[i]] = true; return Object.keys(output); }
javascript
function uniqueStrings(input){ const output = {}; for(let i = 0, l = input.length; i < l; ++i) output[input[i]] = true; return Object.keys(output); }
[ "function", "uniqueStrings", "(", "input", ")", "{", "const", "output", "=", "{", "}", ";", "for", "(", "let", "i", "=", "0", ",", "l", "=", "input", ".", "length", ";", "i", "<", "l", ";", "++", "i", ")", "output", "[", "input", "[", "i", "]", "]", "=", "true", ";", "return", "Object", ".", "keys", "(", "output", ")", ";", "}" ]
Filter duplicate strings from an array. @param {String[]} input @return {Array} @internal
[ "Filter", "duplicate", "strings", "from", "an", "array", "." ]
246e2fadf0ecae27e20864baf3620565f0be7415
https://github.com/Alhadis/GetOptions/blob/246e2fadf0ecae27e20864baf3620565f0be7415/index.js#L190-L195
train
Alhadis/GetOptions
index.js
unstringify
function unstringify(input){ input = String(input || ""); const tokens = []; const {length} = input; let quoteChar = ""; // Quote-type enclosing current region let tokenData = ""; // Characters currently being collected let isEscaped = false; // Flag identifying an escape sequence for(let i = 0; i < length; ++i){ const char = input[i]; // Previous character was a backslash if(isEscaped){ tokenData += char; isEscaped = false; continue; } // Whitespace: terminate token unless quoted if(!quoteChar && /[ \t\n]/.test(char)){ tokenData && tokens.push(tokenData); tokenData = ""; continue; } // Backslash: escape next character if("\\" === char){ isEscaped = true; // Swallow backslash if it escapes a metacharacter const next = input[i + 1]; if(quoteChar && (quoteChar === next || "\\" === next) || !quoteChar && /[- \t\n\\'"`]/.test(next)) continue; } // Quote marks else if((!quoteChar || char === quoteChar) && /['"`]/.test(char)){ quoteChar = quoteChar === char ? "" : char; continue; } tokenData += char; } if(tokenData) tokens.push(tokenData); return tokens; }
javascript
function unstringify(input){ input = String(input || ""); const tokens = []; const {length} = input; let quoteChar = ""; // Quote-type enclosing current region let tokenData = ""; // Characters currently being collected let isEscaped = false; // Flag identifying an escape sequence for(let i = 0; i < length; ++i){ const char = input[i]; // Previous character was a backslash if(isEscaped){ tokenData += char; isEscaped = false; continue; } // Whitespace: terminate token unless quoted if(!quoteChar && /[ \t\n]/.test(char)){ tokenData && tokens.push(tokenData); tokenData = ""; continue; } // Backslash: escape next character if("\\" === char){ isEscaped = true; // Swallow backslash if it escapes a metacharacter const next = input[i + 1]; if(quoteChar && (quoteChar === next || "\\" === next) || !quoteChar && /[- \t\n\\'"`]/.test(next)) continue; } // Quote marks else if((!quoteChar || char === quoteChar) && /['"`]/.test(char)){ quoteChar = quoteChar === char ? "" : char; continue; } tokenData += char; } if(tokenData) tokens.push(tokenData); return tokens; }
[ "function", "unstringify", "(", "input", ")", "{", "input", "=", "String", "(", "input", "||", "\"\"", ")", ";", "const", "tokens", "=", "[", "]", ";", "const", "{", "length", "}", "=", "input", ";", "let", "quoteChar", "=", "\"\"", ";", "let", "tokenData", "=", "\"\"", ";", "let", "isEscaped", "=", "false", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "length", ";", "++", "i", ")", "{", "const", "char", "=", "input", "[", "i", "]", ";", "if", "(", "isEscaped", ")", "{", "tokenData", "+=", "char", ";", "isEscaped", "=", "false", ";", "continue", ";", "}", "if", "(", "!", "quoteChar", "&&", "/", "[ \\t\\n]", "/", ".", "test", "(", "char", ")", ")", "{", "tokenData", "&&", "tokens", ".", "push", "(", "tokenData", ")", ";", "tokenData", "=", "\"\"", ";", "continue", ";", "}", "if", "(", "\"\\\\\"", "===", "\\\\", ")", "char", "else", "{", "isEscaped", "=", "true", ";", "const", "next", "=", "input", "[", "i", "+", "1", "]", ";", "if", "(", "quoteChar", "&&", "(", "quoteChar", "===", "next", "||", "\"\\\\\"", "===", "\\\\", ")", "||", "next", ")", "!", "quoteChar", "&&", "/", "[- \\t\\n\\\\'\"`]", "/", ".", "test", "(", "next", ")", "}", "continue", ";", "}", "if", "(", "(", "!", "quoteChar", "||", "char", "===", "quoteChar", ")", "&&", "/", "['\"`]", "/", ".", "test", "(", "char", ")", ")", "{", "quoteChar", "=", "quoteChar", "===", "char", "?", "\"\"", ":", "char", ";", "continue", ";", "}", "tokenData", "+=", "char", ";", "}" ]
Parse a string as a whitespace-delimited list of options, preserving quoted and escaped characters. @example unstringify("--foo --bar") => ["--foo", "--bar"]; @example unstringify('--foo "bar baz"') => ["--foo", '"bar baz"']; @param {String} input @return {Object} @internal
[ "Parse", "a", "string", "as", "a", "whitespace", "-", "delimited", "list", "of", "options", "preserving", "quoted", "and", "escaped", "characters", "." ]
246e2fadf0ecae27e20864baf3620565f0be7415
https://github.com/Alhadis/GetOptions/blob/246e2fadf0ecae27e20864baf3620565f0be7415/index.js#L208-L256
train
Alhadis/GetOptions
index.js
autoOpts
function autoOpts(input, config = {}){ const opts = new Object(null); const argv = []; let argvEnd; // Bail early if passed a blank string if(!input) return opts; // Stop parsing options after a double-dash const stopAt = input.indexOf("--"); if(stopAt !== -1){ argvEnd = input.slice(stopAt + 1); input = input.slice(0, stopAt); } for(let i = 0, l = input.length; i < l; ++i){ let name = input[i]; // Appears to be an option if(/^-/.test(name)){ // Equals sign is used, should it become the option's value? if(!config.ignoreEquals && /=/.test(name)){ const split = name.split(/=/); name = formatName(split[0], config.noCamelCase); opts[name] = split.slice(1).join("="); } else{ name = formatName(name, config.noCamelCase); // Treat a following non-option as this option's value const next = input[i + 1]; if(next != null && !/^-/.test(next)){ // There's another option after this one. Collect multiple non-options into an array. const nextOpt = input.findIndex((s, I) => I > i && /^-/.test(s)); if(nextOpt !== -1){ opts[name] = input.slice(i + 1, nextOpt); // There's only one value to store; don't wrap it in an array if(nextOpt - i < 3) opts[name] = opts[name][0]; i = nextOpt - 1; } // We're at the last option. Don't touch argv; assume it's a boolean-type option else opts[name] = true; } // No arguments defined. Assume it's a boolean-type option. else opts[name] = true; } } // Non-option: add to argv else argv.push(name); } // Add any additional arguments that were found after a "--" delimiter if(argvEnd) argv.push(...argvEnd); return { options: opts, argv: argv, }; }
javascript
function autoOpts(input, config = {}){ const opts = new Object(null); const argv = []; let argvEnd; // Bail early if passed a blank string if(!input) return opts; // Stop parsing options after a double-dash const stopAt = input.indexOf("--"); if(stopAt !== -1){ argvEnd = input.slice(stopAt + 1); input = input.slice(0, stopAt); } for(let i = 0, l = input.length; i < l; ++i){ let name = input[i]; // Appears to be an option if(/^-/.test(name)){ // Equals sign is used, should it become the option's value? if(!config.ignoreEquals && /=/.test(name)){ const split = name.split(/=/); name = formatName(split[0], config.noCamelCase); opts[name] = split.slice(1).join("="); } else{ name = formatName(name, config.noCamelCase); // Treat a following non-option as this option's value const next = input[i + 1]; if(next != null && !/^-/.test(next)){ // There's another option after this one. Collect multiple non-options into an array. const nextOpt = input.findIndex((s, I) => I > i && /^-/.test(s)); if(nextOpt !== -1){ opts[name] = input.slice(i + 1, nextOpt); // There's only one value to store; don't wrap it in an array if(nextOpt - i < 3) opts[name] = opts[name][0]; i = nextOpt - 1; } // We're at the last option. Don't touch argv; assume it's a boolean-type option else opts[name] = true; } // No arguments defined. Assume it's a boolean-type option. else opts[name] = true; } } // Non-option: add to argv else argv.push(name); } // Add any additional arguments that were found after a "--" delimiter if(argvEnd) argv.push(...argvEnd); return { options: opts, argv: argv, }; }
[ "function", "autoOpts", "(", "input", ",", "config", "=", "{", "}", ")", "{", "const", "opts", "=", "new", "Object", "(", "null", ")", ";", "const", "argv", "=", "[", "]", ";", "let", "argvEnd", ";", "if", "(", "!", "input", ")", "return", "opts", ";", "const", "stopAt", "=", "input", ".", "indexOf", "(", "\"--\"", ")", ";", "if", "(", "stopAt", "!==", "-", "1", ")", "{", "argvEnd", "=", "input", ".", "slice", "(", "stopAt", "+", "1", ")", ";", "input", "=", "input", ".", "slice", "(", "0", ",", "stopAt", ")", ";", "}", "for", "(", "let", "i", "=", "0", ",", "l", "=", "input", ".", "length", ";", "i", "<", "l", ";", "++", "i", ")", "{", "let", "name", "=", "input", "[", "i", "]", ";", "if", "(", "/", "^-", "/", ".", "test", "(", "name", ")", ")", "{", "if", "(", "!", "config", ".", "ignoreEquals", "&&", "/", "=", "/", ".", "test", "(", "name", ")", ")", "{", "const", "split", "=", "name", ".", "split", "(", "/", "=", "/", ")", ";", "name", "=", "formatName", "(", "split", "[", "0", "]", ",", "config", ".", "noCamelCase", ")", ";", "opts", "[", "name", "]", "=", "split", ".", "slice", "(", "1", ")", ".", "join", "(", "\"=\"", ")", ";", "}", "else", "{", "name", "=", "formatName", "(", "name", ",", "config", ".", "noCamelCase", ")", ";", "const", "next", "=", "input", "[", "i", "+", "1", "]", ";", "if", "(", "next", "!=", "null", "&&", "!", "/", "^-", "/", ".", "test", "(", "next", ")", ")", "{", "const", "nextOpt", "=", "input", ".", "findIndex", "(", "(", "s", ",", "I", ")", "=>", "I", ">", "i", "&&", "/", "^-", "/", ".", "test", "(", "s", ")", ")", ";", "if", "(", "nextOpt", "!==", "-", "1", ")", "{", "opts", "[", "name", "]", "=", "input", ".", "slice", "(", "i", "+", "1", ",", "nextOpt", ")", ";", "if", "(", "nextOpt", "-", "i", "<", "3", ")", "opts", "[", "name", "]", "=", "opts", "[", "name", "]", "[", "0", "]", ";", "i", "=", "nextOpt", "-", "1", ";", "}", "else", "opts", "[", "name", "]", "=", "true", ";", "}", "else", "opts", "[", "name", "]", "=", "true", ";", "}", "}", "else", "argv", ".", "push", "(", "name", ")", ";", "}", "if", "(", "argvEnd", ")", "argv", ".", "push", "(", "...", "argvEnd", ")", ";", "return", "{", "options", ":", "opts", ",", "argv", ":", "argv", ",", "}", ";", "}" ]
Parse input using "best guess" logic. Called when no optdef is passed. Essentially, the following assumptions are made about input: - Anything beginning with at least one dash is an option name - Options without arguments mean a boolean "true" - Option-reading stops at "--" - Anything caught between two options becomes the first option's value @param {Array} input @param {Object} [config={}] @return {Object} @internal
[ "Parse", "input", "using", "best", "guess", "logic", ".", "Called", "when", "no", "optdef", "is", "passed", "." ]
246e2fadf0ecae27e20864baf3620565f0be7415
https://github.com/Alhadis/GetOptions/blob/246e2fadf0ecae27e20864baf3620565f0be7415/index.js#L274-L343
train
Alhadis/GetOptions
index.js
resolveDuplicate
function resolveDuplicate(option, name, value){ switch(duplicates){ // Use the first value (or set of values); discard any following duplicates case "use-first": return result.options[name]; // Use the last value (or set of values); discard any preceding duplicates. Default. case "use-last": default: return result.options[name] = value; // Use the first/last options; treat any following/preceding duplicates as argv items respectively case "limit-first": case "limit-last": result.argv.push(option.prevMatchedName, ...arrayify(value)); break; // Throw an exception case "error": const error = new TypeError(`Attempting to reassign option "${name}" with value(s) ${JSON.stringify(value)}`); error.affectedOption = option; error.affectedValue = value; throw error; // Add parameters of duplicate options to the argument list of the first case "append": const oldValues = arrayify(result.options[name]); const newValues = arrayify(value); result.options[name] = oldValues.concat(newValues); break; // Store parameters of duplicated options in a multidimensional array case "stack": { let oldValues = result.options[name]; const newValues = arrayify(value); // This option hasn't been "stacked" yet if(!option.stacked){ oldValues = arrayify(oldValues); result.options[name] = [oldValues, newValues]; option.stacked = true; } // Already "stacked", so just shove the values onto the end of the array else result.options[name].push(arrayify(newValues)); break; } // Store each duplicated value in an array using the order they appear case "stack-values": { let values = result.options[name]; // First time "stacking" this option (nesting its value/s inside an array) if(!option.stacked){ const stack = []; for(const value of arrayify(values)) stack.push([value]); values = stack; option.stacked = true; } arrayify(value).forEach((v, i) => { // An array hasn't been created at this index yet, // because an earlier option wasn't given enough parameters. if(undefined === values[i]) values[i] = Array(values[0].length - 1); values[i].push(v); }); result.options[name] = values; break; } } }
javascript
function resolveDuplicate(option, name, value){ switch(duplicates){ // Use the first value (or set of values); discard any following duplicates case "use-first": return result.options[name]; // Use the last value (or set of values); discard any preceding duplicates. Default. case "use-last": default: return result.options[name] = value; // Use the first/last options; treat any following/preceding duplicates as argv items respectively case "limit-first": case "limit-last": result.argv.push(option.prevMatchedName, ...arrayify(value)); break; // Throw an exception case "error": const error = new TypeError(`Attempting to reassign option "${name}" with value(s) ${JSON.stringify(value)}`); error.affectedOption = option; error.affectedValue = value; throw error; // Add parameters of duplicate options to the argument list of the first case "append": const oldValues = arrayify(result.options[name]); const newValues = arrayify(value); result.options[name] = oldValues.concat(newValues); break; // Store parameters of duplicated options in a multidimensional array case "stack": { let oldValues = result.options[name]; const newValues = arrayify(value); // This option hasn't been "stacked" yet if(!option.stacked){ oldValues = arrayify(oldValues); result.options[name] = [oldValues, newValues]; option.stacked = true; } // Already "stacked", so just shove the values onto the end of the array else result.options[name].push(arrayify(newValues)); break; } // Store each duplicated value in an array using the order they appear case "stack-values": { let values = result.options[name]; // First time "stacking" this option (nesting its value/s inside an array) if(!option.stacked){ const stack = []; for(const value of arrayify(values)) stack.push([value]); values = stack; option.stacked = true; } arrayify(value).forEach((v, i) => { // An array hasn't been created at this index yet, // because an earlier option wasn't given enough parameters. if(undefined === values[i]) values[i] = Array(values[0].length - 1); values[i].push(v); }); result.options[name] = values; break; } } }
[ "function", "resolveDuplicate", "(", "option", ",", "name", ",", "value", ")", "{", "switch", "(", "duplicates", ")", "{", "case", "\"use-first\"", ":", "return", "result", ".", "options", "[", "name", "]", ";", "case", "\"use-last\"", ":", "default", ":", "return", "result", ".", "options", "[", "name", "]", "=", "value", ";", "case", "\"limit-first\"", ":", "case", "\"limit-last\"", ":", "result", ".", "argv", ".", "push", "(", "option", ".", "prevMatchedName", ",", "...", "arrayify", "(", "value", ")", ")", ";", "break", ";", "case", "\"error\"", ":", "const", "error", "=", "new", "TypeError", "(", "`", "${", "name", "}", "${", "JSON", ".", "stringify", "(", "value", ")", "}", "`", ")", ";", "error", ".", "affectedOption", "=", "option", ";", "error", ".", "affectedValue", "=", "value", ";", "throw", "error", ";", "case", "\"append\"", ":", "const", "oldValues", "=", "arrayify", "(", "result", ".", "options", "[", "name", "]", ")", ";", "const", "newValues", "=", "arrayify", "(", "value", ")", ";", "result", ".", "options", "[", "name", "]", "=", "oldValues", ".", "concat", "(", "newValues", ")", ";", "break", ";", "case", "\"stack\"", ":", "{", "let", "oldValues", "=", "result", ".", "options", "[", "name", "]", ";", "const", "newValues", "=", "arrayify", "(", "value", ")", ";", "if", "(", "!", "option", ".", "stacked", ")", "{", "oldValues", "=", "arrayify", "(", "oldValues", ")", ";", "result", ".", "options", "[", "name", "]", "=", "[", "oldValues", ",", "newValues", "]", ";", "option", ".", "stacked", "=", "true", ";", "}", "else", "result", ".", "options", "[", "name", "]", ".", "push", "(", "arrayify", "(", "newValues", ")", ")", ";", "break", ";", "}", "case", "\"stack-values\"", ":", "{", "let", "values", "=", "result", ".", "options", "[", "name", "]", ";", "if", "(", "!", "option", ".", "stacked", ")", "{", "const", "stack", "=", "[", "]", ";", "for", "(", "const", "value", "of", "arrayify", "(", "values", ")", ")", "stack", ".", "push", "(", "[", "value", "]", ")", ";", "values", "=", "stack", ";", "option", ".", "stacked", "=", "true", ";", "}", "arrayify", "(", "value", ")", ".", "forEach", "(", "(", "v", ",", "i", ")", "=>", "{", "if", "(", "undefined", "===", "values", "[", "i", "]", ")", "values", "[", "i", "]", "=", "Array", "(", "values", "[", "0", "]", ".", "length", "-", "1", ")", ";", "values", "[", "i", "]", ".", "push", "(", "v", ")", ";", "}", ")", ";", "result", ".", "options", "[", "name", "]", "=", "values", ";", "break", ";", "}", "}", "}" ]
Manage duplicated option values
[ "Manage", "duplicated", "option", "values" ]
246e2fadf0ecae27e20864baf3620565f0be7415
https://github.com/Alhadis/GetOptions/blob/246e2fadf0ecae27e20864baf3620565f0be7415/index.js#L421-L498
train
Alhadis/GetOptions
index.js
setValue
function setValue(option, value){ // Assign the value only to the option name it matched if(noAliasPropagation){ let name = option.lastMatchedName; // Special alternative: // In lieu of using the matched option name, use the first --long-name only if("first-only" === noAliasPropagation) name = option.longNames[0] || option.shortNames[0]; // camelCase? name = formatName(name, noCamelCase); // This option's already been set before if(result.options[name]) resolveDuplicate(option, name, value); else result.options[name] = value; } // Copy across every alias this option's recognised by else{ const {names} = option; for(let name of names){ // Decide whether to camelCase this option name name = formatName(name, noCamelCase); // Ascertain if this option's being duplicated if(result.options[name]) resolveDuplicate(option, name, value); result.options[name] = value; } } }
javascript
function setValue(option, value){ // Assign the value only to the option name it matched if(noAliasPropagation){ let name = option.lastMatchedName; // Special alternative: // In lieu of using the matched option name, use the first --long-name only if("first-only" === noAliasPropagation) name = option.longNames[0] || option.shortNames[0]; // camelCase? name = formatName(name, noCamelCase); // This option's already been set before if(result.options[name]) resolveDuplicate(option, name, value); else result.options[name] = value; } // Copy across every alias this option's recognised by else{ const {names} = option; for(let name of names){ // Decide whether to camelCase this option name name = formatName(name, noCamelCase); // Ascertain if this option's being duplicated if(result.options[name]) resolveDuplicate(option, name, value); result.options[name] = value; } } }
[ "function", "setValue", "(", "option", ",", "value", ")", "{", "if", "(", "noAliasPropagation", ")", "{", "let", "name", "=", "option", ".", "lastMatchedName", ";", "if", "(", "\"first-only\"", "===", "noAliasPropagation", ")", "name", "=", "option", ".", "longNames", "[", "0", "]", "||", "option", ".", "shortNames", "[", "0", "]", ";", "name", "=", "formatName", "(", "name", ",", "noCamelCase", ")", ";", "if", "(", "result", ".", "options", "[", "name", "]", ")", "resolveDuplicate", "(", "option", ",", "name", ",", "value", ")", ";", "else", "result", ".", "options", "[", "name", "]", "=", "value", ";", "}", "else", "{", "const", "{", "names", "}", "=", "option", ";", "for", "(", "let", "name", "of", "names", ")", "{", "name", "=", "formatName", "(", "name", ",", "noCamelCase", ")", ";", "if", "(", "result", ".", "options", "[", "name", "]", ")", "resolveDuplicate", "(", "option", ",", "name", ",", "value", ")", ";", "result", ".", "options", "[", "name", "]", "=", "value", ";", "}", "}", "}" ]
Assign an option's parsed value to the result's `.options` property
[ "Assign", "an", "option", "s", "parsed", "value", "to", "the", "result", "s", ".", "options", "property" ]
246e2fadf0ecae27e20864baf3620565f0be7415
https://github.com/Alhadis/GetOptions/blob/246e2fadf0ecae27e20864baf3620565f0be7415/index.js#L502-L539
train
Alhadis/GetOptions
index.js
wrapItUp
function wrapItUp(){ let optValue = currentOption.values; // Don't store solitary values in an array. Store them directly as strings if(1 === currentOption.arity && !currentOption.variadic) optValue = optValue[0]; setValue(currentOption, optValue); currentOption.values = []; currentOption = null; }
javascript
function wrapItUp(){ let optValue = currentOption.values; // Don't store solitary values in an array. Store them directly as strings if(1 === currentOption.arity && !currentOption.variadic) optValue = optValue[0]; setValue(currentOption, optValue); currentOption.values = []; currentOption = null; }
[ "function", "wrapItUp", "(", ")", "{", "let", "optValue", "=", "currentOption", ".", "values", ";", "if", "(", "1", "===", "currentOption", ".", "arity", "&&", "!", "currentOption", ".", "variadic", ")", "optValue", "=", "optValue", "[", "0", "]", ";", "setValue", "(", "currentOption", ",", "optValue", ")", ";", "currentOption", ".", "values", "=", "[", "]", ";", "currentOption", "=", "null", ";", "}" ]
Push whatever we've currently collected for this option and reset pointer
[ "Push", "whatever", "we", "ve", "currently", "collected", "for", "this", "option", "and", "reset", "pointer" ]
246e2fadf0ecae27e20864baf3620565f0be7415
https://github.com/Alhadis/GetOptions/blob/246e2fadf0ecae27e20864baf3620565f0be7415/index.js#L543-L553
train
Alhadis/GetOptions
index.js
flip
function flip(input){ input = input.reverse(); // Flip any options back into the right order for(let i = 0, l = input.length; i < l; ++i){ const arg = input[i]; const opt = shortNames[arg] || longNames[arg]; if(opt){ const from = Math.max(0, i - opt.arity); const to = i + 1; const extract = input.slice(from, to).reverse(); input.splice(from, extract.length, ...extract); } } return input; }
javascript
function flip(input){ input = input.reverse(); // Flip any options back into the right order for(let i = 0, l = input.length; i < l; ++i){ const arg = input[i]; const opt = shortNames[arg] || longNames[arg]; if(opt){ const from = Math.max(0, i - opt.arity); const to = i + 1; const extract = input.slice(from, to).reverse(); input.splice(from, extract.length, ...extract); } } return input; }
[ "function", "flip", "(", "input", ")", "{", "input", "=", "input", ".", "reverse", "(", ")", ";", "for", "(", "let", "i", "=", "0", ",", "l", "=", "input", ".", "length", ";", "i", "<", "l", ";", "++", "i", ")", "{", "const", "arg", "=", "input", "[", "i", "]", ";", "const", "opt", "=", "shortNames", "[", "arg", "]", "||", "longNames", "[", "arg", "]", ";", "if", "(", "opt", ")", "{", "const", "from", "=", "Math", ".", "max", "(", "0", ",", "i", "-", "opt", ".", "arity", ")", ";", "const", "to", "=", "i", "+", "1", ";", "const", "extract", "=", "input", ".", "slice", "(", "from", ",", "to", ")", ".", "reverse", "(", ")", ";", "input", ".", "splice", "(", "from", ",", "extract", ".", "length", ",", "...", "extract", ")", ";", "}", "}", "return", "input", ";", "}" ]
Reverse the order of an argument list, keeping options and their parameter lists intact
[ "Reverse", "the", "order", "of", "an", "argument", "list", "keeping", "options", "and", "their", "parameter", "lists", "intact" ]
246e2fadf0ecae27e20864baf3620565f0be7415
https://github.com/Alhadis/GetOptions/blob/246e2fadf0ecae27e20864baf3620565f0be7415/index.js#L557-L574
train
logikum/md-site-engine
source/readers/read-references.js
readReferences
function readReferences( componentPath, referenceFile, filingCabinet ) { logger.showInfo( '*** Reading references...' ); // Initialize the store. getReferences( componentPath, 0, '', referenceFile, filingCabinet.references ); }
javascript
function readReferences( componentPath, referenceFile, filingCabinet ) { logger.showInfo( '*** Reading references...' ); // Initialize the store. getReferences( componentPath, 0, '', referenceFile, filingCabinet.references ); }
[ "function", "readReferences", "(", "componentPath", ",", "referenceFile", ",", "filingCabinet", ")", "{", "logger", ".", "showInfo", "(", "'*** Reading references...'", ")", ";", "getReferences", "(", "componentPath", ",", "0", ",", "''", ",", "referenceFile", ",", "filingCabinet", ".", "references", ")", ";", "}" ]
Read all references. @param {string} componentPath - The path of the components directory. @param {string} referenceFile - The name of the reference files. @param {FilingCabinet} filingCabinet - The file manager object.
[ "Read", "all", "references", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/readers/read-references.js#L15-L22
train
logikum/md-site-engine
source/readers/read-references.js
getReferences
function getReferences( componentDir, level, levelPath, referenceFile, referenceDrawer ) { // Read directory items. var componentPath = path.join( process.cwd(), componentDir ); var items = fs.readdirSync( componentPath ); items.forEach( function ( item ) { var itemPath = path.join( componentDir, item ); var prefix = levelPath === '' ? '' : levelPath + '/'; // Get item info. var stats = fs.statSync( path.join( process.cwd(), itemPath ) ); if (stats.isDirectory()) { // Get language specific references. if (level === 0) getReferences( itemPath, level + 1, prefix + item, referenceFile, referenceDrawer ); } else if (stats.isFile()) { var ext = path.extname( item ); if (ext === '.txt' && path.basename( item ) === referenceFile) { // Read reference file. var componentPath = prefix + path.basename( item, ext ); referenceDrawer.add( componentPath, getReference( itemPath ) ); logger.fileProcessed( 'Reference', itemPath ); } } } ) }
javascript
function getReferences( componentDir, level, levelPath, referenceFile, referenceDrawer ) { // Read directory items. var componentPath = path.join( process.cwd(), componentDir ); var items = fs.readdirSync( componentPath ); items.forEach( function ( item ) { var itemPath = path.join( componentDir, item ); var prefix = levelPath === '' ? '' : levelPath + '/'; // Get item info. var stats = fs.statSync( path.join( process.cwd(), itemPath ) ); if (stats.isDirectory()) { // Get language specific references. if (level === 0) getReferences( itemPath, level + 1, prefix + item, referenceFile, referenceDrawer ); } else if (stats.isFile()) { var ext = path.extname( item ); if (ext === '.txt' && path.basename( item ) === referenceFile) { // Read reference file. var componentPath = prefix + path.basename( item, ext ); referenceDrawer.add( componentPath, getReference( itemPath ) ); logger.fileProcessed( 'Reference', itemPath ); } } } ) }
[ "function", "getReferences", "(", "componentDir", ",", "level", ",", "levelPath", ",", "referenceFile", ",", "referenceDrawer", ")", "{", "var", "componentPath", "=", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "componentDir", ")", ";", "var", "items", "=", "fs", ".", "readdirSync", "(", "componentPath", ")", ";", "items", ".", "forEach", "(", "function", "(", "item", ")", "{", "var", "itemPath", "=", "path", ".", "join", "(", "componentDir", ",", "item", ")", ";", "var", "prefix", "=", "levelPath", "===", "''", "?", "''", ":", "levelPath", "+", "'/'", ";", "var", "stats", "=", "fs", ".", "statSync", "(", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "itemPath", ")", ")", ";", "if", "(", "stats", ".", "isDirectory", "(", ")", ")", "{", "if", "(", "level", "===", "0", ")", "getReferences", "(", "itemPath", ",", "level", "+", "1", ",", "prefix", "+", "item", ",", "referenceFile", ",", "referenceDrawer", ")", ";", "}", "else", "if", "(", "stats", ".", "isFile", "(", ")", ")", "{", "var", "ext", "=", "path", ".", "extname", "(", "item", ")", ";", "if", "(", "ext", "===", "'.txt'", "&&", "path", ".", "basename", "(", "item", ")", "===", "referenceFile", ")", "{", "var", "componentPath", "=", "prefix", "+", "path", ".", "basename", "(", "item", ",", "ext", ")", ";", "referenceDrawer", ".", "add", "(", "componentPath", ",", "getReference", "(", "itemPath", ")", ")", ";", "logger", ".", "fileProcessed", "(", "'Reference'", ",", "itemPath", ")", ";", "}", "}", "}", ")", "}" ]
Reads all references in a component sub-directory. @param {string} componentDir - The path of the component sub-directory. @param {number} level - The level depth compared to the components directory. @param {string} levelPath - The base URL of the component sub-directory. @param {string} referenceFile - The name of the reference files. @param {ReferenceDrawer} referenceDrawer - The reference storage.
[ "Reads", "all", "references", "in", "a", "component", "sub", "-", "directory", "." ]
1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784
https://github.com/logikum/md-site-engine/blob/1abb0d9d6ea2c84690b9ffdde6b7ff7d49288784/source/readers/read-references.js#L32-L63
train
jsCow/jscow
src/__backups__/components/jscow-buttongroup.js
function() { this.addController(jsCow.res.controller.buttongroup); this.addModel(jsCow.res.model.buttongroup); this.addView(jsCow.res.view.buttongroup); return this; }
javascript
function() { this.addController(jsCow.res.controller.buttongroup); this.addModel(jsCow.res.model.buttongroup); this.addView(jsCow.res.view.buttongroup); return this; }
[ "function", "(", ")", "{", "this", ".", "addController", "(", "jsCow", ".", "res", ".", "controller", ".", "buttongroup", ")", ";", "this", ".", "addModel", "(", "jsCow", ".", "res", ".", "model", ".", "buttongroup", ")", ";", "this", ".", "addView", "(", "jsCow", ".", "res", ".", "view", ".", "buttongroup", ")", ";", "return", "this", ";", "}" ]
The init method will be called by initializing the component. The model, view and controller should be set within this method. this.addController(jsCow.res.controller.buttongroup); this.addModel(jsCow.res.model.buttongroup); this.addView(jsCow.res.view.buttongroup); @method init @public @return {Object} Instance of the component itself.
[ "The", "init", "method", "will", "be", "called", "by", "initializing", "the", "component", ".", "The", "model", "view", "and", "controller", "should", "be", "set", "within", "this", "method", "." ]
9fc242a470c34260b123b8c3935c929f1613182b
https://github.com/jsCow/jscow/blob/9fc242a470c34260b123b8c3935c929f1613182b/src/__backups__/components/jscow-buttongroup.js#L27-L34
train
nexdrew/all-stars
lib/fetchAuthors.js
fetchAuthors
function fetchAuthors (forPackages, opts) { opts = normalizeOpts(opts) // start with npmUser and email from registry return fetchRegistry(forPackages, {}, opts) .then(persons => { // reduce duplicates and add pre-known aliases return reduceDuplicates(persons, opts) }) .then(persons => { // add name, githubUser, and twitter from npm profile return fetchProfiles(persons, opts) }) .then(persons => { // finish with name and email from github return fetchGithub(persons, opts) }) }
javascript
function fetchAuthors (forPackages, opts) { opts = normalizeOpts(opts) // start with npmUser and email from registry return fetchRegistry(forPackages, {}, opts) .then(persons => { // reduce duplicates and add pre-known aliases return reduceDuplicates(persons, opts) }) .then(persons => { // add name, githubUser, and twitter from npm profile return fetchProfiles(persons, opts) }) .then(persons => { // finish with name and email from github return fetchGithub(persons, opts) }) }
[ "function", "fetchAuthors", "(", "forPackages", ",", "opts", ")", "{", "opts", "=", "normalizeOpts", "(", "opts", ")", "return", "fetchRegistry", "(", "forPackages", ",", "{", "}", ",", "opts", ")", ".", "then", "(", "persons", "=>", "{", "return", "reduceDuplicates", "(", "persons", ",", "opts", ")", "}", ")", ".", "then", "(", "persons", "=>", "{", "return", "fetchProfiles", "(", "persons", ",", "opts", ")", "}", ")", ".", "then", "(", "persons", "=>", "{", "return", "fetchGithub", "(", "persons", ",", "opts", ")", "}", ")", "}" ]
returns a Promise that resolves to fetched authors
[ "returns", "a", "Promise", "that", "resolves", "to", "fetched", "authors" ]
039c10840f95f6a099522aa494aa0734b3c9a5ba
https://github.com/nexdrew/all-stars/blob/039c10840f95f6a099522aa494aa0734b3c9a5ba/lib/fetchAuthors.js#L22-L38
train
tauren/tmpl-precompile
lib/colors.js
function (color, func) { exports[color] = function(str) { return func.apply(str); }; String.prototype.__defineGetter__(color, func); }
javascript
function (color, func) { exports[color] = function(str) { return func.apply(str); }; String.prototype.__defineGetter__(color, func); }
[ "function", "(", "color", ",", "func", ")", "{", "exports", "[", "color", "]", "=", "function", "(", "str", ")", "{", "return", "func", ".", "apply", "(", "str", ")", ";", "}", ";", "String", ".", "prototype", ".", "__defineGetter__", "(", "color", ",", "func", ")", ";", "}" ]
prototypes the string object to have additional method calls that add terminal colors
[ "prototypes", "the", "string", "object", "to", "have", "additional", "method", "calls", "that", "add", "terminal", "colors" ]
1df2f7b446446a1e6784b5a754f39eeb7055550e
https://github.com/tauren/tmpl-precompile/blob/1df2f7b446446a1e6784b5a754f39eeb7055550e/lib/colors.js#L30-L35
train
pex-gl/pex-color
index.js
create
function create(r, g, b, a) { return [r || 0, g || 0, b || 0, (a === undefined) ? 1 : a]; }
javascript
function create(r, g, b, a) { return [r || 0, g || 0, b || 0, (a === undefined) ? 1 : a]; }
[ "function", "create", "(", "r", ",", "g", ",", "b", ",", "a", ")", "{", "return", "[", "r", "||", "0", ",", "g", "||", "0", ",", "b", "||", "0", ",", "(", "a", "===", "undefined", ")", "?", "1", ":", "a", "]", ";", "}" ]
RGBA color constructor function @param {Number} [r=0] - red component (0..1) @param {Number} [g=0] - green component (0..1) @param {Number} [b=0] - blue component (0..1) @param {Number} [a=1] - alpha component (0..1) @return {Array} - RGBA color array [r,g,b,a] (0..1)
[ "RGBA", "color", "constructor", "function" ]
b4b64e045fa9f1c4697099ed4f658dd289862c1c
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L16-L18
train
pex-gl/pex-color
index.js
setRGB
function setRGB(color, r, g, b, a) { color[0] = r; color[1] = g; color[2] = b; color[3] = (a !== undefined) ? a : 1; return color; }
javascript
function setRGB(color, r, g, b, a) { color[0] = r; color[1] = g; color[2] = b; color[3] = (a !== undefined) ? a : 1; return color; }
[ "function", "setRGB", "(", "color", ",", "r", ",", "g", ",", "b", ",", "a", ")", "{", "color", "[", "0", "]", "=", "r", ";", "color", "[", "1", "]", "=", "g", ";", "color", "[", "2", "]", "=", "b", ";", "color", "[", "3", "]", "=", "(", "a", "!==", "undefined", ")", "?", "a", ":", "1", ";", "return", "color", ";", "}" ]
Updates a color based on r, g, b, a component values @param {Array} color - RGBA color array [r,g,b,a] to update @param {Number} r - red component (0..1) @param {Number} g - green component (0..1) @param {Number} b - blue component (0..1) @param {Number} [a=1] - alpha component (0..1) @return {Array} - updated RGBA color array [r,g,b,a] (0..1)
[ "Updates", "a", "color", "based", "on", "r", "g", "b", "a", "component", "values" ]
b4b64e045fa9f1c4697099ed4f658dd289862c1c
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L79-L86
train
pex-gl/pex-color
index.js
fromHSV
function fromHSV(h, s, v, a) { var color = create(); setHSV(color, h, s, v, a) return color; }
javascript
function fromHSV(h, s, v, a) { var color = create(); setHSV(color, h, s, v, a) return color; }
[ "function", "fromHSV", "(", "h", ",", "s", ",", "v", ",", "a", ")", "{", "var", "color", "=", "create", "(", ")", ";", "setHSV", "(", "color", ",", "h", ",", "s", ",", "v", ",", "a", ")", "return", "color", ";", "}" ]
Creates new color from hue, saturation and value @param {Number} h - hue (0..1) @param {Number} s - saturation (0..1) @param {Number} v - value (0..1) @param {Number} [a=1] - alpha (0..1) @return {Array} - RGBA color array [r,g,b,a] (0..1)
[ "Creates", "new", "color", "from", "hue", "saturation", "and", "value" ]
b4b64e045fa9f1c4697099ed4f658dd289862c1c
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L119-L123
train
pex-gl/pex-color
index.js
setHSV
function setHSV(color, h, s, v, a) { a = a || 1; var i = Math.floor(h * 6); var f = h * 6 - i; var p = v * (1 - s); var q = v * (1 - f * s); var t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: color[0] = v; color[1] = t; color[2] = p; break; case 1: color[0] = q; color[1] = v; color[2] = p; break; case 2: color[0] = p; color[1] = v; color[2] = t; break; case 3: color[0] = p; color[1] = q; color[2] = v; break; case 4: color[0] = t; color[1] = p; color[2] = v; break; case 5: color[0] = v; color[1] = p; color[2] = q; break; } color[3] = a; return color; }
javascript
function setHSV(color, h, s, v, a) { a = a || 1; var i = Math.floor(h * 6); var f = h * 6 - i; var p = v * (1 - s); var q = v * (1 - f * s); var t = v * (1 - (1 - f) * s); switch (i % 6) { case 0: color[0] = v; color[1] = t; color[2] = p; break; case 1: color[0] = q; color[1] = v; color[2] = p; break; case 2: color[0] = p; color[1] = v; color[2] = t; break; case 3: color[0] = p; color[1] = q; color[2] = v; break; case 4: color[0] = t; color[1] = p; color[2] = v; break; case 5: color[0] = v; color[1] = p; color[2] = q; break; } color[3] = a; return color; }
[ "function", "setHSV", "(", "color", ",", "h", ",", "s", ",", "v", ",", "a", ")", "{", "a", "=", "a", "||", "1", ";", "var", "i", "=", "Math", ".", "floor", "(", "h", "*", "6", ")", ";", "var", "f", "=", "h", "*", "6", "-", "i", ";", "var", "p", "=", "v", "*", "(", "1", "-", "s", ")", ";", "var", "q", "=", "v", "*", "(", "1", "-", "f", "*", "s", ")", ";", "var", "t", "=", "v", "*", "(", "1", "-", "(", "1", "-", "f", ")", "*", "s", ")", ";", "switch", "(", "i", "%", "6", ")", "{", "case", "0", ":", "color", "[", "0", "]", "=", "v", ";", "color", "[", "1", "]", "=", "t", ";", "color", "[", "2", "]", "=", "p", ";", "break", ";", "case", "1", ":", "color", "[", "0", "]", "=", "q", ";", "color", "[", "1", "]", "=", "v", ";", "color", "[", "2", "]", "=", "p", ";", "break", ";", "case", "2", ":", "color", "[", "0", "]", "=", "p", ";", "color", "[", "1", "]", "=", "v", ";", "color", "[", "2", "]", "=", "t", ";", "break", ";", "case", "3", ":", "color", "[", "0", "]", "=", "p", ";", "color", "[", "1", "]", "=", "q", ";", "color", "[", "2", "]", "=", "v", ";", "break", ";", "case", "4", ":", "color", "[", "0", "]", "=", "t", ";", "color", "[", "1", "]", "=", "p", ";", "color", "[", "2", "]", "=", "v", ";", "break", ";", "case", "5", ":", "color", "[", "0", "]", "=", "v", ";", "color", "[", "1", "]", "=", "p", ";", "color", "[", "2", "]", "=", "q", ";", "break", ";", "}", "color", "[", "3", "]", "=", "a", ";", "return", "color", ";", "}" ]
Updates a color based on hue, saturation, value and alpha @param {Array} color - RGBA color array [r,g,b,a] to update @param {Number} h - hue (0..1) @param {Number} s - saturation (0..1) @param {Number} v - value (0..1) @param {Number} [a=1] - alpha (0..1) @return {Array} - updated RGBA color array [r,g,b,a] (0..1)
[ "Updates", "a", "color", "based", "on", "hue", "saturation", "value", "and", "alpha" ]
b4b64e045fa9f1c4697099ed4f658dd289862c1c
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L134-L154
train
pex-gl/pex-color
index.js
fromHSL
function fromHSL(h, s, l, a) { var color = create(); setHSL(color, h, s, l, a); return color; }
javascript
function fromHSL(h, s, l, a) { var color = create(); setHSL(color, h, s, l, a); return color; }
[ "function", "fromHSL", "(", "h", ",", "s", ",", "l", ",", "a", ")", "{", "var", "color", "=", "create", "(", ")", ";", "setHSL", "(", "color", ",", "h", ",", "s", ",", "l", ",", "a", ")", ";", "return", "color", ";", "}" ]
Creates new color from hue, saturation, lightness and alpha @param {Number} h - hue (0..1) @param {Number} s - saturation (0..1) @param {Number} l - lightness (0..1) @param {Number} [a=1] - alpha (0..1) @return {Array} - RGBA color array [r,g,b,a] (0..1)
[ "Creates", "new", "color", "from", "hue", "saturation", "lightness", "and", "alpha" ]
b4b64e045fa9f1c4697099ed4f658dd289862c1c
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L195-L199
train
pex-gl/pex-color
index.js
setHSL
function setHSL(color, h, s, l, a) { a = a || 1; function hue2rgb(p, q, t) { if (t < 0) { t += 1; } if (t > 1) { t -= 1; } if (t < 1/6) { return p + (q - p) * 6 * t; } if (t < 1/2) { return q; } if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; } return p; } if (s === 0) { color[0] = color[1] = color[2] = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; color[0] = hue2rgb(p, q, h + 1/3); color[1] = hue2rgb(p, q, h); color[2] = hue2rgb(p, q, h - 1/3); } color[3] = a; return color; }
javascript
function setHSL(color, h, s, l, a) { a = a || 1; function hue2rgb(p, q, t) { if (t < 0) { t += 1; } if (t > 1) { t -= 1; } if (t < 1/6) { return p + (q - p) * 6 * t; } if (t < 1/2) { return q; } if (t < 2/3) { return p + (q - p) * (2/3 - t) * 6; } return p; } if (s === 0) { color[0] = color[1] = color[2] = l; // achromatic } else { var q = l < 0.5 ? l * (1 + s) : l + s - l * s; var p = 2 * l - q; color[0] = hue2rgb(p, q, h + 1/3); color[1] = hue2rgb(p, q, h); color[2] = hue2rgb(p, q, h - 1/3); } color[3] = a; return color; }
[ "function", "setHSL", "(", "color", ",", "h", ",", "s", ",", "l", ",", "a", ")", "{", "a", "=", "a", "||", "1", ";", "function", "hue2rgb", "(", "p", ",", "q", ",", "t", ")", "{", "if", "(", "t", "<", "0", ")", "{", "t", "+=", "1", ";", "}", "if", "(", "t", ">", "1", ")", "{", "t", "-=", "1", ";", "}", "if", "(", "t", "<", "1", "/", "6", ")", "{", "return", "p", "+", "(", "q", "-", "p", ")", "*", "6", "*", "t", ";", "}", "if", "(", "t", "<", "1", "/", "2", ")", "{", "return", "q", ";", "}", "if", "(", "t", "<", "2", "/", "3", ")", "{", "return", "p", "+", "(", "q", "-", "p", ")", "*", "(", "2", "/", "3", "-", "t", ")", "*", "6", ";", "}", "return", "p", ";", "}", "if", "(", "s", "===", "0", ")", "{", "color", "[", "0", "]", "=", "color", "[", "1", "]", "=", "color", "[", "2", "]", "=", "l", ";", "}", "else", "{", "var", "q", "=", "l", "<", "0.5", "?", "l", "*", "(", "1", "+", "s", ")", ":", "l", "+", "s", "-", "l", "*", "s", ";", "var", "p", "=", "2", "*", "l", "-", "q", ";", "color", "[", "0", "]", "=", "hue2rgb", "(", "p", ",", "q", ",", "h", "+", "1", "/", "3", ")", ";", "color", "[", "1", "]", "=", "hue2rgb", "(", "p", ",", "q", ",", "h", ")", ";", "color", "[", "2", "]", "=", "hue2rgb", "(", "p", ",", "q", ",", "h", "-", "1", "/", "3", ")", ";", "}", "color", "[", "3", "]", "=", "a", ";", "return", "color", ";", "}" ]
Updates a color based on hue, saturation, lightness and alpha @param {Array} color - RGBA color array [r,g,b,a] to update @param {Number} h - hue (0..1) @param {Number} s - saturation (0..1) @param {Number} l - lightness (0..1) @param {Number} [a=1] - alpha (0..1) @return {Array} - updated RGBA color array [r,g,b,a] (0..1)
[ "Updates", "a", "color", "based", "on", "hue", "saturation", "lightness", "and", "alpha" ]
b4b64e045fa9f1c4697099ed4f658dd289862c1c
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L210-L235
train
pex-gl/pex-color
index.js
getHex
function getHex(color) { var c = [ color[0], color[1], color[2] ].map(function(val) { return Math.floor(val * 255); }); return "#" + ((c[2] | c[1] << 8 | c[0] << 16) | 1 << 24) .toString(16) .slice(1) .toUpperCase(); }
javascript
function getHex(color) { var c = [ color[0], color[1], color[2] ].map(function(val) { return Math.floor(val * 255); }); return "#" + ((c[2] | c[1] << 8 | c[0] << 16) | 1 << 24) .toString(16) .slice(1) .toUpperCase(); }
[ "function", "getHex", "(", "color", ")", "{", "var", "c", "=", "[", "color", "[", "0", "]", ",", "color", "[", "1", "]", ",", "color", "[", "2", "]", "]", ".", "map", "(", "function", "(", "val", ")", "{", "return", "Math", ".", "floor", "(", "val", "*", "255", ")", ";", "}", ")", ";", "return", "\"#\"", "+", "(", "(", "c", "[", "2", "]", "|", "c", "[", "1", "]", "<<", "8", "|", "c", "[", "0", "]", "<<", "16", ")", "|", "1", "<<", "24", ")", ".", "toString", "(", "16", ")", ".", "slice", "(", "1", ")", ".", "toUpperCase", "(", ")", ";", "}" ]
Returns html hex representation of given color @param {Array} color - RGBA color array [r,g,b,a] @return {String} - html hex color including leading hash e.g. #FF0000
[ "Returns", "html", "hex", "representation", "of", "given", "color" ]
b4b64e045fa9f1c4697099ed4f658dd289862c1c
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L305-L314
train
pex-gl/pex-color
index.js
fromXYZ
function fromXYZ(x, y, z) { var color = create(); setXYZ(color, x, y, z); return color; }
javascript
function fromXYZ(x, y, z) { var color = create(); setXYZ(color, x, y, z); return color; }
[ "function", "fromXYZ", "(", "x", ",", "y", ",", "z", ")", "{", "var", "color", "=", "create", "(", ")", ";", "setXYZ", "(", "color", ",", "x", ",", "y", ",", "z", ")", ";", "return", "color", ";", "}" ]
Creates new color from XYZ values @param {Number} x - x component (0..95) @param {Number} y - y component (0..100) @param {Number} z - z component (0..108) @return {Array} - RGBA color array [r,g,b,a] (0..1)
[ "Creates", "new", "color", "from", "XYZ", "values" ]
b4b64e045fa9f1c4697099ed4f658dd289862c1c
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L323-L327
train
pex-gl/pex-color
index.js
setXYZ
function setXYZ(color, x, y, z) { var r = x * 3.2406 + y * -1.5372 + z * -0.4986; var g = x * -0.9689 + y * 1.8758 + z * 0.0415; var b = x * 0.0557 + y * -0.2040 + z * 1.0570; color[0] = fromXYZValue(r); color[1] = fromXYZValue(g); color[2] = fromXYZValue(b); color[3] = 1.0; return color; }
javascript
function setXYZ(color, x, y, z) { var r = x * 3.2406 + y * -1.5372 + z * -0.4986; var g = x * -0.9689 + y * 1.8758 + z * 0.0415; var b = x * 0.0557 + y * -0.2040 + z * 1.0570; color[0] = fromXYZValue(r); color[1] = fromXYZValue(g); color[2] = fromXYZValue(b); color[3] = 1.0; return color; }
[ "function", "setXYZ", "(", "color", ",", "x", ",", "y", ",", "z", ")", "{", "var", "r", "=", "x", "*", "3.2406", "+", "y", "*", "-", "1.5372", "+", "z", "*", "-", "0.4986", ";", "var", "g", "=", "x", "*", "-", "0.9689", "+", "y", "*", "1.8758", "+", "z", "*", "0.0415", ";", "var", "b", "=", "x", "*", "0.0557", "+", "y", "*", "-", "0.2040", "+", "z", "*", "1.0570", ";", "color", "[", "0", "]", "=", "fromXYZValue", "(", "r", ")", ";", "color", "[", "1", "]", "=", "fromXYZValue", "(", "g", ")", ";", "color", "[", "2", "]", "=", "fromXYZValue", "(", "b", ")", ";", "color", "[", "3", "]", "=", "1.0", ";", "return", "color", ";", "}" ]
Updates a color based on x, y, z component values @param {Array} color - RGBA color array [r,g,b,a] to update @param {Number} x - x component (0..95) @param {Number} y - y component (0..100) @param {Number} z - z component (0..108) @return {Array} - updated RGBA color array [r,g,b,a] (0..1)
[ "Updates", "a", "color", "based", "on", "x", "y", "z", "component", "values" ]
b4b64e045fa9f1c4697099ed4f658dd289862c1c
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L367-L378
train
pex-gl/pex-color
index.js
getXYZ
function getXYZ(color) { var r = toXYZValue(color[0]); var g = toXYZValue(color[1]); var b = toXYZValue(color[2]); return [ r * 0.4124 + g * 0.3576 + b * 0.1805, r * 0.2126 + g * 0.7152 + b * 0.0722, r * 0.0193 + g * 0.1192 + b * 0.9505 ] }
javascript
function getXYZ(color) { var r = toXYZValue(color[0]); var g = toXYZValue(color[1]); var b = toXYZValue(color[2]); return [ r * 0.4124 + g * 0.3576 + b * 0.1805, r * 0.2126 + g * 0.7152 + b * 0.0722, r * 0.0193 + g * 0.1192 + b * 0.9505 ] }
[ "function", "getXYZ", "(", "color", ")", "{", "var", "r", "=", "toXYZValue", "(", "color", "[", "0", "]", ")", ";", "var", "g", "=", "toXYZValue", "(", "color", "[", "1", "]", ")", ";", "var", "b", "=", "toXYZValue", "(", "color", "[", "2", "]", ")", ";", "return", "[", "r", "*", "0.4124", "+", "g", "*", "0.3576", "+", "b", "*", "0.1805", ",", "r", "*", "0.2126", "+", "g", "*", "0.7152", "+", "b", "*", "0.0722", ",", "r", "*", "0.0193", "+", "g", "*", "0.1192", "+", "b", "*", "0.9505", "]", "}" ]
Returns XYZ representation of given color @param {Array} color - RGBA color array [r,g,b,a] @return {Array} - [x,y,z] (x:0..95, y:0..100, z:0..108)
[ "Returns", "XYZ", "representation", "of", "given", "color" ]
b4b64e045fa9f1c4697099ed4f658dd289862c1c
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L385-L395
train
pex-gl/pex-color
index.js
fromLab
function fromLab(l, a, b) { var color = create(); setLab(color, l, a, b); return color; }
javascript
function fromLab(l, a, b) { var color = create(); setLab(color, l, a, b); return color; }
[ "function", "fromLab", "(", "l", ",", "a", ",", "b", ")", "{", "var", "color", "=", "create", "(", ")", ";", "setLab", "(", "color", ",", "l", ",", "a", ",", "b", ")", ";", "return", "color", ";", "}" ]
Creates new color from l,a,b component values @param {Number} l - l component (0..100) @param {Number} a - a component (-128..127) @param {Number} b - b component (-128..127) @return {Array} - RGBA color array [r,g,b,a] (0..1)
[ "Creates", "new", "color", "from", "l", "a", "b", "component", "values" ]
b4b64e045fa9f1c4697099ed4f658dd289862c1c
https://github.com/pex-gl/pex-color/blob/b4b64e045fa9f1c4697099ed4f658dd289862c1c/index.js#L404-L408
train