id
int32
0
58k
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
26,800
rappid/rAppid.js
js/data/Model.js
function (options, callback) { if (arguments.length === 1 && options instanceof Function) { callback = options; options = null; } options = options || {}; var self = this; if (this._fetch.state === FETCHSTATE.LOADING) { // currently fetching -> register callback this._fetch.callbacks.push(function (err, model) { modelFetchedComplete(err, model, options, callback); }); } else if (this._fetch.state == FETCHSTATE.LOADED && !options.noCache) { // completed loaded -> execute modelFetchedComplete(null, this, options, callback); } else { // set state and start loading self._fetch.state = FETCHSTATE.LOADING; this.$context.$dataSource.loadModel(this, options, function (err, model) { self._fetch.state = err ? FETCHSTATE.ERROR : FETCHSTATE.LOADED; // execute callbacks modelFetchedComplete.call(self, err, model, options, callback); _.each(self._fetch.callbacks, function (cb) { cb.call(self, err, model); }); }); } }
javascript
function (options, callback) { if (arguments.length === 1 && options instanceof Function) { callback = options; options = null; } options = options || {}; var self = this; if (this._fetch.state === FETCHSTATE.LOADING) { // currently fetching -> register callback this._fetch.callbacks.push(function (err, model) { modelFetchedComplete(err, model, options, callback); }); } else if (this._fetch.state == FETCHSTATE.LOADED && !options.noCache) { // completed loaded -> execute modelFetchedComplete(null, this, options, callback); } else { // set state and start loading self._fetch.state = FETCHSTATE.LOADING; this.$context.$dataSource.loadModel(this, options, function (err, model) { self._fetch.state = err ? FETCHSTATE.ERROR : FETCHSTATE.LOADED; // execute callbacks modelFetchedComplete.call(self, err, model, options, callback); _.each(self._fetch.callbacks, function (cb) { cb.call(self, err, model); }); }); } }
[ "function", "(", "options", ",", "callback", ")", "{", "if", "(", "arguments", ".", "length", "===", "1", "&&", "options", "instanceof", "Function", ")", "{", "callback", "=", "options", ";", "options", "=", "null", ";", "}", "options", "=", "options", "||", "{", "}", ";", "var", "self", "=", "this", ";", "if", "(", "this", ".", "_fetch", ".", "state", "===", "FETCHSTATE", ".", "LOADING", ")", "{", "// currently fetching -> register callback", "this", ".", "_fetch", ".", "callbacks", ".", "push", "(", "function", "(", "err", ",", "model", ")", "{", "modelFetchedComplete", "(", "err", ",", "model", ",", "options", ",", "callback", ")", ";", "}", ")", ";", "}", "else", "if", "(", "this", ".", "_fetch", ".", "state", "==", "FETCHSTATE", ".", "LOADED", "&&", "!", "options", ".", "noCache", ")", "{", "// completed loaded -> execute", "modelFetchedComplete", "(", "null", ",", "this", ",", "options", ",", "callback", ")", ";", "}", "else", "{", "// set state and start loading", "self", ".", "_fetch", ".", "state", "=", "FETCHSTATE", ".", "LOADING", ";", "this", ".", "$context", ".", "$dataSource", ".", "loadModel", "(", "this", ",", "options", ",", "function", "(", "err", ",", "model", ")", "{", "self", ".", "_fetch", ".", "state", "=", "err", "?", "FETCHSTATE", ".", "ERROR", ":", "FETCHSTATE", ".", "LOADED", ";", "// execute callbacks", "modelFetchedComplete", ".", "call", "(", "self", ",", "err", ",", "model", ",", "options", ",", "callback", ")", ";", "_", ".", "each", "(", "self", ".", "_fetch", ".", "callbacks", ",", "function", "(", "cb", ")", "{", "cb", ".", "call", "(", "self", ",", "err", ",", "model", ")", ";", "}", ")", ";", "}", ")", ";", "}", "}" ]
Fetches the model over the given DataSource. The id of the model must be set. @param {Object} options @param {Array} options.fetchSubModels - array of submodels to fetch @param {Function} callback - function(err, model, options)
[ "Fetches", "the", "model", "over", "the", "given", "DataSource", ".", "The", "id", "of", "the", "model", "must", "be", "set", "." ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/data/Model.js#L221-L256
26,801
rappid/rAppid.js
js/data/Model.js
function (identifier) { var idField = this.idField; if (this.schema.hasOwnProperty(idField)) { var schemaObject = this.schema[idField]; if (schemaObject.type && schemaObject.type === Number) { return parseInt(identifier); } } return identifier; }
javascript
function (identifier) { var idField = this.idField; if (this.schema.hasOwnProperty(idField)) { var schemaObject = this.schema[idField]; if (schemaObject.type && schemaObject.type === Number) { return parseInt(identifier); } } return identifier; }
[ "function", "(", "identifier", ")", "{", "var", "idField", "=", "this", ".", "idField", ";", "if", "(", "this", ".", "schema", ".", "hasOwnProperty", "(", "idField", ")", ")", "{", "var", "schemaObject", "=", "this", ".", "schema", "[", "idField", "]", ";", "if", "(", "schemaObject", ".", "type", "&&", "schemaObject", ".", "type", "===", "Number", ")", "{", "return", "parseInt", "(", "identifier", ")", ";", "}", "}", "return", "identifier", ";", "}" ]
Converts the identifier to the given type in the schema @param {String} identifier @return {Number|String}
[ "Converts", "the", "identifier", "to", "the", "given", "type", "in", "the", "schema" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/data/Model.js#L339-L348
26,802
rappid/rAppid.js
js/core/Repeat.js
function (items) { var c, j; if (this.$renderedItems) { for (j = this.$renderedItems.length - 1; j >= 0; j--) { c = this.$renderedItems[j]; this.$parent.removeChild(c.component); c.component.destroy(); } } if (this.$renderedItemsMap) { var itemList; for (var key in this.$renderedItemsMap) { if (this.$renderedItemsMap.hasOwnProperty(key)) { itemList = this.$renderedItemsMap[key]; for (j = itemList.length - 1; j >= 0; j--) { c = itemList[j]; this.$parent.removeChild(c.component); c.component.destroy(); } } } } this.$renderedItems = []; this.$renderedItemsMap = {}; this.$indexOffset = 0; if (items) { for (var i = 0; i < items.length; i++) { this._innerRenderItem(items[i], i); } } this.trigger("on:itemsRendered", {}, this); }
javascript
function (items) { var c, j; if (this.$renderedItems) { for (j = this.$renderedItems.length - 1; j >= 0; j--) { c = this.$renderedItems[j]; this.$parent.removeChild(c.component); c.component.destroy(); } } if (this.$renderedItemsMap) { var itemList; for (var key in this.$renderedItemsMap) { if (this.$renderedItemsMap.hasOwnProperty(key)) { itemList = this.$renderedItemsMap[key]; for (j = itemList.length - 1; j >= 0; j--) { c = itemList[j]; this.$parent.removeChild(c.component); c.component.destroy(); } } } } this.$renderedItems = []; this.$renderedItemsMap = {}; this.$indexOffset = 0; if (items) { for (var i = 0; i < items.length; i++) { this._innerRenderItem(items[i], i); } } this.trigger("on:itemsRendered", {}, this); }
[ "function", "(", "items", ")", "{", "var", "c", ",", "j", ";", "if", "(", "this", ".", "$renderedItems", ")", "{", "for", "(", "j", "=", "this", ".", "$renderedItems", ".", "length", "-", "1", ";", "j", ">=", "0", ";", "j", "--", ")", "{", "c", "=", "this", ".", "$renderedItems", "[", "j", "]", ";", "this", ".", "$parent", ".", "removeChild", "(", "c", ".", "component", ")", ";", "c", ".", "component", ".", "destroy", "(", ")", ";", "}", "}", "if", "(", "this", ".", "$renderedItemsMap", ")", "{", "var", "itemList", ";", "for", "(", "var", "key", "in", "this", ".", "$renderedItemsMap", ")", "{", "if", "(", "this", ".", "$renderedItemsMap", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "itemList", "=", "this", ".", "$renderedItemsMap", "[", "key", "]", ";", "for", "(", "j", "=", "itemList", ".", "length", "-", "1", ";", "j", ">=", "0", ";", "j", "--", ")", "{", "c", "=", "itemList", "[", "j", "]", ";", "this", ".", "$parent", ".", "removeChild", "(", "c", ".", "component", ")", ";", "c", ".", "component", ".", "destroy", "(", ")", ";", "}", "}", "}", "}", "this", ".", "$renderedItems", "=", "[", "]", ";", "this", ".", "$renderedItemsMap", "=", "{", "}", ";", "this", ".", "$indexOffset", "=", "0", ";", "if", "(", "items", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "++", ")", "{", "this", ".", "_innerRenderItem", "(", "items", "[", "i", "]", ",", "i", ")", ";", "}", "}", "this", ".", "trigger", "(", "\"on:itemsRendered\"", ",", "{", "}", ",", "this", ")", ";", "}" ]
Inner render method for a list of items All rendered items will be removed and destroyed before rendering @param {Array} items[] @private
[ "Inner", "render", "method", "for", "a", "list", "of", "items", "All", "rendered", "items", "will", "be", "removed", "and", "destroyed", "before", "rendering" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Repeat.js#L103-L136
26,803
rappid/rAppid.js
js/core/Repeat.js
function (child, index) { var indexOffset = this._calculateIndexOffsetForChild(child); this.$parent.addChild(child, {childIndex: index + indexOffset}); }
javascript
function (child, index) { var indexOffset = this._calculateIndexOffsetForChild(child); this.$parent.addChild(child, {childIndex: index + indexOffset}); }
[ "function", "(", "child", ",", "index", ")", "{", "var", "indexOffset", "=", "this", ".", "_calculateIndexOffsetForChild", "(", "child", ")", ";", "this", ".", "$parent", ".", "addChild", "(", "child", ",", "{", "childIndex", ":", "index", "+", "indexOffset", "}", ")", ";", "}" ]
Adds a child element to the right index in the parent element @param {js.core.Element} child - the child to add @param {Number} index - index of item @private
[ "Adds", "a", "child", "element", "to", "the", "right", "index", "in", "the", "parent", "element" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Repeat.js#L230-L233
26,804
rappid/rAppid.js
js/core/Repeat.js
function (item) { var key = this._getKeyForItem(item), list = this.$renderedItems; if (key) { list = this.$renderedItemsMap[key]; } if (list) { var ri; for (var i = 0; i < list.length; i++) { ri = list[i]; if (key || ri.item === item) { return ri.component; } } } return null; }
javascript
function (item) { var key = this._getKeyForItem(item), list = this.$renderedItems; if (key) { list = this.$renderedItemsMap[key]; } if (list) { var ri; for (var i = 0; i < list.length; i++) { ri = list[i]; if (key || ri.item === item) { return ri.component; } } } return null; }
[ "function", "(", "item", ")", "{", "var", "key", "=", "this", ".", "_getKeyForItem", "(", "item", ")", ",", "list", "=", "this", ".", "$renderedItems", ";", "if", "(", "key", ")", "{", "list", "=", "this", ".", "$renderedItemsMap", "[", "key", "]", ";", "}", "if", "(", "list", ")", "{", "var", "ri", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "list", ".", "length", ";", "i", "++", ")", "{", "ri", "=", "list", "[", "i", "]", ";", "if", "(", "key", "||", "ri", ".", "item", "===", "item", ")", "{", "return", "ri", ".", "component", ";", "}", "}", "}", "return", "null", ";", "}" ]
Returns the rendered component to a given item @param item @return {js.core.Component} component
[ "Returns", "the", "rendered", "component", "to", "a", "given", "item" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Repeat.js#L297-L313
26,805
rappid/rAppid.js
js/lib/query/query.js
function (operator, field) { if (!this.query.where) { return null; } function findExpression(expressions) { var expression, ret = null; for (var i = 0; i < expressions.length; i++) { expression = expressions[i]; if (expression instanceof Where) { ret = findExpression(expression.expressions); } else if (expression instanceof Comparator) { if (expression.operator == operator && expression.field == field) { ret = expression; } } if (ret) { return ret; } } return ret; } return findExpression(this.query.where.expressions); }
javascript
function (operator, field) { if (!this.query.where) { return null; } function findExpression(expressions) { var expression, ret = null; for (var i = 0; i < expressions.length; i++) { expression = expressions[i]; if (expression instanceof Where) { ret = findExpression(expression.expressions); } else if (expression instanceof Comparator) { if (expression.operator == operator && expression.field == field) { ret = expression; } } if (ret) { return ret; } } return ret; } return findExpression(this.query.where.expressions); }
[ "function", "(", "operator", ",", "field", ")", "{", "if", "(", "!", "this", ".", "query", ".", "where", ")", "{", "return", "null", ";", "}", "function", "findExpression", "(", "expressions", ")", "{", "var", "expression", ",", "ret", "=", "null", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "expressions", ".", "length", ";", "i", "++", ")", "{", "expression", "=", "expressions", "[", "i", "]", ";", "if", "(", "expression", "instanceof", "Where", ")", "{", "ret", "=", "findExpression", "(", "expression", ".", "expressions", ")", ";", "}", "else", "if", "(", "expression", "instanceof", "Comparator", ")", "{", "if", "(", "expression", ".", "operator", "==", "operator", "&&", "expression", ".", "field", "==", "field", ")", "{", "ret", "=", "expression", ";", "}", "}", "if", "(", "ret", ")", "{", "return", "ret", ";", "}", "}", "return", "ret", ";", "}", "return", "findExpression", "(", "this", ".", "query", ".", "where", ".", "expressions", ")", ";", "}" ]
Tries to find a expression for an operator and a field @param {String} operator @param {String} field @returns {*}
[ "Tries", "to", "find", "a", "expression", "for", "an", "operator", "and", "a", "field" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/lib/query/query.js#L128-L154
26,806
rappid/rAppid.js
js/core/Component.js
function (event) { for (var i = 0; i < this.events.length; i++) { if (event === this.events[i]) { return true; } } return false; }
javascript
function (event) { for (var i = 0; i < this.events.length; i++) { if (event === this.events[i]) { return true; } } return false; }
[ "function", "(", "event", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "events", ".", "length", ";", "i", "++", ")", "{", "if", "(", "event", "===", "this", ".", "events", "[", "i", "]", ")", "{", "return", "true", ";", "}", "}", "return", "false", ";", "}" ]
Returns true if event is defined in Component event list @param event
[ "Returns", "true", "if", "event", "is", "defined", "in", "Component", "event", "list" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Component.js#L410-L417
26,807
rappid/rAppid.js
js/core/Component.js
function (domNode) { if (domNode.localName) { return domNode.localName; } var localName = LocalNameCache[domNode.tagName]; if (localName) { return localName; } var st = domNode.tagName.split(":"); LocalNameCache[domNode.tagName] = st[st.length - 1]; return LocalNameCache[domNode.tagName]; }
javascript
function (domNode) { if (domNode.localName) { return domNode.localName; } var localName = LocalNameCache[domNode.tagName]; if (localName) { return localName; } var st = domNode.tagName.split(":"); LocalNameCache[domNode.tagName] = st[st.length - 1]; return LocalNameCache[domNode.tagName]; }
[ "function", "(", "domNode", ")", "{", "if", "(", "domNode", ".", "localName", ")", "{", "return", "domNode", ".", "localName", ";", "}", "var", "localName", "=", "LocalNameCache", "[", "domNode", ".", "tagName", "]", ";", "if", "(", "localName", ")", "{", "return", "localName", ";", "}", "var", "st", "=", "domNode", ".", "tagName", ".", "split", "(", "\":\"", ")", ";", "LocalNameCache", "[", "domNode", ".", "tagName", "]", "=", "st", "[", "st", ".", "length", "-", "1", "]", ";", "return", "LocalNameCache", "[", "domNode", ".", "tagName", "]", ";", "}" ]
determinate the local-name of a DomNode @param domNode
[ "determinate", "the", "local", "-", "name", "of", "a", "DomNode" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Component.js#L573-L588
26,808
rappid/rAppid.js
js/data/DataSource.js
function (entity, action, options) { var ret = {}, data = entity.compose(action, options), schemaDefinition, schemaType, isModel = entity instanceof Model, factory = entity.factory; for (var key in entity.schema) { if (entity.schema.hasOwnProperty(key) && (!isModel || (!options || !options.includeInIndex || _.contains(options.includeInIndex, key)))) { schemaDefinition = entity.schema[key]; schemaType = schemaDefinition.type; var value; if (data[key] && schemaDefinition.isReference && schemaType.classof && schemaType.classof(Entity) && !schemaType.classof(Model)) { value = {}; value[schemaType.prototype.idField] = data[key].identifier(); } else { value = this._getCompositionValue(data[key], key, action, options, entity); } if (value !== undefined) { ret[this._getReferenceKey(key, schemaType)] = value; } } } return ret; }
javascript
function (entity, action, options) { var ret = {}, data = entity.compose(action, options), schemaDefinition, schemaType, isModel = entity instanceof Model, factory = entity.factory; for (var key in entity.schema) { if (entity.schema.hasOwnProperty(key) && (!isModel || (!options || !options.includeInIndex || _.contains(options.includeInIndex, key)))) { schemaDefinition = entity.schema[key]; schemaType = schemaDefinition.type; var value; if (data[key] && schemaDefinition.isReference && schemaType.classof && schemaType.classof(Entity) && !schemaType.classof(Model)) { value = {}; value[schemaType.prototype.idField] = data[key].identifier(); } else { value = this._getCompositionValue(data[key], key, action, options, entity); } if (value !== undefined) { ret[this._getReferenceKey(key, schemaType)] = value; } } } return ret; }
[ "function", "(", "entity", ",", "action", ",", "options", ")", "{", "var", "ret", "=", "{", "}", ",", "data", "=", "entity", ".", "compose", "(", "action", ",", "options", ")", ",", "schemaDefinition", ",", "schemaType", ",", "isModel", "=", "entity", "instanceof", "Model", ",", "factory", "=", "entity", ".", "factory", ";", "for", "(", "var", "key", "in", "entity", ".", "schema", ")", "{", "if", "(", "entity", ".", "schema", ".", "hasOwnProperty", "(", "key", ")", "&&", "(", "!", "isModel", "||", "(", "!", "options", "||", "!", "options", ".", "includeInIndex", "||", "_", ".", "contains", "(", "options", ".", "includeInIndex", ",", "key", ")", ")", ")", ")", "{", "schemaDefinition", "=", "entity", ".", "schema", "[", "key", "]", ";", "schemaType", "=", "schemaDefinition", ".", "type", ";", "var", "value", ";", "if", "(", "data", "[", "key", "]", "&&", "schemaDefinition", ".", "isReference", "&&", "schemaType", ".", "classof", "&&", "schemaType", ".", "classof", "(", "Entity", ")", "&&", "!", "schemaType", ".", "classof", "(", "Model", ")", ")", "{", "value", "=", "{", "}", ";", "value", "[", "schemaType", ".", "prototype", ".", "idField", "]", "=", "data", "[", "key", "]", ".", "identifier", "(", ")", ";", "}", "else", "{", "value", "=", "this", ".", "_getCompositionValue", "(", "data", "[", "key", "]", ",", "key", ",", "action", ",", "options", ",", "entity", ")", ";", "}", "if", "(", "value", "!==", "undefined", ")", "{", "ret", "[", "this", ".", "_getReferenceKey", "(", "key", ",", "schemaType", ")", "]", "=", "value", ";", "}", "}", "}", "return", "ret", ";", "}" ]
Composes an entity, calls default compose method @param entity @param action @param options @return {JSON} @private
[ "Composes", "an", "entity", "calls", "default", "compose", "method" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/data/DataSource.js#L373-L400
26,809
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.ejs.js
function(object, extra_helpers) { object = object || {}; this._extra_helpers = extra_helpers; var v = new EJS.Helpers(object, extra_helpers || {}); return this.template.process.call(object, object,v); }
javascript
function(object, extra_helpers) { object = object || {}; this._extra_helpers = extra_helpers; var v = new EJS.Helpers(object, extra_helpers || {}); return this.template.process.call(object, object,v); }
[ "function", "(", "object", ",", "extra_helpers", ")", "{", "object", "=", "object", "||", "{", "}", ";", "this", ".", "_extra_helpers", "=", "extra_helpers", ";", "var", "v", "=", "new", "EJS", ".", "Helpers", "(", "object", ",", "extra_helpers", "||", "{", "}", ")", ";", "return", "this", ".", "template", ".", "process", ".", "call", "(", "object", ",", "object", ",", "v", ")", ";", "}" ]
Renders an object with extra view helpers attached to the view. @param {Object} object data to be rendered @param {Object} extra_helpers an object with additonal view helpers @return {String} returns the result of the string
[ "Renders", "an", "object", "with", "extra", "view", "helpers", "attached", "to", "the", "view", "." ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.ejs.js#L91-L96
26,810
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.ejs.js
function(options, data, helpers) { if (!helpers) helpers = this._extras; if (!data) data = this._data; return new EJS(options).render(data, helpers); }
javascript
function(options, data, helpers) { if (!helpers) helpers = this._extras; if (!data) data = this._data; return new EJS(options).render(data, helpers); }
[ "function", "(", "options", ",", "data", ",", "helpers", ")", "{", "if", "(", "!", "helpers", ")", "helpers", "=", "this", ".", "_extras", ";", "if", "(", "!", "data", ")", "data", "=", "this", ".", "_data", ";", "return", "new", "EJS", "(", "options", ")", ".", "render", "(", "data", ",", "helpers", ")", ";", "}" ]
Renders a new view. If data is passed in, uses that to render the view. @param {Object} options standard options passed to a new view. @param {optional:Object} data @return {String}
[ "Renders", "a", "new", "view", ".", "If", "data", "is", "passed", "in", "uses", "that", "to", "render", "the", "view", "." ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.ejs.js#L421-L425
26,811
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.ejs.js
function(input, null_text) { if (input == null || input === undefined) return null_text || ''; if (input instanceof(Date)) return input.toDateString(); if (input.toString) return input.toString().replace(/\n/g, '<br />').replace(/''/g, "'"); return ''; }
javascript
function(input, null_text) { if (input == null || input === undefined) return null_text || ''; if (input instanceof(Date)) return input.toDateString(); if (input.toString) return input.toString().replace(/\n/g, '<br />').replace(/''/g, "'"); return ''; }
[ "function", "(", "input", ",", "null_text", ")", "{", "if", "(", "input", "==", "null", "||", "input", "===", "undefined", ")", "return", "null_text", "||", "''", ";", "if", "(", "input", "instanceof", "(", "Date", ")", ")", "return", "input", ".", "toDateString", "(", ")", ";", "if", "(", "input", ".", "toString", ")", "return", "input", ".", "toString", "(", ")", ".", "replace", "(", "/", "\\n", "/", "g", ",", "'<br />'", ")", ".", "replace", "(", "/", "''", "/", "g", ",", "\"'\"", ")", ";", "return", "''", ";", "}" ]
For a given value, tries to create a human representation. @param {Object} input the value being converted. @param {Object} null_text what text should be present if input == null or undefined, defaults to '' @return {String}
[ "For", "a", "given", "value", "tries", "to", "create", "a", "human", "representation", "." ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.ejs.js#L432-L437
26,812
rappid/rAppid.js
js/core/Binding.js
function (path) { var str = []; for (var i = 0; i < path.length; i++) { var el = path[i]; if (el.type === TYPE_VAR) { str.push(el.name); } else { return false; } } return str.join("."); }
javascript
function (path) { var str = []; for (var i = 0; i < path.length; i++) { var el = path[i]; if (el.type === TYPE_VAR) { str.push(el.name); } else { return false; } } return str.join("."); }
[ "function", "(", "path", ")", "{", "var", "str", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "path", ".", "length", ";", "i", "++", ")", "{", "var", "el", "=", "path", "[", "i", "]", ";", "if", "(", "el", ".", "type", "===", "TYPE_VAR", ")", "{", "str", ".", "push", "(", "el", ".", "name", ")", ";", "}", "else", "{", "return", "false", ";", "}", "}", "return", "str", ".", "join", "(", "\".\"", ")", ";", "}" ]
Returns false if path includes function @param path
[ "Returns", "false", "if", "path", "includes", "function" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Binding.js#L14-L25
26,813
rappid/rAppid.js
js/core/Binding.js
function (event) { if (!this.$) { return; } for (var i = 0; i < this.$.fnc._attributes.length; i++) { if (event.$.hasOwnProperty(this.$.fnc._attributes[i])) { this._callback(); return; } } }
javascript
function (event) { if (!this.$) { return; } for (var i = 0; i < this.$.fnc._attributes.length; i++) { if (event.$.hasOwnProperty(this.$.fnc._attributes[i])) { this._callback(); return; } } }
[ "function", "(", "event", ")", "{", "if", "(", "!", "this", ".", "$", ")", "{", "return", ";", "}", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "$", ".", "fnc", ".", "_attributes", ".", "length", ";", "i", "++", ")", "{", "if", "(", "event", ".", "$", ".", "hasOwnProperty", "(", "this", ".", "$", ".", "fnc", ".", "_attributes", "[", "i", "]", ")", ")", "{", "this", ".", "_callback", "(", ")", ";", "return", ";", "}", "}", "}" ]
This method is called, when the a change event of an function binding is triggered @param event @private
[ "This", "method", "is", "called", "when", "the", "a", "change", "event", "of", "an", "function", "binding", "is", "triggered" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Binding.js#L334-L346
26,814
rappid/rAppid.js
js/core/Binding.js
function () { // binding already destroyed? if (!this.$) { return; } var e; for (var j = 0; j < this.$events.length; j++) { e = this.$events[j]; this.$.scope.unbind(e.eventType, e.callback, this); } this.$.scope.unbind('destroy', this.destroy, this); if (this.$.twoWay === true) { this.$.target.unbind(this.$.targetEvent, this._revCallback, this); } if (this.$subBinding) { this.$subBinding.destroy(); this.$subBinding = null; } // destroy parameter bindings for (var i = 0; i < this.$parameters.length; i++) { var par = this.$parameters[i]; if (par instanceof Binding) { par.destroy(); } } this.$parameters = null; this.$.scope = this.$.target = this.$.callback = null; this.$ = null; this.$targets = null; this.callBase(); bindingsDestroyed++; if (bindingsDestroyed === 500) { if (typeof(CollectGarbage) === "function") { CollectGarbage(); } bindingsDestroyed = 0; } }
javascript
function () { // binding already destroyed? if (!this.$) { return; } var e; for (var j = 0; j < this.$events.length; j++) { e = this.$events[j]; this.$.scope.unbind(e.eventType, e.callback, this); } this.$.scope.unbind('destroy', this.destroy, this); if (this.$.twoWay === true) { this.$.target.unbind(this.$.targetEvent, this._revCallback, this); } if (this.$subBinding) { this.$subBinding.destroy(); this.$subBinding = null; } // destroy parameter bindings for (var i = 0; i < this.$parameters.length; i++) { var par = this.$parameters[i]; if (par instanceof Binding) { par.destroy(); } } this.$parameters = null; this.$.scope = this.$.target = this.$.callback = null; this.$ = null; this.$targets = null; this.callBase(); bindingsDestroyed++; if (bindingsDestroyed === 500) { if (typeof(CollectGarbage) === "function") { CollectGarbage(); } bindingsDestroyed = 0; } }
[ "function", "(", ")", "{", "// binding already destroyed?", "if", "(", "!", "this", ".", "$", ")", "{", "return", ";", "}", "var", "e", ";", "for", "(", "var", "j", "=", "0", ";", "j", "<", "this", ".", "$events", ".", "length", ";", "j", "++", ")", "{", "e", "=", "this", ".", "$events", "[", "j", "]", ";", "this", ".", "$", ".", "scope", ".", "unbind", "(", "e", ".", "eventType", ",", "e", ".", "callback", ",", "this", ")", ";", "}", "this", ".", "$", ".", "scope", ".", "unbind", "(", "'destroy'", ",", "this", ".", "destroy", ",", "this", ")", ";", "if", "(", "this", ".", "$", ".", "twoWay", "===", "true", ")", "{", "this", ".", "$", ".", "target", ".", "unbind", "(", "this", ".", "$", ".", "targetEvent", ",", "this", ".", "_revCallback", ",", "this", ")", ";", "}", "if", "(", "this", ".", "$subBinding", ")", "{", "this", ".", "$subBinding", ".", "destroy", "(", ")", ";", "this", ".", "$subBinding", "=", "null", ";", "}", "// destroy parameter bindings", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "$parameters", ".", "length", ";", "i", "++", ")", "{", "var", "par", "=", "this", ".", "$parameters", "[", "i", "]", ";", "if", "(", "par", "instanceof", "Binding", ")", "{", "par", ".", "destroy", "(", ")", ";", "}", "}", "this", ".", "$parameters", "=", "null", ";", "this", ".", "$", ".", "scope", "=", "this", ".", "$", ".", "target", "=", "this", ".", "$", ".", "callback", "=", "null", ";", "this", ".", "$", "=", "null", ";", "this", ".", "$targets", "=", "null", ";", "this", ".", "callBase", "(", ")", ";", "bindingsDestroyed", "++", ";", "if", "(", "bindingsDestroyed", "===", "500", ")", "{", "if", "(", "typeof", "(", "CollectGarbage", ")", "===", "\"function\"", ")", "{", "CollectGarbage", "(", ")", ";", "}", "bindingsDestroyed", "=", "0", ";", "}", "}" ]
Unbinds all events and destroys subBinding...
[ "Unbinds", "all", "events", "and", "destroys", "subBinding", "..." ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Binding.js#L374-L415
26,815
rappid/rAppid.js
js/core/Binding.js
function () { var parameters = []; for (var i = 0; i < this.$parameters.length; i++) { var para = this.$parameters[i]; if (para instanceof Binding) { para = para.getValue(); } parameters.push(para); } return parameters; }
javascript
function () { var parameters = []; for (var i = 0; i < this.$parameters.length; i++) { var para = this.$parameters[i]; if (para instanceof Binding) { para = para.getValue(); } parameters.push(para); } return parameters; }
[ "function", "(", ")", "{", "var", "parameters", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "$parameters", ".", "length", ";", "i", "++", ")", "{", "var", "para", "=", "this", ".", "$parameters", "[", "i", "]", ";", "if", "(", "para", "instanceof", "Binding", ")", "{", "para", "=", "para", ".", "getValue", "(", ")", ";", "}", "parameters", ".", "push", "(", "para", ")", ";", "}", "return", "parameters", ";", "}" ]
Returns an array with values of all function parameters @return {Array} @private
[ "Returns", "an", "array", "with", "values", "of", "all", "function", "parameters" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Binding.js#L421-L431
26,816
rappid/rAppid.js
js/core/Binding.js
function () { if (this.$subBinding) { this.$subBinding.invalidateValueCache(); return this.$subBinding.getValue(); } else { if (this.$cachedValue !== undefined && !this.$jsonObject) { return this.$cachedValue; } this.$originalValue = undefined; if (this.$.fnc && !this.$jsonObject) { this.$originalValue = this.$.fnc.apply(this.$.scope, this._getFncParameters()); } else if (this.$.path.length === 1) { this.$originalValue = this.$.scope.get(this.$.key.name); } else if (this.$jsonObject && !_.isString(this.$jsonObject)) { this.$originalValue = this.$.scope.get(this.$jsonObject, this.$.path.slice(1)); } else { this.$originalValue = this.$.scope.get(this.$.path); } this.$cachedValue = this.transform.call(this.transformScope, this.$originalValue); return this.$cachedValue; } }
javascript
function () { if (this.$subBinding) { this.$subBinding.invalidateValueCache(); return this.$subBinding.getValue(); } else { if (this.$cachedValue !== undefined && !this.$jsonObject) { return this.$cachedValue; } this.$originalValue = undefined; if (this.$.fnc && !this.$jsonObject) { this.$originalValue = this.$.fnc.apply(this.$.scope, this._getFncParameters()); } else if (this.$.path.length === 1) { this.$originalValue = this.$.scope.get(this.$.key.name); } else if (this.$jsonObject && !_.isString(this.$jsonObject)) { this.$originalValue = this.$.scope.get(this.$jsonObject, this.$.path.slice(1)); } else { this.$originalValue = this.$.scope.get(this.$.path); } this.$cachedValue = this.transform.call(this.transformScope, this.$originalValue); return this.$cachedValue; } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "$subBinding", ")", "{", "this", ".", "$subBinding", ".", "invalidateValueCache", "(", ")", ";", "return", "this", ".", "$subBinding", ".", "getValue", "(", ")", ";", "}", "else", "{", "if", "(", "this", ".", "$cachedValue", "!==", "undefined", "&&", "!", "this", ".", "$jsonObject", ")", "{", "return", "this", ".", "$cachedValue", ";", "}", "this", ".", "$originalValue", "=", "undefined", ";", "if", "(", "this", ".", "$", ".", "fnc", "&&", "!", "this", ".", "$jsonObject", ")", "{", "this", ".", "$originalValue", "=", "this", ".", "$", ".", "fnc", ".", "apply", "(", "this", ".", "$", ".", "scope", ",", "this", ".", "_getFncParameters", "(", ")", ")", ";", "}", "else", "if", "(", "this", ".", "$", ".", "path", ".", "length", "===", "1", ")", "{", "this", ".", "$originalValue", "=", "this", ".", "$", ".", "scope", ".", "get", "(", "this", ".", "$", ".", "key", ".", "name", ")", ";", "}", "else", "if", "(", "this", ".", "$jsonObject", "&&", "!", "_", ".", "isString", "(", "this", ".", "$jsonObject", ")", ")", "{", "this", ".", "$originalValue", "=", "this", ".", "$", ".", "scope", ".", "get", "(", "this", ".", "$jsonObject", ",", "this", ".", "$", ".", "path", ".", "slice", "(", "1", ")", ")", ";", "}", "else", "{", "this", ".", "$originalValue", "=", "this", ".", "$", ".", "scope", ".", "get", "(", "this", ".", "$", ".", "path", ")", ";", "}", "this", ".", "$cachedValue", "=", "this", ".", "transform", ".", "call", "(", "this", ".", "transformScope", ",", "this", ".", "$originalValue", ")", ";", "return", "this", ".", "$cachedValue", ";", "}", "}" ]
Returns the transformed value of the binding or null, if the binding path is not present @return {*}
[ "Returns", "the", "transformed", "value", "of", "the", "binding", "or", "null", "if", "the", "binding", "path", "is", "not", "present" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Binding.js#L436-L460
26,817
rappid/rAppid.js
js/core/Binding.js
function () { // get value var val = this.getContextValue(); var target, targets = this.$.root.getTargets(); if (targets) { for (var i = 0; i < targets.length; i++) { target = targets[i]; if (target.key instanceof Function) { target.key.call(target.scope, val, this); } else { target.scope.set(target.key, val); } } } }
javascript
function () { // get value var val = this.getContextValue(); var target, targets = this.$.root.getTargets(); if (targets) { for (var i = 0; i < targets.length; i++) { target = targets[i]; if (target.key instanceof Function) { target.key.call(target.scope, val, this); } else { target.scope.set(target.key, val); } } } }
[ "function", "(", ")", "{", "// get value", "var", "val", "=", "this", ".", "getContextValue", "(", ")", ";", "var", "target", ",", "targets", "=", "this", ".", "$", ".", "root", ".", "getTargets", "(", ")", ";", "if", "(", "targets", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "targets", ".", "length", ";", "i", "++", ")", "{", "target", "=", "targets", "[", "i", "]", ";", "if", "(", "target", ".", "key", "instanceof", "Function", ")", "{", "target", ".", "key", ".", "call", "(", "target", ".", "scope", ",", "val", ",", "this", ")", ";", "}", "else", "{", "target", ".", "scope", ".", "set", "(", "target", ".", "key", ",", "val", ")", ";", "}", "}", "}", "}" ]
This method triggers the binding and syncs the target with the scope
[ "This", "method", "triggers", "the", "binding", "and", "syncs", "the", "target", "with", "the", "scope" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Binding.js#L480-L497
26,818
rappid/rAppid.js
js/core/Bindable.js
function () { if (this._$source) { var val, attributes = {}, unsetAttributes = {}; for (var key in this.$) { if (this.$.hasOwnProperty(key)) { val = this.$[key]; if (val instanceof Bindable && val.sync()) { attributes[key] = val._$source; } else { attributes[key] = val; } } } // remove all attributes, which are not in clone for (var sourceKey in this._$source.$) { if (this._$source.$.hasOwnProperty(sourceKey)) { if (!attributes.hasOwnProperty(sourceKey)) { unsetAttributes[sourceKey] = ""; } } } this._$source.set(unsetAttributes, {unset: true}); this._$source.set(attributes); return true; } else { return false; } }
javascript
function () { if (this._$source) { var val, attributes = {}, unsetAttributes = {}; for (var key in this.$) { if (this.$.hasOwnProperty(key)) { val = this.$[key]; if (val instanceof Bindable && val.sync()) { attributes[key] = val._$source; } else { attributes[key] = val; } } } // remove all attributes, which are not in clone for (var sourceKey in this._$source.$) { if (this._$source.$.hasOwnProperty(sourceKey)) { if (!attributes.hasOwnProperty(sourceKey)) { unsetAttributes[sourceKey] = ""; } } } this._$source.set(unsetAttributes, {unset: true}); this._$source.set(attributes); return true; } else { return false; } }
[ "function", "(", ")", "{", "if", "(", "this", ".", "_$source", ")", "{", "var", "val", ",", "attributes", "=", "{", "}", ",", "unsetAttributes", "=", "{", "}", ";", "for", "(", "var", "key", "in", "this", ".", "$", ")", "{", "if", "(", "this", ".", "$", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "val", "=", "this", ".", "$", "[", "key", "]", ";", "if", "(", "val", "instanceof", "Bindable", "&&", "val", ".", "sync", "(", ")", ")", "{", "attributes", "[", "key", "]", "=", "val", ".", "_$source", ";", "}", "else", "{", "attributes", "[", "key", "]", "=", "val", ";", "}", "}", "}", "// remove all attributes, which are not in clone", "for", "(", "var", "sourceKey", "in", "this", ".", "_$source", ".", "$", ")", "{", "if", "(", "this", ".", "_$source", ".", "$", ".", "hasOwnProperty", "(", "sourceKey", ")", ")", "{", "if", "(", "!", "attributes", ".", "hasOwnProperty", "(", "sourceKey", ")", ")", "{", "unsetAttributes", "[", "sourceKey", "]", "=", "\"\"", ";", "}", "}", "}", "this", ".", "_$source", ".", "set", "(", "unsetAttributes", ",", "{", "unset", ":", "true", "}", ")", ";", "this", ".", "_$source", ".", "set", "(", "attributes", ")", ";", "return", "true", ";", "}", "else", "{", "return", "false", ";", "}", "}" ]
Writes attributes back to the source
[ "Writes", "attributes", "back", "to", "the", "source" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Bindable.js#L500-L528
26,819
rappid/rAppid.js
js/core/Bindable.js
function (attribute, key) { if (this.inject && this.inject.hasOwnProperty(key)) { return attribute; } else if (attribute instanceof Bindable) { return attribute.clone(); } else if (attribute && (attribute.clone instanceof Function)) { return attribute.clone(); } else if (_.isArray(attribute)) { var retArray = []; for (var i = 0; i < attribute.length; i++) { retArray.push(this._cloneAttribute(attribute[i])); } return retArray; } else if (attribute instanceof Date) { return new Date(attribute.getTime()); } else if (_.isObject(attribute)) { var retObject = {}; for (var attrKey in attribute) { if (attribute.hasOwnProperty(attrKey)) { retObject[attrKey] = this._cloneAttribute(attribute[attrKey], attrKey); } } return retObject; } else { return attribute; } }
javascript
function (attribute, key) { if (this.inject && this.inject.hasOwnProperty(key)) { return attribute; } else if (attribute instanceof Bindable) { return attribute.clone(); } else if (attribute && (attribute.clone instanceof Function)) { return attribute.clone(); } else if (_.isArray(attribute)) { var retArray = []; for (var i = 0; i < attribute.length; i++) { retArray.push(this._cloneAttribute(attribute[i])); } return retArray; } else if (attribute instanceof Date) { return new Date(attribute.getTime()); } else if (_.isObject(attribute)) { var retObject = {}; for (var attrKey in attribute) { if (attribute.hasOwnProperty(attrKey)) { retObject[attrKey] = this._cloneAttribute(attribute[attrKey], attrKey); } } return retObject; } else { return attribute; } }
[ "function", "(", "attribute", ",", "key", ")", "{", "if", "(", "this", ".", "inject", "&&", "this", ".", "inject", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "return", "attribute", ";", "}", "else", "if", "(", "attribute", "instanceof", "Bindable", ")", "{", "return", "attribute", ".", "clone", "(", ")", ";", "}", "else", "if", "(", "attribute", "&&", "(", "attribute", ".", "clone", "instanceof", "Function", ")", ")", "{", "return", "attribute", ".", "clone", "(", ")", ";", "}", "else", "if", "(", "_", ".", "isArray", "(", "attribute", ")", ")", "{", "var", "retArray", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "attribute", ".", "length", ";", "i", "++", ")", "{", "retArray", ".", "push", "(", "this", ".", "_cloneAttribute", "(", "attribute", "[", "i", "]", ")", ")", ";", "}", "return", "retArray", ";", "}", "else", "if", "(", "attribute", "instanceof", "Date", ")", "{", "return", "new", "Date", "(", "attribute", ".", "getTime", "(", ")", ")", ";", "}", "else", "if", "(", "_", ".", "isObject", "(", "attribute", ")", ")", "{", "var", "retObject", "=", "{", "}", ";", "for", "(", "var", "attrKey", "in", "attribute", ")", "{", "if", "(", "attribute", ".", "hasOwnProperty", "(", "attrKey", ")", ")", "{", "retObject", "[", "attrKey", "]", "=", "this", ".", "_cloneAttribute", "(", "attribute", "[", "attrKey", "]", ",", "attrKey", ")", ";", "}", "}", "return", "retObject", ";", "}", "else", "{", "return", "attribute", ";", "}", "}" ]
Returns a copy of the attribute. This method is a hook for further cloning options @param attribute @param key @private
[ "Returns", "a", "copy", "of", "the", "attribute", ".", "This", "method", "is", "a", "hook", "for", "further", "cloning", "options" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Bindable.js#L568-L594
26,820
rappid/rAppid.js
js/core/Bindable.js
function (key, value, options) { if (_.isNumber(key)) { key = String(key); } if (_.isString(key)) { var attributes = {}; attributes[key] = value; } else { options = value; attributes = key; } options = options || {silent: false, unset: false, force: false}; // for un-setting attributes if (options.unset) { for (key in attributes) { if (attributes.hasOwnProperty(key)) { attributes[key] = void 0; } } } var changedAttributes = {}, changedAttributesCount = 0, now = this.$, val, prev; for (key in attributes) { if (attributes.hasOwnProperty(key)) { // get the value val = attributes[key]; // unset attribute or change it ... if (options.unset === true) { prev = now[key]; delete now[key]; changedAttributes[key] = undefined; changedAttributesCount++; this.$previousAttributes[key] = prev; } else { if (options.force || !isEqual(now[key], attributes[key])) { prev = options.initial ? null : now[key]; this.$previousAttributes[key] = prev; now[key] = attributes[key]; changedAttributes[key] = now[key]; changedAttributesCount++; } } } } var commitMethod; if (changedAttributesCount) { for (key in changedAttributes) { if (changedAttributes.hasOwnProperty(key)) { commitMethod = this['_commit' + key.charAt(0).toUpperCase() + key.substr(1)]; if (commitMethod instanceof Function) { // call method if (commitMethod.call(this, now[key], this.$previousAttributes[key], options) === false) { // false returned rollback changedAttributesCount--; now[key] = this.$previousAttributes[key]; } } } } if (changedAttributesCount) { this._commitChangedAttributes(changedAttributes, options); if (!options.silent) { for (key in changedAttributes) { if (changedAttributes.hasOwnProperty(key)) { this.trigger('change:' + key, changedAttributes[key], this); } } this.trigger('change', changedAttributes, this); } } } return this; }
javascript
function (key, value, options) { if (_.isNumber(key)) { key = String(key); } if (_.isString(key)) { var attributes = {}; attributes[key] = value; } else { options = value; attributes = key; } options = options || {silent: false, unset: false, force: false}; // for un-setting attributes if (options.unset) { for (key in attributes) { if (attributes.hasOwnProperty(key)) { attributes[key] = void 0; } } } var changedAttributes = {}, changedAttributesCount = 0, now = this.$, val, prev; for (key in attributes) { if (attributes.hasOwnProperty(key)) { // get the value val = attributes[key]; // unset attribute or change it ... if (options.unset === true) { prev = now[key]; delete now[key]; changedAttributes[key] = undefined; changedAttributesCount++; this.$previousAttributes[key] = prev; } else { if (options.force || !isEqual(now[key], attributes[key])) { prev = options.initial ? null : now[key]; this.$previousAttributes[key] = prev; now[key] = attributes[key]; changedAttributes[key] = now[key]; changedAttributesCount++; } } } } var commitMethod; if (changedAttributesCount) { for (key in changedAttributes) { if (changedAttributes.hasOwnProperty(key)) { commitMethod = this['_commit' + key.charAt(0).toUpperCase() + key.substr(1)]; if (commitMethod instanceof Function) { // call method if (commitMethod.call(this, now[key], this.$previousAttributes[key], options) === false) { // false returned rollback changedAttributesCount--; now[key] = this.$previousAttributes[key]; } } } } if (changedAttributesCount) { this._commitChangedAttributes(changedAttributes, options); if (!options.silent) { for (key in changedAttributes) { if (changedAttributes.hasOwnProperty(key)) { this.trigger('change:' + key, changedAttributes[key], this); } } this.trigger('change', changedAttributes, this); } } } return this; }
[ "function", "(", "key", ",", "value", ",", "options", ")", "{", "if", "(", "_", ".", "isNumber", "(", "key", ")", ")", "{", "key", "=", "String", "(", "key", ")", ";", "}", "if", "(", "_", ".", "isString", "(", "key", ")", ")", "{", "var", "attributes", "=", "{", "}", ";", "attributes", "[", "key", "]", "=", "value", ";", "}", "else", "{", "options", "=", "value", ";", "attributes", "=", "key", ";", "}", "options", "=", "options", "||", "{", "silent", ":", "false", ",", "unset", ":", "false", ",", "force", ":", "false", "}", ";", "// for un-setting attributes", "if", "(", "options", ".", "unset", ")", "{", "for", "(", "key", "in", "attributes", ")", "{", "if", "(", "attributes", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "attributes", "[", "key", "]", "=", "void", "0", ";", "}", "}", "}", "var", "changedAttributes", "=", "{", "}", ",", "changedAttributesCount", "=", "0", ",", "now", "=", "this", ".", "$", ",", "val", ",", "prev", ";", "for", "(", "key", "in", "attributes", ")", "{", "if", "(", "attributes", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "// get the value", "val", "=", "attributes", "[", "key", "]", ";", "// unset attribute or change it ...", "if", "(", "options", ".", "unset", "===", "true", ")", "{", "prev", "=", "now", "[", "key", "]", ";", "delete", "now", "[", "key", "]", ";", "changedAttributes", "[", "key", "]", "=", "undefined", ";", "changedAttributesCount", "++", ";", "this", ".", "$previousAttributes", "[", "key", "]", "=", "prev", ";", "}", "else", "{", "if", "(", "options", ".", "force", "||", "!", "isEqual", "(", "now", "[", "key", "]", ",", "attributes", "[", "key", "]", ")", ")", "{", "prev", "=", "options", ".", "initial", "?", "null", ":", "now", "[", "key", "]", ";", "this", ".", "$previousAttributes", "[", "key", "]", "=", "prev", ";", "now", "[", "key", "]", "=", "attributes", "[", "key", "]", ";", "changedAttributes", "[", "key", "]", "=", "now", "[", "key", "]", ";", "changedAttributesCount", "++", ";", "}", "}", "}", "}", "var", "commitMethod", ";", "if", "(", "changedAttributesCount", ")", "{", "for", "(", "key", "in", "changedAttributes", ")", "{", "if", "(", "changedAttributes", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "commitMethod", "=", "this", "[", "'_commit'", "+", "key", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "key", ".", "substr", "(", "1", ")", "]", ";", "if", "(", "commitMethod", "instanceof", "Function", ")", "{", "// call method", "if", "(", "commitMethod", ".", "call", "(", "this", ",", "now", "[", "key", "]", ",", "this", ".", "$previousAttributes", "[", "key", "]", ",", "options", ")", "===", "false", ")", "{", "// false returned rollback", "changedAttributesCount", "--", ";", "now", "[", "key", "]", "=", "this", ".", "$previousAttributes", "[", "key", "]", ";", "}", "}", "}", "}", "if", "(", "changedAttributesCount", ")", "{", "this", ".", "_commitChangedAttributes", "(", "changedAttributes", ",", "options", ")", ";", "if", "(", "!", "options", ".", "silent", ")", "{", "for", "(", "key", "in", "changedAttributes", ")", "{", "if", "(", "changedAttributes", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "this", ".", "trigger", "(", "'change:'", "+", "key", ",", "changedAttributes", "[", "key", "]", ",", "this", ")", ";", "}", "}", "this", ".", "trigger", "(", "'change'", ",", "changedAttributes", ",", "this", ")", ";", "}", "}", "}", "return", "this", ";", "}" ]
Sets new values for attributes and notify about changes @param {String} key The attribute key @param {String} value The attribute value @param {Object} options A hash of options @param {Boolean} [options.silent=false] if true no event is triggered on change @param {Boolean} [options.unset=false] if true the attribute gets deleted @return {js.core.Bindable} this
[ "Sets", "new", "values", "for", "attributes", "and", "notify", "about", "changes" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/Bindable.js#L651-L738
26,821
rappid/rAppid.js
srv/core/AuthenticationService.js
function (authenticationRequest) { var authenticationProviders = this.$providers, provider; for (var i = 0; i < authenticationProviders.length; i++) { provider = authenticationProviders[i]; if (provider.isResponsibleForAuthenticationRequest(authenticationRequest)) { return provider; } } return null; }
javascript
function (authenticationRequest) { var authenticationProviders = this.$providers, provider; for (var i = 0; i < authenticationProviders.length; i++) { provider = authenticationProviders[i]; if (provider.isResponsibleForAuthenticationRequest(authenticationRequest)) { return provider; } } return null; }
[ "function", "(", "authenticationRequest", ")", "{", "var", "authenticationProviders", "=", "this", ".", "$providers", ",", "provider", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "authenticationProviders", ".", "length", ";", "i", "++", ")", "{", "provider", "=", "authenticationProviders", "[", "i", "]", ";", "if", "(", "provider", ".", "isResponsibleForAuthenticationRequest", "(", "authenticationRequest", ")", ")", "{", "return", "provider", ";", "}", "}", "return", "null", ";", "}" ]
Returns the authentication provider for a given request @param authenticationRequest @returns {*}
[ "Returns", "the", "authentication", "provider", "for", "a", "given", "request" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/srv/core/AuthenticationService.js#L79-L95
26,822
rappid/rAppid.js
srv/core/AuthenticationService.js
function (context, token, callback) { var authentication = this.$.dataSource.createEntity(Authentication, token), self = this; // setup authentication this.$stage.$bus.setUp(authentication); flow() .seq("authentication", function (cb) { authentication.fetch({noCache: true}, function (err) { if (!err) { var now = new Date(); if (authentication.$.updated.getTime() < now.getTime() - (1000 * self.$.tokenLifeTime)) { // remove token authentication.remove(); // return error err = AuthenticationError.AUTHENTICATION_EXPIRED; } } else { // TODO: change to authentication not found err = AuthenticationError.AUTHENTICATION_EXPIRED; } cb(err, authentication); }); }) .seq(function (cb) { this.vars.authentication.set('updated', new Date()); this.vars.authentication.save(null, cb); }) .seq(function (cb) { // init authentication this.vars.authentication.init(cb); }) .exec(function (err, results) { authentication = results.authentication; if (!err && authentication) { context.user.addAuthentication(authentication); } callback && callback(err, authentication); }); }
javascript
function (context, token, callback) { var authentication = this.$.dataSource.createEntity(Authentication, token), self = this; // setup authentication this.$stage.$bus.setUp(authentication); flow() .seq("authentication", function (cb) { authentication.fetch({noCache: true}, function (err) { if (!err) { var now = new Date(); if (authentication.$.updated.getTime() < now.getTime() - (1000 * self.$.tokenLifeTime)) { // remove token authentication.remove(); // return error err = AuthenticationError.AUTHENTICATION_EXPIRED; } } else { // TODO: change to authentication not found err = AuthenticationError.AUTHENTICATION_EXPIRED; } cb(err, authentication); }); }) .seq(function (cb) { this.vars.authentication.set('updated', new Date()); this.vars.authentication.save(null, cb); }) .seq(function (cb) { // init authentication this.vars.authentication.init(cb); }) .exec(function (err, results) { authentication = results.authentication; if (!err && authentication) { context.user.addAuthentication(authentication); } callback && callback(err, authentication); }); }
[ "function", "(", "context", ",", "token", ",", "callback", ")", "{", "var", "authentication", "=", "this", ".", "$", ".", "dataSource", ".", "createEntity", "(", "Authentication", ",", "token", ")", ",", "self", "=", "this", ";", "// setup authentication", "this", ".", "$stage", ".", "$bus", ".", "setUp", "(", "authentication", ")", ";", "flow", "(", ")", ".", "seq", "(", "\"authentication\"", ",", "function", "(", "cb", ")", "{", "authentication", ".", "fetch", "(", "{", "noCache", ":", "true", "}", ",", "function", "(", "err", ")", "{", "if", "(", "!", "err", ")", "{", "var", "now", "=", "new", "Date", "(", ")", ";", "if", "(", "authentication", ".", "$", ".", "updated", ".", "getTime", "(", ")", "<", "now", ".", "getTime", "(", ")", "-", "(", "1000", "*", "self", ".", "$", ".", "tokenLifeTime", ")", ")", "{", "// remove token", "authentication", ".", "remove", "(", ")", ";", "// return error", "err", "=", "AuthenticationError", ".", "AUTHENTICATION_EXPIRED", ";", "}", "}", "else", "{", "// TODO: change to authentication not found", "err", "=", "AuthenticationError", ".", "AUTHENTICATION_EXPIRED", ";", "}", "cb", "(", "err", ",", "authentication", ")", ";", "}", ")", ";", "}", ")", ".", "seq", "(", "function", "(", "cb", ")", "{", "this", ".", "vars", ".", "authentication", ".", "set", "(", "'updated'", ",", "new", "Date", "(", ")", ")", ";", "this", ".", "vars", ".", "authentication", ".", "save", "(", "null", ",", "cb", ")", ";", "}", ")", ".", "seq", "(", "function", "(", "cb", ")", "{", "// init authentication", "this", ".", "vars", ".", "authentication", ".", "init", "(", "cb", ")", ";", "}", ")", ".", "exec", "(", "function", "(", "err", ",", "results", ")", "{", "authentication", "=", "results", ".", "authentication", ";", "if", "(", "!", "err", "&&", "authentication", ")", "{", "context", ".", "user", ".", "addAuthentication", "(", "authentication", ")", ";", "}", "callback", "&&", "callback", "(", "err", ",", "authentication", ")", ";", "}", ")", ";", "}" ]
Checks token against a database @param token @param callback
[ "Checks", "token", "against", "a", "database" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/srv/core/AuthenticationService.js#L120-L161
26,823
rappid/rAppid.js
srv/core/AuthenticationService.js
function (authentication, callback) { /*** * Let's save the authentication and so the user is logged in * */ var token = generateId(); var authenticationInstance = this.$.dataSource.createEntity(Authentication, token); authenticationInstance.set(authentication.$); authenticationInstance.save(null, callback); }
javascript
function (authentication, callback) { /*** * Let's save the authentication and so the user is logged in * */ var token = generateId(); var authenticationInstance = this.$.dataSource.createEntity(Authentication, token); authenticationInstance.set(authentication.$); authenticationInstance.save(null, callback); }
[ "function", "(", "authentication", ",", "callback", ")", "{", "/***\n * Let's save the authentication and so the user is logged in\n *\n */", "var", "token", "=", "generateId", "(", ")", ";", "var", "authenticationInstance", "=", "this", ".", "$", ".", "dataSource", ".", "createEntity", "(", "Authentication", ",", "token", ")", ";", "authenticationInstance", ".", "set", "(", "authentication", ".", "$", ")", ";", "authenticationInstance", ".", "save", "(", "null", ",", "callback", ")", ";", "}" ]
Saves an authentication and adds an token to it @param authentication @param callback
[ "Saves", "an", "authentication", "and", "adds", "an", "token", "to", "it" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/srv/core/AuthenticationService.js#L279-L289
26,824
rappid/rAppid.js
srv/handler/rest/ResourceHandler.js
function (context, callback, checkParents) { if (this.$parentResource) { var self = this; flow() .seq("parentCollection", function (cb) { self.$parentResource._findCollection(context, cb); }) .seq("parent", function (cb) { var parentCollection = this.vars.parentCollection, id = parentCollection.$modelFactory.prototype.convertIdentifier(self.$parentResource.$resourceId), parent = parentCollection.createItem(id); if (checkParents) { parent.fetch(null, cb); } else { cb(null, parent); } }) .exec(function (err, results) { if (!err) { var collection = results.parent.getCollection(self.$resourceConfiguration.$.path); callback && callback(null, collection); } else { callback && callback(err); } }); } else { var dataSource = this.$restHandler.getDataSource(context, this); callback && callback(null, dataSource.createCollection(Collection.of(this._getModelFactory()), {pageSize: 100})); } }
javascript
function (context, callback, checkParents) { if (this.$parentResource) { var self = this; flow() .seq("parentCollection", function (cb) { self.$parentResource._findCollection(context, cb); }) .seq("parent", function (cb) { var parentCollection = this.vars.parentCollection, id = parentCollection.$modelFactory.prototype.convertIdentifier(self.$parentResource.$resourceId), parent = parentCollection.createItem(id); if (checkParents) { parent.fetch(null, cb); } else { cb(null, parent); } }) .exec(function (err, results) { if (!err) { var collection = results.parent.getCollection(self.$resourceConfiguration.$.path); callback && callback(null, collection); } else { callback && callback(err); } }); } else { var dataSource = this.$restHandler.getDataSource(context, this); callback && callback(null, dataSource.createCollection(Collection.of(this._getModelFactory()), {pageSize: 100})); } }
[ "function", "(", "context", ",", "callback", ",", "checkParents", ")", "{", "if", "(", "this", ".", "$parentResource", ")", "{", "var", "self", "=", "this", ";", "flow", "(", ")", ".", "seq", "(", "\"parentCollection\"", ",", "function", "(", "cb", ")", "{", "self", ".", "$parentResource", ".", "_findCollection", "(", "context", ",", "cb", ")", ";", "}", ")", ".", "seq", "(", "\"parent\"", ",", "function", "(", "cb", ")", "{", "var", "parentCollection", "=", "this", ".", "vars", ".", "parentCollection", ",", "id", "=", "parentCollection", ".", "$modelFactory", ".", "prototype", ".", "convertIdentifier", "(", "self", ".", "$parentResource", ".", "$resourceId", ")", ",", "parent", "=", "parentCollection", ".", "createItem", "(", "id", ")", ";", "if", "(", "checkParents", ")", "{", "parent", ".", "fetch", "(", "null", ",", "cb", ")", ";", "}", "else", "{", "cb", "(", "null", ",", "parent", ")", ";", "}", "}", ")", ".", "exec", "(", "function", "(", "err", ",", "results", ")", "{", "if", "(", "!", "err", ")", "{", "var", "collection", "=", "results", ".", "parent", ".", "getCollection", "(", "self", ".", "$resourceConfiguration", ".", "$", ".", "path", ")", ";", "callback", "&&", "callback", "(", "null", ",", "collection", ")", ";", "}", "else", "{", "callback", "&&", "callback", "(", "err", ")", ";", "}", "}", ")", ";", "}", "else", "{", "var", "dataSource", "=", "this", ".", "$restHandler", ".", "getDataSource", "(", "context", ",", "this", ")", ";", "callback", "&&", "callback", "(", "null", ",", "dataSource", ".", "createCollection", "(", "Collection", ".", "of", "(", "this", ".", "_getModelFactory", "(", ")", ")", ",", "{", "pageSize", ":", "100", "}", ")", ")", ";", "}", "}" ]
Returns a collection for this resource in the right context @param {srv.core.Context} context @param {Function} callback @param {Boolean} [checkParents] - default true @return {*} @private
[ "Returns", "a", "collection", "for", "this", "resource", "in", "the", "right", "context" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/srv/handler/rest/ResourceHandler.js#L178-L208
26,825
rappid/rAppid.js
js/core/History.js
function () { if (this.$processUrl) { var currentFragment = this._getFragment(); if (currentFragment == this.$fragment) { return false; } this.navigate(currentFragment, !this.$.useState, true, true, emptyCallback); } this.$processUrl = true; }
javascript
function () { if (this.$processUrl) { var currentFragment = this._getFragment(); if (currentFragment == this.$fragment) { return false; } this.navigate(currentFragment, !this.$.useState, true, true, emptyCallback); } this.$processUrl = true; }
[ "function", "(", ")", "{", "if", "(", "this", ".", "$processUrl", ")", "{", "var", "currentFragment", "=", "this", ".", "_getFragment", "(", ")", ";", "if", "(", "currentFragment", "==", "this", ".", "$fragment", ")", "{", "return", "false", ";", "}", "this", ".", "navigate", "(", "currentFragment", ",", "!", "this", ".", "$", ".", "useState", ",", "true", ",", "true", ",", "emptyCallback", ")", ";", "}", "this", ".", "$processUrl", "=", "true", ";", "}" ]
Checks if the current fragment has changed and calls navigate in case it did
[ "Checks", "if", "the", "current", "fragment", "has", "changed", "and", "calls", "navigate", "in", "case", "it", "did" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/History.js#L175-L188
26,826
rappid/rAppid.js
js/core/History.js
function (fragment, callback) { var routeExecutionStack = []; for (var i = 0; i < this.$routers.length; i++) { routeExecutionStack = routeExecutionStack.concat(this.$routers[i].generateRoutingStack(fragment)); } if (routeExecutionStack.length === 0) { this.routeNotFound(fragment, callback); } else { flow() .seqEach(routeExecutionStack, function(routingFunction, cb){ routingFunction(cb); }) .exec(callback); } }
javascript
function (fragment, callback) { var routeExecutionStack = []; for (var i = 0; i < this.$routers.length; i++) { routeExecutionStack = routeExecutionStack.concat(this.$routers[i].generateRoutingStack(fragment)); } if (routeExecutionStack.length === 0) { this.routeNotFound(fragment, callback); } else { flow() .seqEach(routeExecutionStack, function(routingFunction, cb){ routingFunction(cb); }) .exec(callback); } }
[ "function", "(", "fragment", ",", "callback", ")", "{", "var", "routeExecutionStack", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "$routers", ".", "length", ";", "i", "++", ")", "{", "routeExecutionStack", "=", "routeExecutionStack", ".", "concat", "(", "this", ".", "$routers", "[", "i", "]", ".", "generateRoutingStack", "(", "fragment", ")", ")", ";", "}", "if", "(", "routeExecutionStack", ".", "length", "===", "0", ")", "{", "this", ".", "routeNotFound", "(", "fragment", ",", "callback", ")", ";", "}", "else", "{", "flow", "(", ")", ".", "seqEach", "(", "routeExecutionStack", ",", "function", "(", "routingFunction", ",", "cb", ")", "{", "routingFunction", "(", "cb", ")", ";", "}", ")", ".", "exec", "(", "callback", ")", ";", "}", "}" ]
Triggers a route @param {String} fragment - the fragment which should be triggered @param {Function} callback - gets called after the route execution stack is done
[ "Triggers", "a", "route" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/History.js#L195-L212
26,827
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.pure.js
getPlugins
function getPlugins(){ var plugins = $p.plugins, f = function(){}; f.prototype = plugins; // do not overwrite functions if external definition f.prototype.compile = plugins.compile || compile; f.prototype.render = plugins.render || render; f.prototype.autoRender = plugins.autoRender || autoRender; f.prototype.find = plugins.find || find; // give the compiler and the error handling to the plugin context f.prototype._compiler = compiler; f.prototype._error = error; return new f(); }
javascript
function getPlugins(){ var plugins = $p.plugins, f = function(){}; f.prototype = plugins; // do not overwrite functions if external definition f.prototype.compile = plugins.compile || compile; f.prototype.render = plugins.render || render; f.prototype.autoRender = plugins.autoRender || autoRender; f.prototype.find = plugins.find || find; // give the compiler and the error handling to the plugin context f.prototype._compiler = compiler; f.prototype._error = error; return new f(); }
[ "function", "getPlugins", "(", ")", "{", "var", "plugins", "=", "$p", ".", "plugins", ",", "f", "=", "function", "(", ")", "{", "}", ";", "f", ".", "prototype", "=", "plugins", ";", "// do not overwrite functions if external definition", "f", ".", "prototype", ".", "compile", "=", "plugins", ".", "compile", "||", "compile", ";", "f", ".", "prototype", ".", "render", "=", "plugins", ".", "render", "||", "render", ";", "f", ".", "prototype", ".", "autoRender", "=", "plugins", ".", "autoRender", "||", "autoRender", ";", "f", ".", "prototype", ".", "find", "=", "plugins", ".", "find", "||", "find", ";", "// give the compiler and the error handling to the plugin context", "f", ".", "prototype", ".", "_compiler", "=", "compiler", ";", "f", ".", "prototype", ".", "_error", "=", "error", ";", "return", "new", "f", "(", ")", ";", "}" ]
return a new instance of plugins
[ "return", "a", "new", "instance", "of", "plugins" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.pure.js#L87-L103
26,828
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.pure.js
wrapquote
function wrapquote(qfn, f){ return function(ctxt){ return qfn('' + f.call(ctxt.context, ctxt)); }; }
javascript
function wrapquote(qfn, f){ return function(ctxt){ return qfn('' + f.call(ctxt.context, ctxt)); }; }
[ "function", "wrapquote", "(", "qfn", ",", "f", ")", "{", "return", "function", "(", "ctxt", ")", "{", "return", "qfn", "(", "''", "+", "f", ".", "call", "(", "ctxt", ".", "context", ",", "ctxt", ")", ")", ";", "}", ";", "}" ]
returns the string generator function
[ "returns", "the", "string", "generator", "function" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.pure.js#L119-L123
26,829
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.pure.js
find
function find(n, sel){ if(typeof n === 'string'){ sel = n; n = false; } if(typeof document.querySelectorAll !== 'undefined'){ return (n||document).querySelectorAll( sel ); }else{ error('You can test PURE standalone with: iPhone, FF3.5+, Safari4+ and IE8+\n\nTo run PURE on your browser, you need a JS library/framework with a CSS selector engine'); } }
javascript
function find(n, sel){ if(typeof n === 'string'){ sel = n; n = false; } if(typeof document.querySelectorAll !== 'undefined'){ return (n||document).querySelectorAll( sel ); }else{ error('You can test PURE standalone with: iPhone, FF3.5+, Safari4+ and IE8+\n\nTo run PURE on your browser, you need a JS library/framework with a CSS selector engine'); } }
[ "function", "find", "(", "n", ",", "sel", ")", "{", "if", "(", "typeof", "n", "===", "'string'", ")", "{", "sel", "=", "n", ";", "n", "=", "false", ";", "}", "if", "(", "typeof", "document", ".", "querySelectorAll", "!==", "'undefined'", ")", "{", "return", "(", "n", "||", "document", ")", ".", "querySelectorAll", "(", "sel", ")", ";", "}", "else", "{", "error", "(", "'You can test PURE standalone with: iPhone, FF3.5+, Safari4+ and IE8+\\n\\nTo run PURE on your browser, you need a JS library/framework with a CSS selector engine'", ")", ";", "}", "}" ]
default find using querySelector when available on the browser
[ "default", "find", "using", "querySelector", "when", "available", "on", "the", "browser" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.pure.js#L126-L136
26,830
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.pure.js
parseloopspec
function parseloopspec(p){ var m = p.match( /^(\w+)\s*<-\s*(\S+)?$/ ); if(m === null){ error('bad loop spec: "' + p + '"'); } if(m[1] === 'item'){ error('"item<-..." is a reserved word for the current running iteration.\n\nPlease choose another name for your loop.'); } if( !m[2] || (m[2] && (/context/i).test(m[2]))){ //undefined or space(IE) m[2] = function(ctxt){return ctxt.context;}; } return {name: m[1], sel: m[2]}; }
javascript
function parseloopspec(p){ var m = p.match( /^(\w+)\s*<-\s*(\S+)?$/ ); if(m === null){ error('bad loop spec: "' + p + '"'); } if(m[1] === 'item'){ error('"item<-..." is a reserved word for the current running iteration.\n\nPlease choose another name for your loop.'); } if( !m[2] || (m[2] && (/context/i).test(m[2]))){ //undefined or space(IE) m[2] = function(ctxt){return ctxt.context;}; } return {name: m[1], sel: m[2]}; }
[ "function", "parseloopspec", "(", "p", ")", "{", "var", "m", "=", "p", ".", "match", "(", "/", "^(\\w+)\\s*<-\\s*(\\S+)?$", "/", ")", ";", "if", "(", "m", "===", "null", ")", "{", "error", "(", "'bad loop spec: \"'", "+", "p", "+", "'\"'", ")", ";", "}", "if", "(", "m", "[", "1", "]", "===", "'item'", ")", "{", "error", "(", "'\"item<-...\" is a reserved word for the current running iteration.\\n\\nPlease choose another name for your loop.'", ")", ";", "}", "if", "(", "!", "m", "[", "2", "]", "||", "(", "m", "[", "2", "]", "&&", "(", "/", "context", "/", "i", ")", ".", "test", "(", "m", "[", "2", "]", ")", ")", ")", "{", "//undefined or space(IE)", "m", "[", "2", "]", "=", "function", "(", "ctxt", ")", "{", "return", "ctxt", ".", "context", ";", "}", ";", "}", "return", "{", "name", ":", "m", "[", "1", "]", ",", "sel", ":", "m", "[", "2", "]", "}", ";", "}" ]
parse and check the loop directive
[ "parse", "and", "check", "the", "loop", "directive" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.pure.js#L171-L183
26,831
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.pure.js
loopfn
function loopfn(name, dselect, inner, sorter, filter){ return function(ctxt){ var a = dselect(ctxt), old = ctxt[name], temp = { items : a }, filtered = 0, length, strs = [], buildArg = function(idx, temp, ftr, len){ ctxt.pos = temp.pos = idx; ctxt.item = temp.item = a[ idx ]; ctxt.items = a; //if array, set a length property - filtered items typeof len !== 'undefined' && (ctxt.length = len); //if filter directive if(typeof ftr === 'function' && ftr(ctxt) === false){ filtered++; return; } strs.push( inner.call(temp, ctxt ) ); }; ctxt[name] = temp; if( isArray(a) ){ length = a.length || 0; // if sort directive if(typeof sorter === 'function'){ a.sort(sorter); } //loop on array for(var i = 0, ii = length; i < ii; i++){ buildArg(i, temp, filter, length - filtered); } }else{ if(a && typeof sorter !== 'undefined'){ error('sort is only available on arrays, not objects'); } //loop on collections for(var prop in a){ a.hasOwnProperty( prop ) && buildArg(prop, temp, filter); } } typeof old !== 'undefined' ? ctxt[name] = old : delete ctxt[name]; return strs.join(''); }; }
javascript
function loopfn(name, dselect, inner, sorter, filter){ return function(ctxt){ var a = dselect(ctxt), old = ctxt[name], temp = { items : a }, filtered = 0, length, strs = [], buildArg = function(idx, temp, ftr, len){ ctxt.pos = temp.pos = idx; ctxt.item = temp.item = a[ idx ]; ctxt.items = a; //if array, set a length property - filtered items typeof len !== 'undefined' && (ctxt.length = len); //if filter directive if(typeof ftr === 'function' && ftr(ctxt) === false){ filtered++; return; } strs.push( inner.call(temp, ctxt ) ); }; ctxt[name] = temp; if( isArray(a) ){ length = a.length || 0; // if sort directive if(typeof sorter === 'function'){ a.sort(sorter); } //loop on array for(var i = 0, ii = length; i < ii; i++){ buildArg(i, temp, filter, length - filtered); } }else{ if(a && typeof sorter !== 'undefined'){ error('sort is only available on arrays, not objects'); } //loop on collections for(var prop in a){ a.hasOwnProperty( prop ) && buildArg(prop, temp, filter); } } typeof old !== 'undefined' ? ctxt[name] = old : delete ctxt[name]; return strs.join(''); }; }
[ "function", "loopfn", "(", "name", ",", "dselect", ",", "inner", ",", "sorter", ",", "filter", ")", "{", "return", "function", "(", "ctxt", ")", "{", "var", "a", "=", "dselect", "(", "ctxt", ")", ",", "old", "=", "ctxt", "[", "name", "]", ",", "temp", "=", "{", "items", ":", "a", "}", ",", "filtered", "=", "0", ",", "length", ",", "strs", "=", "[", "]", ",", "buildArg", "=", "function", "(", "idx", ",", "temp", ",", "ftr", ",", "len", ")", "{", "ctxt", ".", "pos", "=", "temp", ".", "pos", "=", "idx", ";", "ctxt", ".", "item", "=", "temp", ".", "item", "=", "a", "[", "idx", "]", ";", "ctxt", ".", "items", "=", "a", ";", "//if array, set a length property - filtered items", "typeof", "len", "!==", "'undefined'", "&&", "(", "ctxt", ".", "length", "=", "len", ")", ";", "//if filter directive", "if", "(", "typeof", "ftr", "===", "'function'", "&&", "ftr", "(", "ctxt", ")", "===", "false", ")", "{", "filtered", "++", ";", "return", ";", "}", "strs", ".", "push", "(", "inner", ".", "call", "(", "temp", ",", "ctxt", ")", ")", ";", "}", ";", "ctxt", "[", "name", "]", "=", "temp", ";", "if", "(", "isArray", "(", "a", ")", ")", "{", "length", "=", "a", ".", "length", "||", "0", ";", "// if sort directive", "if", "(", "typeof", "sorter", "===", "'function'", ")", "{", "a", ".", "sort", "(", "sorter", ")", ";", "}", "//loop on array", "for", "(", "var", "i", "=", "0", ",", "ii", "=", "length", ";", "i", "<", "ii", ";", "i", "++", ")", "{", "buildArg", "(", "i", ",", "temp", ",", "filter", ",", "length", "-", "filtered", ")", ";", "}", "}", "else", "{", "if", "(", "a", "&&", "typeof", "sorter", "!==", "'undefined'", ")", "{", "error", "(", "'sort is only available on arrays, not objects'", ")", ";", "}", "//loop on collections", "for", "(", "var", "prop", "in", "a", ")", "{", "a", ".", "hasOwnProperty", "(", "prop", ")", "&&", "buildArg", "(", "prop", ",", "temp", ",", "filter", ")", ";", "}", "}", "typeof", "old", "!==", "'undefined'", "?", "ctxt", "[", "name", "]", "=", "old", ":", "delete", "ctxt", "[", "name", "]", ";", "return", "strs", ".", "join", "(", "''", ")", ";", "}", ";", "}" ]
read de loop data, and pass it to the inner rendering function
[ "read", "de", "loop", "data", "and", "pass", "it", "to", "the", "inner", "rendering", "function" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.pure.js#L346-L391
26,832
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.pure.js
loopgen
function loopgen(dom, sel, loop, fns){ var already = false, ls, sorter, filter, prop; for(prop in loop){ if(loop.hasOwnProperty(prop)){ if(prop === 'sort'){ sorter = loop.sort; continue; }else if(prop === 'filter'){ filter = loop.filter; continue; } if(already){ error('cannot have more than one loop on a target'); } ls = prop; already = true; } } if(!ls){ error('Error in the selector: ' + sel + '\nA directive action must be a string, a function or a loop(<-)'); } var dsel = loop[ls]; // if it's a simple data selector then we default to contents, not replacement. if(typeof(dsel) === 'string' || typeof(dsel) === 'function'){ loop = {}; loop[ls] = {root: dsel}; return loopgen(dom, sel, loop, fns); } var spec = parseloopspec(ls), itersel = dataselectfn(spec.sel), target = gettarget(dom, sel, true), nodes = target.nodes; for(i = 0; i < nodes.length; i++){ var node = nodes[i], inner = compiler(node, dsel); fns[fns.length] = wrapquote(target.quotefn, loopfn(spec.name, itersel, inner, sorter, filter)); target.nodes = [node]; // N.B. side effect on target. setsig(target, fns.length - 1); } }
javascript
function loopgen(dom, sel, loop, fns){ var already = false, ls, sorter, filter, prop; for(prop in loop){ if(loop.hasOwnProperty(prop)){ if(prop === 'sort'){ sorter = loop.sort; continue; }else if(prop === 'filter'){ filter = loop.filter; continue; } if(already){ error('cannot have more than one loop on a target'); } ls = prop; already = true; } } if(!ls){ error('Error in the selector: ' + sel + '\nA directive action must be a string, a function or a loop(<-)'); } var dsel = loop[ls]; // if it's a simple data selector then we default to contents, not replacement. if(typeof(dsel) === 'string' || typeof(dsel) === 'function'){ loop = {}; loop[ls] = {root: dsel}; return loopgen(dom, sel, loop, fns); } var spec = parseloopspec(ls), itersel = dataselectfn(spec.sel), target = gettarget(dom, sel, true), nodes = target.nodes; for(i = 0; i < nodes.length; i++){ var node = nodes[i], inner = compiler(node, dsel); fns[fns.length] = wrapquote(target.quotefn, loopfn(spec.name, itersel, inner, sorter, filter)); target.nodes = [node]; // N.B. side effect on target. setsig(target, fns.length - 1); } }
[ "function", "loopgen", "(", "dom", ",", "sel", ",", "loop", ",", "fns", ")", "{", "var", "already", "=", "false", ",", "ls", ",", "sorter", ",", "filter", ",", "prop", ";", "for", "(", "prop", "in", "loop", ")", "{", "if", "(", "loop", ".", "hasOwnProperty", "(", "prop", ")", ")", "{", "if", "(", "prop", "===", "'sort'", ")", "{", "sorter", "=", "loop", ".", "sort", ";", "continue", ";", "}", "else", "if", "(", "prop", "===", "'filter'", ")", "{", "filter", "=", "loop", ".", "filter", ";", "continue", ";", "}", "if", "(", "already", ")", "{", "error", "(", "'cannot have more than one loop on a target'", ")", ";", "}", "ls", "=", "prop", ";", "already", "=", "true", ";", "}", "}", "if", "(", "!", "ls", ")", "{", "error", "(", "'Error in the selector: '", "+", "sel", "+", "'\\nA directive action must be a string, a function or a loop(<-)'", ")", ";", "}", "var", "dsel", "=", "loop", "[", "ls", "]", ";", "// if it's a simple data selector then we default to contents, not replacement.", "if", "(", "typeof", "(", "dsel", ")", "===", "'string'", "||", "typeof", "(", "dsel", ")", "===", "'function'", ")", "{", "loop", "=", "{", "}", ";", "loop", "[", "ls", "]", "=", "{", "root", ":", "dsel", "}", ";", "return", "loopgen", "(", "dom", ",", "sel", ",", "loop", ",", "fns", ")", ";", "}", "var", "spec", "=", "parseloopspec", "(", "ls", ")", ",", "itersel", "=", "dataselectfn", "(", "spec", ".", "sel", ")", ",", "target", "=", "gettarget", "(", "dom", ",", "sel", ",", "true", ")", ",", "nodes", "=", "target", ".", "nodes", ";", "for", "(", "i", "=", "0", ";", "i", "<", "nodes", ".", "length", ";", "i", "++", ")", "{", "var", "node", "=", "nodes", "[", "i", "]", ",", "inner", "=", "compiler", "(", "node", ",", "dsel", ")", ";", "fns", "[", "fns", ".", "length", "]", "=", "wrapquote", "(", "target", ".", "quotefn", ",", "loopfn", "(", "spec", ".", "name", ",", "itersel", ",", "inner", ",", "sorter", ",", "filter", ")", ")", ";", "target", ".", "nodes", "=", "[", "node", "]", ";", "// N.B. side effect on target.", "setsig", "(", "target", ",", "fns", ".", "length", "-", "1", ")", ";", "}", "}" ]
generate the template for a loop node
[ "generate", "the", "template", "for", "a", "loop", "node" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.pure.js#L393-L433
26,833
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.pure.js
compiler
function compiler(dom, directive, data, ans){ var fns = []; // autoRendering nodes parsing -> auto-nodes ans = ans || data && getAutoNodes(dom, data); if(data){ var j, jj, cspec, n, target, nodes, itersel, node, inner; // for each auto-nodes while(ans.length > 0){ cspec = ans[0].cspec; n = ans[0].n; ans.splice(0, 1); if(cspec.t === 'str'){ // if the target is a value target = gettarget(n, cspec, false); setsig(target, fns.length); fns[fns.length] = wrapquote(target.quotefn, dataselectfn(cspec.prop)); }else{ // if the target is a loop itersel = dataselectfn(cspec.sel); target = gettarget(n, cspec, true); nodes = target.nodes; for(j = 0, jj = nodes.length; j < jj; j++){ node = nodes[j]; inner = compiler(node, false, data, ans); fns[fns.length] = wrapquote(target.quotefn, loopfn(cspec.sel, itersel, inner)); target.nodes = [node]; setsig(target, fns.length - 1); } } } } // read directives var target, dsel; for(var sel in directive){ if(directive.hasOwnProperty(sel)){ dsel = directive[sel]; if(typeof(dsel) === 'function' || typeof(dsel) === 'string'){ // set the value for the node/attr target = gettarget(dom, sel, false); setsig(target, fns.length); fns[fns.length] = wrapquote(target.quotefn, dataselectfn(dsel)); }else{ // loop on node loopgen(dom, sel, dsel, fns); } } } // convert node to a string var h = outerHTML(dom), pfns = []; // IE adds an unremovable "selected, value" attribute // hard replace while waiting for a better solution h = h.replace(/<([^>]+)\s(value\=""|selected)\s?([^>]*)>/ig, "<$1 $3>"); // remove attribute prefix h = h.split(attPfx).join(''); // slice the html string at "Sig" var parts = h.split( Sig ), p; // for each slice add the return string of for(var i = 1; i < parts.length; i++){ p = parts[i]; // part is of the form "fn-number:..." as placed there by setsig. pfns[i] = fns[ parseInt(p, 10) ]; parts[i] = p.substring( p.indexOf(':') + 1 ); } return concatenator(parts, pfns); }
javascript
function compiler(dom, directive, data, ans){ var fns = []; // autoRendering nodes parsing -> auto-nodes ans = ans || data && getAutoNodes(dom, data); if(data){ var j, jj, cspec, n, target, nodes, itersel, node, inner; // for each auto-nodes while(ans.length > 0){ cspec = ans[0].cspec; n = ans[0].n; ans.splice(0, 1); if(cspec.t === 'str'){ // if the target is a value target = gettarget(n, cspec, false); setsig(target, fns.length); fns[fns.length] = wrapquote(target.quotefn, dataselectfn(cspec.prop)); }else{ // if the target is a loop itersel = dataselectfn(cspec.sel); target = gettarget(n, cspec, true); nodes = target.nodes; for(j = 0, jj = nodes.length; j < jj; j++){ node = nodes[j]; inner = compiler(node, false, data, ans); fns[fns.length] = wrapquote(target.quotefn, loopfn(cspec.sel, itersel, inner)); target.nodes = [node]; setsig(target, fns.length - 1); } } } } // read directives var target, dsel; for(var sel in directive){ if(directive.hasOwnProperty(sel)){ dsel = directive[sel]; if(typeof(dsel) === 'function' || typeof(dsel) === 'string'){ // set the value for the node/attr target = gettarget(dom, sel, false); setsig(target, fns.length); fns[fns.length] = wrapquote(target.quotefn, dataselectfn(dsel)); }else{ // loop on node loopgen(dom, sel, dsel, fns); } } } // convert node to a string var h = outerHTML(dom), pfns = []; // IE adds an unremovable "selected, value" attribute // hard replace while waiting for a better solution h = h.replace(/<([^>]+)\s(value\=""|selected)\s?([^>]*)>/ig, "<$1 $3>"); // remove attribute prefix h = h.split(attPfx).join(''); // slice the html string at "Sig" var parts = h.split( Sig ), p; // for each slice add the return string of for(var i = 1; i < parts.length; i++){ p = parts[i]; // part is of the form "fn-number:..." as placed there by setsig. pfns[i] = fns[ parseInt(p, 10) ]; parts[i] = p.substring( p.indexOf(':') + 1 ); } return concatenator(parts, pfns); }
[ "function", "compiler", "(", "dom", ",", "directive", ",", "data", ",", "ans", ")", "{", "var", "fns", "=", "[", "]", ";", "// autoRendering nodes parsing -> auto-nodes", "ans", "=", "ans", "||", "data", "&&", "getAutoNodes", "(", "dom", ",", "data", ")", ";", "if", "(", "data", ")", "{", "var", "j", ",", "jj", ",", "cspec", ",", "n", ",", "target", ",", "nodes", ",", "itersel", ",", "node", ",", "inner", ";", "// for each auto-nodes", "while", "(", "ans", ".", "length", ">", "0", ")", "{", "cspec", "=", "ans", "[", "0", "]", ".", "cspec", ";", "n", "=", "ans", "[", "0", "]", ".", "n", ";", "ans", ".", "splice", "(", "0", ",", "1", ")", ";", "if", "(", "cspec", ".", "t", "===", "'str'", ")", "{", "// if the target is a value", "target", "=", "gettarget", "(", "n", ",", "cspec", ",", "false", ")", ";", "setsig", "(", "target", ",", "fns", ".", "length", ")", ";", "fns", "[", "fns", ".", "length", "]", "=", "wrapquote", "(", "target", ".", "quotefn", ",", "dataselectfn", "(", "cspec", ".", "prop", ")", ")", ";", "}", "else", "{", "// if the target is a loop", "itersel", "=", "dataselectfn", "(", "cspec", ".", "sel", ")", ";", "target", "=", "gettarget", "(", "n", ",", "cspec", ",", "true", ")", ";", "nodes", "=", "target", ".", "nodes", ";", "for", "(", "j", "=", "0", ",", "jj", "=", "nodes", ".", "length", ";", "j", "<", "jj", ";", "j", "++", ")", "{", "node", "=", "nodes", "[", "j", "]", ";", "inner", "=", "compiler", "(", "node", ",", "false", ",", "data", ",", "ans", ")", ";", "fns", "[", "fns", ".", "length", "]", "=", "wrapquote", "(", "target", ".", "quotefn", ",", "loopfn", "(", "cspec", ".", "sel", ",", "itersel", ",", "inner", ")", ")", ";", "target", ".", "nodes", "=", "[", "node", "]", ";", "setsig", "(", "target", ",", "fns", ".", "length", "-", "1", ")", ";", "}", "}", "}", "}", "// read directives", "var", "target", ",", "dsel", ";", "for", "(", "var", "sel", "in", "directive", ")", "{", "if", "(", "directive", ".", "hasOwnProperty", "(", "sel", ")", ")", "{", "dsel", "=", "directive", "[", "sel", "]", ";", "if", "(", "typeof", "(", "dsel", ")", "===", "'function'", "||", "typeof", "(", "dsel", ")", "===", "'string'", ")", "{", "// set the value for the node/attr", "target", "=", "gettarget", "(", "dom", ",", "sel", ",", "false", ")", ";", "setsig", "(", "target", ",", "fns", ".", "length", ")", ";", "fns", "[", "fns", ".", "length", "]", "=", "wrapquote", "(", "target", ".", "quotefn", ",", "dataselectfn", "(", "dsel", ")", ")", ";", "}", "else", "{", "// loop on node", "loopgen", "(", "dom", ",", "sel", ",", "dsel", ",", "fns", ")", ";", "}", "}", "}", "// convert node to a string", "var", "h", "=", "outerHTML", "(", "dom", ")", ",", "pfns", "=", "[", "]", ";", "// IE adds an unremovable \"selected, value\" attribute", "// hard replace while waiting for a better solution", "h", "=", "h", ".", "replace", "(", "/", "<([^>]+)\\s(value\\=\"\"|selected)\\s?([^>]*)>", "/", "ig", ",", "\"<$1 $3>\"", ")", ";", "// remove attribute prefix", "h", "=", "h", ".", "split", "(", "attPfx", ")", ".", "join", "(", "''", ")", ";", "// slice the html string at \"Sig\"", "var", "parts", "=", "h", ".", "split", "(", "Sig", ")", ",", "p", ";", "// for each slice add the return string of", "for", "(", "var", "i", "=", "1", ";", "i", "<", "parts", ".", "length", ";", "i", "++", ")", "{", "p", "=", "parts", "[", "i", "]", ";", "// part is of the form \"fn-number:...\" as placed there by setsig.", "pfns", "[", "i", "]", "=", "fns", "[", "parseInt", "(", "p", ",", "10", ")", "]", ";", "parts", "[", "i", "]", "=", "p", ".", "substring", "(", "p", ".", "indexOf", "(", "':'", ")", "+", "1", ")", ";", "}", "return", "concatenator", "(", "parts", ",", "pfns", ")", ";", "}" ]
returns a function that, given a context argument, will render the template defined by dom and directive.
[ "returns", "a", "function", "that", "given", "a", "context", "argument", "will", "render", "the", "template", "defined", "by", "dom", "and", "directive", "." ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.pure.js#L510-L576
26,834
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.pure.js
compile
function compile(directive, ctxt, template){ var rfn = compiler( ( template || this[0] ).cloneNode(true), directive, ctxt); return function(context){ return rfn({context:context}); }; }
javascript
function compile(directive, ctxt, template){ var rfn = compiler( ( template || this[0] ).cloneNode(true), directive, ctxt); return function(context){ return rfn({context:context}); }; }
[ "function", "compile", "(", "directive", ",", "ctxt", ",", "template", ")", "{", "var", "rfn", "=", "compiler", "(", "(", "template", "||", "this", "[", "0", "]", ")", ".", "cloneNode", "(", "true", ")", ",", "directive", ",", "ctxt", ")", ";", "return", "function", "(", "context", ")", "{", "return", "rfn", "(", "{", "context", ":", "context", "}", ")", ";", "}", ";", "}" ]
compile the template with directive if a context is passed, the autoRendering is triggered automatically return a function waiting the data as argument
[ "compile", "the", "template", "with", "directive", "if", "a", "context", "is", "passed", "the", "autoRendering", "is", "triggered", "automatically", "return", "a", "function", "waiting", "the", "data", "as", "argument" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.pure.js#L580-L585
26,835
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.pure.js
render
function render(ctxt, directive){ var fn = typeof directive === 'function' ? directive : plugins.compile( directive, false, this[0] ); for(var i = 0, ii = this.length; i < ii; i++){ this[i] = replaceWith( this[i], fn( ctxt, false )); } context = null; return this; }
javascript
function render(ctxt, directive){ var fn = typeof directive === 'function' ? directive : plugins.compile( directive, false, this[0] ); for(var i = 0, ii = this.length; i < ii; i++){ this[i] = replaceWith( this[i], fn( ctxt, false )); } context = null; return this; }
[ "function", "render", "(", "ctxt", ",", "directive", ")", "{", "var", "fn", "=", "typeof", "directive", "===", "'function'", "?", "directive", ":", "plugins", ".", "compile", "(", "directive", ",", "false", ",", "this", "[", "0", "]", ")", ";", "for", "(", "var", "i", "=", "0", ",", "ii", "=", "this", ".", "length", ";", "i", "<", "ii", ";", "i", "++", ")", "{", "this", "[", "i", "]", "=", "replaceWith", "(", "this", "[", "i", "]", ",", "fn", "(", "ctxt", ",", "false", ")", ")", ";", "}", "context", "=", "null", ";", "return", "this", ";", "}" ]
compile with the directive as argument run the template function on the context argument return an HTML string should replace the template and return this
[ "compile", "with", "the", "directive", "as", "argument", "run", "the", "template", "function", "on", "the", "context", "argument", "return", "an", "HTML", "string", "should", "replace", "the", "template", "and", "return", "this" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.pure.js#L590-L597
26,836
adrianlee44/ical2json
index.js
convert
function convert(source) { let currentKey = "", currentValue = "", objectNames = [], output = {}, parentObj = {}, lines = source.split(NEW_LINE), splitAt; let currentObj = output; let parents = []; for (let i = 0; i < lines.length; i++) { let line = lines[i]; if (line.charAt(0) === " ") { currentObj[currentKey] += line.substr(1); } else { splitAt = line.indexOf(":"); if (splitAt < 0) { continue; } currentKey = line.substr(0, splitAt); currentValue = line.substr(splitAt + 1); switch (currentKey) { case "BEGIN": parents.push(parentObj); parentObj = currentObj; if (parentObj[currentValue] == null) { parentObj[currentValue] = []; } // Create a new object, store the reference for future uses currentObj = {}; parentObj[currentValue].push(currentObj); break; case "END": currentObj = parentObj; parentObj = parents.pop(); break; default: if(currentObj[currentKey]) { if(!Array.isArray(currentObj[currentKey])) { currentObj[currentKey] = [currentObj[currentKey]]; } currentObj[currentKey].push(currentValue); } else { currentObj[currentKey] = currentValue; } } } } return output; }
javascript
function convert(source) { let currentKey = "", currentValue = "", objectNames = [], output = {}, parentObj = {}, lines = source.split(NEW_LINE), splitAt; let currentObj = output; let parents = []; for (let i = 0; i < lines.length; i++) { let line = lines[i]; if (line.charAt(0) === " ") { currentObj[currentKey] += line.substr(1); } else { splitAt = line.indexOf(":"); if (splitAt < 0) { continue; } currentKey = line.substr(0, splitAt); currentValue = line.substr(splitAt + 1); switch (currentKey) { case "BEGIN": parents.push(parentObj); parentObj = currentObj; if (parentObj[currentValue] == null) { parentObj[currentValue] = []; } // Create a new object, store the reference for future uses currentObj = {}; parentObj[currentValue].push(currentObj); break; case "END": currentObj = parentObj; parentObj = parents.pop(); break; default: if(currentObj[currentKey]) { if(!Array.isArray(currentObj[currentKey])) { currentObj[currentKey] = [currentObj[currentKey]]; } currentObj[currentKey].push(currentValue); } else { currentObj[currentKey] = currentValue; } } } } return output; }
[ "function", "convert", "(", "source", ")", "{", "let", "currentKey", "=", "\"\"", ",", "currentValue", "=", "\"\"", ",", "objectNames", "=", "[", "]", ",", "output", "=", "{", "}", ",", "parentObj", "=", "{", "}", ",", "lines", "=", "source", ".", "split", "(", "NEW_LINE", ")", ",", "splitAt", ";", "let", "currentObj", "=", "output", ";", "let", "parents", "=", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "lines", ".", "length", ";", "i", "++", ")", "{", "let", "line", "=", "lines", "[", "i", "]", ";", "if", "(", "line", ".", "charAt", "(", "0", ")", "===", "\" \"", ")", "{", "currentObj", "[", "currentKey", "]", "+=", "line", ".", "substr", "(", "1", ")", ";", "}", "else", "{", "splitAt", "=", "line", ".", "indexOf", "(", "\":\"", ")", ";", "if", "(", "splitAt", "<", "0", ")", "{", "continue", ";", "}", "currentKey", "=", "line", ".", "substr", "(", "0", ",", "splitAt", ")", ";", "currentValue", "=", "line", ".", "substr", "(", "splitAt", "+", "1", ")", ";", "switch", "(", "currentKey", ")", "{", "case", "\"BEGIN\"", ":", "parents", ".", "push", "(", "parentObj", ")", ";", "parentObj", "=", "currentObj", ";", "if", "(", "parentObj", "[", "currentValue", "]", "==", "null", ")", "{", "parentObj", "[", "currentValue", "]", "=", "[", "]", ";", "}", "// Create a new object, store the reference for future uses", "currentObj", "=", "{", "}", ";", "parentObj", "[", "currentValue", "]", ".", "push", "(", "currentObj", ")", ";", "break", ";", "case", "\"END\"", ":", "currentObj", "=", "parentObj", ";", "parentObj", "=", "parents", ".", "pop", "(", ")", ";", "break", ";", "default", ":", "if", "(", "currentObj", "[", "currentKey", "]", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "currentObj", "[", "currentKey", "]", ")", ")", "{", "currentObj", "[", "currentKey", "]", "=", "[", "currentObj", "[", "currentKey", "]", "]", ";", "}", "currentObj", "[", "currentKey", "]", ".", "push", "(", "currentValue", ")", ";", "}", "else", "{", "currentObj", "[", "currentKey", "]", "=", "currentValue", ";", "}", "}", "}", "}", "return", "output", ";", "}" ]
Take ical string data and convert to JSON @param {string} source @returns {Object}
[ "Take", "ical", "string", "data", "and", "convert", "to", "JSON" ]
4f1e00f896d68fa7ed6365f12788d6603377cffc
https://github.com/adrianlee44/ical2json/blob/4f1e00f896d68fa7ed6365f12788d6603377cffc/index.js#L17-L72
26,837
adrianlee44/ical2json
index.js
revert
function revert(object) { let lines = []; for (let key in object) { let value = object[key]; if (Array.isArray(value)) { value.forEach((item) => { lines.push(`BEGIN:${key}`); lines.push(revert(item)); lines.push(`END:${key}`); }); } else { let fullLine = `${key}:${value}`; do { // According to ical spec, lines of text should be no longer // than 75 octets lines.push(fullLine.substr(0, 75)); fullLine = ' ' + fullLine.substr(75); } while (fullLine.length > 1); } } return lines.join('\n'); }
javascript
function revert(object) { let lines = []; for (let key in object) { let value = object[key]; if (Array.isArray(value)) { value.forEach((item) => { lines.push(`BEGIN:${key}`); lines.push(revert(item)); lines.push(`END:${key}`); }); } else { let fullLine = `${key}:${value}`; do { // According to ical spec, lines of text should be no longer // than 75 octets lines.push(fullLine.substr(0, 75)); fullLine = ' ' + fullLine.substr(75); } while (fullLine.length > 1); } } return lines.join('\n'); }
[ "function", "revert", "(", "object", ")", "{", "let", "lines", "=", "[", "]", ";", "for", "(", "let", "key", "in", "object", ")", "{", "let", "value", "=", "object", "[", "key", "]", ";", "if", "(", "Array", ".", "isArray", "(", "value", ")", ")", "{", "value", ".", "forEach", "(", "(", "item", ")", "=>", "{", "lines", ".", "push", "(", "`", "${", "key", "}", "`", ")", ";", "lines", ".", "push", "(", "revert", "(", "item", ")", ")", ";", "lines", ".", "push", "(", "`", "${", "key", "}", "`", ")", ";", "}", ")", ";", "}", "else", "{", "let", "fullLine", "=", "`", "${", "key", "}", "${", "value", "}", "`", ";", "do", "{", "// According to ical spec, lines of text should be no longer", "// than 75 octets", "lines", ".", "push", "(", "fullLine", ".", "substr", "(", "0", ",", "75", ")", ")", ";", "fullLine", "=", "' '", "+", "fullLine", ".", "substr", "(", "75", ")", ";", "}", "while", "(", "fullLine", ".", "length", ">", "1", ")", ";", "}", "}", "return", "lines", ".", "join", "(", "'\\n'", ")", ";", "}" ]
Take JSON, revert back to ical @param {Object} object @return {String}
[ "Take", "JSON", "revert", "back", "to", "ical" ]
4f1e00f896d68fa7ed6365f12788d6603377cffc
https://github.com/adrianlee44/ical2json/blob/4f1e00f896d68fa7ed6365f12788d6603377cffc/index.js#L79-L102
26,838
adrianlee44/ical2json
index.js
run
function run(options) { let files, filePromises = []; files = options.args || []; for (let i = 0; i < files.length; i++) { let file = files[i]; let filePath = path.resolve(cwd, file); if (!fs.existsSync(filePath)) { continue; } let stat = fs.statSync(filePath); let ext = path.extname(filePath); let isConvert = !options.revert && ext === '.ics' let isRevert = options.revert && ext === '.json' if (!stat.isFile() || (!isConvert && !isRevert)) { continue; } filePromises.push(Q.nfcall(fs.readFile, filePath) .then((buffer) => { let output; let data = buffer.toString(); if (isConvert) { output = convert(data); output = JSON.stringify(output, null, " "); } else if (isRevert) { output = revert(data); } let basename = path.basename(filePath, ext); let dirname = path.dirname(filePath); let compiledExt = isConvert ? '.json' : '.ics'; let writePath = path.join(dirname, basename) + compiledExt; return Q.nfcall(fs.writeFile, writePath, output); }) .fail((error) => { throw new Error(error); })); } return Q.all(filePromises); }
javascript
function run(options) { let files, filePromises = []; files = options.args || []; for (let i = 0; i < files.length; i++) { let file = files[i]; let filePath = path.resolve(cwd, file); if (!fs.existsSync(filePath)) { continue; } let stat = fs.statSync(filePath); let ext = path.extname(filePath); let isConvert = !options.revert && ext === '.ics' let isRevert = options.revert && ext === '.json' if (!stat.isFile() || (!isConvert && !isRevert)) { continue; } filePromises.push(Q.nfcall(fs.readFile, filePath) .then((buffer) => { let output; let data = buffer.toString(); if (isConvert) { output = convert(data); output = JSON.stringify(output, null, " "); } else if (isRevert) { output = revert(data); } let basename = path.basename(filePath, ext); let dirname = path.dirname(filePath); let compiledExt = isConvert ? '.json' : '.ics'; let writePath = path.join(dirname, basename) + compiledExt; return Q.nfcall(fs.writeFile, writePath, output); }) .fail((error) => { throw new Error(error); })); } return Q.all(filePromises); }
[ "function", "run", "(", "options", ")", "{", "let", "files", ",", "filePromises", "=", "[", "]", ";", "files", "=", "options", ".", "args", "||", "[", "]", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "files", ".", "length", ";", "i", "++", ")", "{", "let", "file", "=", "files", "[", "i", "]", ";", "let", "filePath", "=", "path", ".", "resolve", "(", "cwd", ",", "file", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "filePath", ")", ")", "{", "continue", ";", "}", "let", "stat", "=", "fs", ".", "statSync", "(", "filePath", ")", ";", "let", "ext", "=", "path", ".", "extname", "(", "filePath", ")", ";", "let", "isConvert", "=", "!", "options", ".", "revert", "&&", "ext", "===", "'.ics'", "let", "isRevert", "=", "options", ".", "revert", "&&", "ext", "===", "'.json'", "if", "(", "!", "stat", ".", "isFile", "(", ")", "||", "(", "!", "isConvert", "&&", "!", "isRevert", ")", ")", "{", "continue", ";", "}", "filePromises", ".", "push", "(", "Q", ".", "nfcall", "(", "fs", ".", "readFile", ",", "filePath", ")", ".", "then", "(", "(", "buffer", ")", "=>", "{", "let", "output", ";", "let", "data", "=", "buffer", ".", "toString", "(", ")", ";", "if", "(", "isConvert", ")", "{", "output", "=", "convert", "(", "data", ")", ";", "output", "=", "JSON", ".", "stringify", "(", "output", ",", "null", ",", "\" \"", ")", ";", "}", "else", "if", "(", "isRevert", ")", "{", "output", "=", "revert", "(", "data", ")", ";", "}", "let", "basename", "=", "path", ".", "basename", "(", "filePath", ",", "ext", ")", ";", "let", "dirname", "=", "path", ".", "dirname", "(", "filePath", ")", ";", "let", "compiledExt", "=", "isConvert", "?", "'.json'", ":", "'.ics'", ";", "let", "writePath", "=", "path", ".", "join", "(", "dirname", ",", "basename", ")", "+", "compiledExt", ";", "return", "Q", ".", "nfcall", "(", "fs", ".", "writeFile", ",", "writePath", ",", "output", ")", ";", "}", ")", ".", "fail", "(", "(", "error", ")", "=>", "{", "throw", "new", "Error", "(", "error", ")", ";", "}", ")", ")", ";", "}", "return", "Q", ".", "all", "(", "filePromises", ")", ";", "}" ]
Pass in options to parse and generate JSON files @param {Object} options @return {Promise}
[ "Pass", "in", "options", "to", "parse", "and", "generate", "JSON", "files" ]
4f1e00f896d68fa7ed6365f12788d6603377cffc
https://github.com/adrianlee44/ical2json/blob/4f1e00f896d68fa7ed6365f12788d6603377cffc/index.js#L109-L156
26,839
rappid/rAppid.js
js/data/Entity.js
function () { if (this.factory.schema) { this.schema = this.factory.schema; return; } var base = this.base; while (base.factory.classof(Entity)) { var baseSchema = base.schema; for (var type in baseSchema) { if (baseSchema.hasOwnProperty(type) && !this.schema.hasOwnProperty(type)) { this.schema[type] = baseSchema[type]; } } base = base.base; } var schemaDefaults = { required: true, includeInIndex: false, serverOnly: false, _rewritten: true, // if true, sub models get composed and not just linked compose: false }, schemaObject; // add id schema if (this.idField && !this.schema.hasOwnProperty(this.idField)) { this.schema[this.idField] = { type: String, required: false, serverOnly: false, includeInIndex: true, generated: true }; } if (this.updatedField && !this.schema.hasOwnProperty(this.updatedField)) { this.schema[this.updatedField] = { type: Date, required: false, serverOnly: false, includeInIndex: true, generated: true }; } if (this.createdField && !this.schema.hasOwnProperty(this.createdField)) { this.schema[this.createdField] = { type: Date, required: false, includeInIndex: true, serverOnly: false, generated: true }; } // rewrite schema for (var key in this.schema) { if (this.schema.hasOwnProperty(key)) { schemaObject = this.schema[key]; if (_.isString(schemaObject) || schemaObject instanceof Array || schemaObject instanceof Function) { schemaObject = { type: schemaObject }; this.schema[key] = schemaObject; } if (_.isString(schemaObject.type)) { schemaObject.type = require(schemaObject.type.replace(/\./g, "/")); } _.defaults(schemaObject, schemaDefaults); schemaObject._key = key; } } this.factory.schema = this.schema; }
javascript
function () { if (this.factory.schema) { this.schema = this.factory.schema; return; } var base = this.base; while (base.factory.classof(Entity)) { var baseSchema = base.schema; for (var type in baseSchema) { if (baseSchema.hasOwnProperty(type) && !this.schema.hasOwnProperty(type)) { this.schema[type] = baseSchema[type]; } } base = base.base; } var schemaDefaults = { required: true, includeInIndex: false, serverOnly: false, _rewritten: true, // if true, sub models get composed and not just linked compose: false }, schemaObject; // add id schema if (this.idField && !this.schema.hasOwnProperty(this.idField)) { this.schema[this.idField] = { type: String, required: false, serverOnly: false, includeInIndex: true, generated: true }; } if (this.updatedField && !this.schema.hasOwnProperty(this.updatedField)) { this.schema[this.updatedField] = { type: Date, required: false, serverOnly: false, includeInIndex: true, generated: true }; } if (this.createdField && !this.schema.hasOwnProperty(this.createdField)) { this.schema[this.createdField] = { type: Date, required: false, includeInIndex: true, serverOnly: false, generated: true }; } // rewrite schema for (var key in this.schema) { if (this.schema.hasOwnProperty(key)) { schemaObject = this.schema[key]; if (_.isString(schemaObject) || schemaObject instanceof Array || schemaObject instanceof Function) { schemaObject = { type: schemaObject }; this.schema[key] = schemaObject; } if (_.isString(schemaObject.type)) { schemaObject.type = require(schemaObject.type.replace(/\./g, "/")); } _.defaults(schemaObject, schemaDefaults); schemaObject._key = key; } } this.factory.schema = this.schema; }
[ "function", "(", ")", "{", "if", "(", "this", ".", "factory", ".", "schema", ")", "{", "this", ".", "schema", "=", "this", ".", "factory", ".", "schema", ";", "return", ";", "}", "var", "base", "=", "this", ".", "base", ";", "while", "(", "base", ".", "factory", ".", "classof", "(", "Entity", ")", ")", "{", "var", "baseSchema", "=", "base", ".", "schema", ";", "for", "(", "var", "type", "in", "baseSchema", ")", "{", "if", "(", "baseSchema", ".", "hasOwnProperty", "(", "type", ")", "&&", "!", "this", ".", "schema", ".", "hasOwnProperty", "(", "type", ")", ")", "{", "this", ".", "schema", "[", "type", "]", "=", "baseSchema", "[", "type", "]", ";", "}", "}", "base", "=", "base", ".", "base", ";", "}", "var", "schemaDefaults", "=", "{", "required", ":", "true", ",", "includeInIndex", ":", "false", ",", "serverOnly", ":", "false", ",", "_rewritten", ":", "true", ",", "// if true, sub models get composed and not just linked", "compose", ":", "false", "}", ",", "schemaObject", ";", "// add id schema", "if", "(", "this", ".", "idField", "&&", "!", "this", ".", "schema", ".", "hasOwnProperty", "(", "this", ".", "idField", ")", ")", "{", "this", ".", "schema", "[", "this", ".", "idField", "]", "=", "{", "type", ":", "String", ",", "required", ":", "false", ",", "serverOnly", ":", "false", ",", "includeInIndex", ":", "true", ",", "generated", ":", "true", "}", ";", "}", "if", "(", "this", ".", "updatedField", "&&", "!", "this", ".", "schema", ".", "hasOwnProperty", "(", "this", ".", "updatedField", ")", ")", "{", "this", ".", "schema", "[", "this", ".", "updatedField", "]", "=", "{", "type", ":", "Date", ",", "required", ":", "false", ",", "serverOnly", ":", "false", ",", "includeInIndex", ":", "true", ",", "generated", ":", "true", "}", ";", "}", "if", "(", "this", ".", "createdField", "&&", "!", "this", ".", "schema", ".", "hasOwnProperty", "(", "this", ".", "createdField", ")", ")", "{", "this", ".", "schema", "[", "this", ".", "createdField", "]", "=", "{", "type", ":", "Date", ",", "required", ":", "false", ",", "includeInIndex", ":", "true", ",", "serverOnly", ":", "false", ",", "generated", ":", "true", "}", ";", "}", "// rewrite schema", "for", "(", "var", "key", "in", "this", ".", "schema", ")", "{", "if", "(", "this", ".", "schema", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "schemaObject", "=", "this", ".", "schema", "[", "key", "]", ";", "if", "(", "_", ".", "isString", "(", "schemaObject", ")", "||", "schemaObject", "instanceof", "Array", "||", "schemaObject", "instanceof", "Function", ")", "{", "schemaObject", "=", "{", "type", ":", "schemaObject", "}", ";", "this", ".", "schema", "[", "key", "]", "=", "schemaObject", ";", "}", "if", "(", "_", ".", "isString", "(", "schemaObject", ".", "type", ")", ")", "{", "schemaObject", ".", "type", "=", "require", "(", "schemaObject", ".", "type", ".", "replace", "(", "/", "\\.", "/", "g", ",", "\"/\"", ")", ")", ";", "}", "_", ".", "defaults", "(", "schemaObject", ",", "schemaDefaults", ")", ";", "schemaObject", ".", "_key", "=", "key", ";", "}", "}", "this", ".", "factory", ".", "schema", "=", "this", ".", "schema", ";", "}" ]
Constructs the schema with the schema definition @private
[ "Constructs", "the", "schema", "with", "the", "schema", "definition" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/data/Entity.js#L278-L354
26,840
rappid/rAppid.js
js/data/Entity.js
function (key, scope) { var value = this.get(key, scope); if (key && this.schema[key]) { for (var i = 0; i < this.transformers.length; i++) { value = this.transformers[i].transformValue(key, value, this.schema[key]); } } return value; }
javascript
function (key, scope) { var value = this.get(key, scope); if (key && this.schema[key]) { for (var i = 0; i < this.transformers.length; i++) { value = this.transformers[i].transformValue(key, value, this.schema[key]); } } return value; }
[ "function", "(", "key", ",", "scope", ")", "{", "var", "value", "=", "this", ".", "get", "(", "key", ",", "scope", ")", ";", "if", "(", "key", "&&", "this", ".", "schema", "[", "key", "]", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "transformers", ".", "length", ";", "i", "++", ")", "{", "value", "=", "this", ".", "transformers", "[", "i", "]", ".", "transformValue", "(", "key", ",", "value", ",", "this", ".", "schema", "[", "key", "]", ")", ";", "}", "}", "return", "value", ";", "}" ]
Returns the transformed value of a field @param {String} key @param {Object|js.core.Bindable} [scope] @returns {*}
[ "Returns", "the", "transformed", "value", "of", "a", "field" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/data/Entity.js#L390-L398
26,841
rappid/rAppid.js
js/data/Entity.js
function (options) { var ret = {}; for (var k in this.schema) { if (this.schema.hasOwnProperty(k)) { ret[k] = this.getTransformedValue(k); } } this.set(ret, options); }
javascript
function (options) { var ret = {}; for (var k in this.schema) { if (this.schema.hasOwnProperty(k)) { ret[k] = this.getTransformedValue(k); } } this.set(ret, options); }
[ "function", "(", "options", ")", "{", "var", "ret", "=", "{", "}", ";", "for", "(", "var", "k", "in", "this", ".", "schema", ")", "{", "if", "(", "this", ".", "schema", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "ret", "[", "k", "]", "=", "this", ".", "getTransformedValue", "(", "k", ")", ";", "}", "}", "this", ".", "set", "(", "ret", ",", "options", ")", ";", "}" ]
Transforms all values defined in the schema @param {Object} [options]
[ "Transforms", "all", "values", "defined", "in", "the", "schema" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/data/Entity.js#L414-L423
26,842
rappid/rAppid.js
js/data/Entity.js
function (entity, options, callback) { if (entity instanceof Entity) { entity.validate(options, callback); } else { callback("parameter is not an entity"); } }
javascript
function (entity, options, callback) { if (entity instanceof Entity) { entity.validate(options, callback); } else { callback("parameter is not an entity"); } }
[ "function", "(", "entity", ",", "options", ",", "callback", ")", "{", "if", "(", "entity", "instanceof", "Entity", ")", "{", "entity", ".", "validate", "(", "options", ",", "callback", ")", ";", "}", "else", "{", "callback", "(", "\"parameter is not an entity\"", ")", ";", "}", "}" ]
Validates a sub entity @param {js.data.Entity} entity @param {Object} options @param {Function} callback
[ "Validates", "a", "sub", "entity" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/data/Entity.js#L648-L654
26,843
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.form.js
function(keypath, content, attributes) { var attrs = {'for': this._attributesForKeyPath(keypath).name}; return simple_element('label', $.extend(attrs, attributes), content); }
javascript
function(keypath, content, attributes) { var attrs = {'for': this._attributesForKeyPath(keypath).name}; return simple_element('label', $.extend(attrs, attributes), content); }
[ "function", "(", "keypath", ",", "content", ",", "attributes", ")", "{", "var", "attrs", "=", "{", "'for'", ":", "this", ".", "_attributesForKeyPath", "(", "keypath", ")", ".", "name", "}", ";", "return", "simple_element", "(", "'label'", ",", "$", ".", "extend", "(", "attrs", ",", "attributes", ")", ",", "content", ")", ";", "}" ]
creates a label for `keypath` with the text `content with an optional `attributes` object
[ "creates", "a", "label", "for", "keypath", "with", "the", "text", "content", "with", "an", "optional", "attributes", "object" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.form.js#L87-L90
26,844
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.form.js
function(keypath, attributes) { attributes = $.extend({type: 'hidden'}, this._attributesForKeyPath(keypath), attributes); return simple_element('input', attributes); }
javascript
function(keypath, attributes) { attributes = $.extend({type: 'hidden'}, this._attributesForKeyPath(keypath), attributes); return simple_element('input', attributes); }
[ "function", "(", "keypath", ",", "attributes", ")", "{", "attributes", "=", "$", ".", "extend", "(", "{", "type", ":", "'hidden'", "}", ",", "this", ".", "_attributesForKeyPath", "(", "keypath", ")", ",", "attributes", ")", ";", "return", "simple_element", "(", "'input'", ",", "attributes", ")", ";", "}" ]
creates a hidden input for `keypath` with an optional `attributes` object
[ "creates", "a", "hidden", "input", "for", "keypath", "with", "an", "optional", "attributes", "object" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.form.js#L93-L96
26,845
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.form.js
function(keypath, attributes) { var current; attributes = $.extend(this._attributesForKeyPath(keypath), attributes); current = attributes.value; delete attributes['value']; return simple_element('textarea', attributes, current); }
javascript
function(keypath, attributes) { var current; attributes = $.extend(this._attributesForKeyPath(keypath), attributes); current = attributes.value; delete attributes['value']; return simple_element('textarea', attributes, current); }
[ "function", "(", "keypath", ",", "attributes", ")", "{", "var", "current", ";", "attributes", "=", "$", ".", "extend", "(", "this", ".", "_attributesForKeyPath", "(", "keypath", ")", ",", "attributes", ")", ";", "current", "=", "attributes", ".", "value", ";", "delete", "attributes", "[", "'value'", "]", ";", "return", "simple_element", "(", "'textarea'", ",", "attributes", ",", "current", ")", ";", "}" ]
creates a textarea for `keypath` with an optional `attributes` object
[ "creates", "a", "textarea", "for", "keypath", "with", "an", "optional", "attributes", "object" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.form.js#L105-L111
26,846
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.form.js
function(keypath, value, attributes) { var selected; attributes = $.extend(this._attributesForKeyPath(keypath), attributes); selected = attributes.value; attributes.value = getStringContent(this.object, value); if (selected == attributes.value) { attributes.checked = 'checked'; } return simple_element('input', $.extend({type:'radio'}, attributes)); }
javascript
function(keypath, value, attributes) { var selected; attributes = $.extend(this._attributesForKeyPath(keypath), attributes); selected = attributes.value; attributes.value = getStringContent(this.object, value); if (selected == attributes.value) { attributes.checked = 'checked'; } return simple_element('input', $.extend({type:'radio'}, attributes)); }
[ "function", "(", "keypath", ",", "value", ",", "attributes", ")", "{", "var", "selected", ";", "attributes", "=", "$", ".", "extend", "(", "this", ".", "_attributesForKeyPath", "(", "keypath", ")", ",", "attributes", ")", ";", "selected", "=", "attributes", ".", "value", ";", "attributes", ".", "value", "=", "getStringContent", "(", "this", ".", "object", ",", "value", ")", ";", "if", "(", "selected", "==", "attributes", ".", "value", ")", "{", "attributes", ".", "checked", "=", "'checked'", ";", "}", "return", "simple_element", "(", "'input'", ",", "$", ".", "extend", "(", "{", "type", ":", "'radio'", "}", ",", "attributes", ")", ")", ";", "}" ]
creates a radio input for keypath with the value `value`. Multiple radios can be created with different value, if `value` equals the current value of the key of the form builder's object the attribute checked='checked' will be added.
[ "creates", "a", "radio", "input", "for", "keypath", "with", "the", "value", "value", ".", "Multiple", "radios", "can", "be", "created", "with", "different", "value", "if", "value", "equals", "the", "current", "value", "of", "the", "key", "of", "the", "form", "builder", "s", "object", "the", "attribute", "checked", "=", "checked", "will", "be", "added", "." ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.form.js#L158-L167
26,847
rappid/rAppid.js
js/core/List.js
function (items, options) { options = options || {}; _.defaults(options, {silent: false, index: this.$items.length}); var index = options.index; if (!_.isArray(items)) { items = [items]; } var item, itemIndex; for (var i = 0; i < items.length; i++) { item = items[i]; if (item instanceof Bindable) { item.bind('change', this._onItemChange, this); item.bind('*', this._onItemEvent, this); } itemIndex = index + i; if (_.isUndefined(this.$items[itemIndex]) || itemIndex >= this.$items.length) { this.$items[itemIndex] = item; } else { this.$items.splice(itemIndex, 0, item); } if (options.silent !== true) { this.trigger('add', {item: item, index: itemIndex}); } } }
javascript
function (items, options) { options = options || {}; _.defaults(options, {silent: false, index: this.$items.length}); var index = options.index; if (!_.isArray(items)) { items = [items]; } var item, itemIndex; for (var i = 0; i < items.length; i++) { item = items[i]; if (item instanceof Bindable) { item.bind('change', this._onItemChange, this); item.bind('*', this._onItemEvent, this); } itemIndex = index + i; if (_.isUndefined(this.$items[itemIndex]) || itemIndex >= this.$items.length) { this.$items[itemIndex] = item; } else { this.$items.splice(itemIndex, 0, item); } if (options.silent !== true) { this.trigger('add', {item: item, index: itemIndex}); } } }
[ "function", "(", "items", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "_", ".", "defaults", "(", "options", ",", "{", "silent", ":", "false", ",", "index", ":", "this", ".", "$items", ".", "length", "}", ")", ";", "var", "index", "=", "options", ".", "index", ";", "if", "(", "!", "_", ".", "isArray", "(", "items", ")", ")", "{", "items", "=", "[", "items", "]", ";", "}", "var", "item", ",", "itemIndex", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "++", ")", "{", "item", "=", "items", "[", "i", "]", ";", "if", "(", "item", "instanceof", "Bindable", ")", "{", "item", ".", "bind", "(", "'change'", ",", "this", ".", "_onItemChange", ",", "this", ")", ";", "item", ".", "bind", "(", "'*'", ",", "this", ".", "_onItemEvent", ",", "this", ")", ";", "}", "itemIndex", "=", "index", "+", "i", ";", "if", "(", "_", ".", "isUndefined", "(", "this", ".", "$items", "[", "itemIndex", "]", ")", "||", "itemIndex", ">=", "this", ".", "$items", ".", "length", ")", "{", "this", ".", "$items", "[", "itemIndex", "]", "=", "item", ";", "}", "else", "{", "this", ".", "$items", ".", "splice", "(", "itemIndex", ",", "0", ",", "item", ")", ";", "}", "if", "(", "options", ".", "silent", "!==", "true", ")", "{", "this", ".", "trigger", "(", "'add'", ",", "{", "item", ":", "item", ",", "index", ":", "itemIndex", "}", ")", ";", "}", "}", "}" ]
This method adds one ore items to the array. @param {Array|Object} items @param {Object} options
[ "This", "method", "adds", "one", "ore", "items", "to", "the", "array", "." ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/List.js#L77-L105
26,848
rappid/rAppid.js
js/core/List.js
function (items, options) { var removed = []; if (!_.isArray(items)) { items = [items]; } var item; for (var i = 0; i < items.length; i++) { item = this.removeAt(this.indexOf(items[i]), options); item && removed.push(item); } return removed; }
javascript
function (items, options) { var removed = []; if (!_.isArray(items)) { items = [items]; } var item; for (var i = 0; i < items.length; i++) { item = this.removeAt(this.indexOf(items[i]), options); item && removed.push(item); } return removed; }
[ "function", "(", "items", ",", "options", ")", "{", "var", "removed", "=", "[", "]", ";", "if", "(", "!", "_", ".", "isArray", "(", "items", ")", ")", "{", "items", "=", "[", "items", "]", ";", "}", "var", "item", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "items", ".", "length", ";", "i", "++", ")", "{", "item", "=", "this", ".", "removeAt", "(", "this", ".", "indexOf", "(", "items", "[", "i", "]", ")", ",", "options", ")", ";", "item", "&&", "removed", ".", "push", "(", "item", ")", ";", "}", "return", "removed", ";", "}" ]
Removes an Array or just one item from the list. Triggers remove events. @param {Object|Array} items @param {Object} options
[ "Removes", "an", "Array", "or", "just", "one", "item", "from", "the", "list", ".", "Triggers", "remove", "events", "." ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/List.js#L125-L137
26,849
rappid/rAppid.js
js/core/List.js
function (index, options) { options = options || {}; if (index > -1 && index < this.$items.length) { var items = this.$items.splice(index, 1), item = items[0]; if (options.silent !== true) { this.trigger('remove', {item: item, index: index}); } if (item instanceof Bindable) { item.unbind('*', this._onItemEvent, this); item.unbind('change', this._onItemChange, this); } return items[0]; } return null; }
javascript
function (index, options) { options = options || {}; if (index > -1 && index < this.$items.length) { var items = this.$items.splice(index, 1), item = items[0]; if (options.silent !== true) { this.trigger('remove', {item: item, index: index}); } if (item instanceof Bindable) { item.unbind('*', this._onItemEvent, this); item.unbind('change', this._onItemChange, this); } return items[0]; } return null; }
[ "function", "(", "index", ",", "options", ")", "{", "options", "=", "options", "||", "{", "}", ";", "if", "(", "index", ">", "-", "1", "&&", "index", "<", "this", ".", "$items", ".", "length", ")", "{", "var", "items", "=", "this", ".", "$items", ".", "splice", "(", "index", ",", "1", ")", ",", "item", "=", "items", "[", "0", "]", ";", "if", "(", "options", ".", "silent", "!==", "true", ")", "{", "this", ".", "trigger", "(", "'remove'", ",", "{", "item", ":", "item", ",", "index", ":", "index", "}", ")", ";", "}", "if", "(", "item", "instanceof", "Bindable", ")", "{", "item", ".", "unbind", "(", "'*'", ",", "this", ".", "_onItemEvent", ",", "this", ")", ";", "item", ".", "unbind", "(", "'change'", ",", "this", ".", "_onItemChange", ",", "this", ")", ";", "}", "return", "items", "[", "0", "]", ";", "}", "return", "null", ";", "}" ]
Removes one item a specific index and triggers remove event @param {Number} index @param {Object} options @return {Object} removed item
[ "Removes", "one", "item", "a", "specific", "index", "and", "triggers", "remove", "event" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/List.js#L152-L169
26,850
rappid/rAppid.js
js/core/List.js
function (items, options) { items = items || []; var self = this; this.each(function (item) { if (item instanceof EventDispatcher) { item.unbind('*', self._onItemEvent, self); item.unbind('change', self._onItemChange, self); } }); this.$items = items || []; this.each(function (item) { if (item instanceof EventDispatcher) { item.bind('*', self._onItemEvent, self); item.bind('change', self._onItemChange, self); } }); options = options || {}; if (!options.silent) { this.trigger('reset', {items: items}); } }
javascript
function (items, options) { items = items || []; var self = this; this.each(function (item) { if (item instanceof EventDispatcher) { item.unbind('*', self._onItemEvent, self); item.unbind('change', self._onItemChange, self); } }); this.$items = items || []; this.each(function (item) { if (item instanceof EventDispatcher) { item.bind('*', self._onItemEvent, self); item.bind('change', self._onItemChange, self); } }); options = options || {}; if (!options.silent) { this.trigger('reset', {items: items}); } }
[ "function", "(", "items", ",", "options", ")", "{", "items", "=", "items", "||", "[", "]", ";", "var", "self", "=", "this", ";", "this", ".", "each", "(", "function", "(", "item", ")", "{", "if", "(", "item", "instanceof", "EventDispatcher", ")", "{", "item", ".", "unbind", "(", "'*'", ",", "self", ".", "_onItemEvent", ",", "self", ")", ";", "item", ".", "unbind", "(", "'change'", ",", "self", ".", "_onItemChange", ",", "self", ")", ";", "}", "}", ")", ";", "this", ".", "$items", "=", "items", "||", "[", "]", ";", "this", ".", "each", "(", "function", "(", "item", ")", "{", "if", "(", "item", "instanceof", "EventDispatcher", ")", "{", "item", ".", "bind", "(", "'*'", ",", "self", ".", "_onItemEvent", ",", "self", ")", ";", "item", ".", "bind", "(", "'change'", ",", "self", ".", "_onItemChange", ",", "self", ")", ";", "}", "}", ")", ";", "options", "=", "options", "||", "{", "}", ";", "if", "(", "!", "options", ".", "silent", ")", "{", "this", ".", "trigger", "(", "'reset'", ",", "{", "items", ":", "items", "}", ")", ";", "}", "}" ]
Resets the list with the given items and triggers reset event @param {Array} items @param {Object} options
[ "Resets", "the", "list", "with", "the", "given", "items", "and", "triggers", "reset", "event" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/List.js#L175-L198
26,851
rappid/rAppid.js
js/core/List.js
function (fnc, scope) { scope = scope || this; for (var i = 0; i < this.$items.length; i++) { fnc.call(scope, this.$items[i], i, this.$items); } }
javascript
function (fnc, scope) { scope = scope || this; for (var i = 0; i < this.$items.length; i++) { fnc.call(scope, this.$items[i], i, this.$items); } }
[ "function", "(", "fnc", ",", "scope", ")", "{", "scope", "=", "scope", "||", "this", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "$items", ".", "length", ";", "i", "++", ")", "{", "fnc", ".", "call", "(", "scope", ",", "this", ".", "$items", "[", "i", "]", ",", "i", ",", "this", ".", "$items", ")", ";", "}", "}" ]
Iterates over all items with given callback @param {Function} fnc callback with signature function(item, index) @param {Object} scope The call scope of the callback
[ "Iterates", "over", "all", "items", "with", "given", "callback" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/List.js#L230-L236
26,852
rappid/rAppid.js
js/core/List.js
function (fnc, scope) { scope = scope || this; var b = false, items = this.$items, length = items.length; for (var i = 0; i < length; i++) { b = fnc.call(scope, items[i], i, this.$items); if (b === true) { break; } } return i < length ? items[i] : null; }
javascript
function (fnc, scope) { scope = scope || this; var b = false, items = this.$items, length = items.length; for (var i = 0; i < length; i++) { b = fnc.call(scope, items[i], i, this.$items); if (b === true) { break; } } return i < length ? items[i] : null; }
[ "function", "(", "fnc", ",", "scope", ")", "{", "scope", "=", "scope", "||", "this", ";", "var", "b", "=", "false", ",", "items", "=", "this", ".", "$items", ",", "length", "=", "items", ".", "length", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "b", "=", "fnc", ".", "call", "(", "scope", ",", "items", "[", "i", "]", ",", "i", ",", "this", ".", "$items", ")", ";", "if", "(", "b", "===", "true", ")", "{", "break", ";", "}", "}", "return", "i", "<", "length", "?", "items", "[", "i", "]", ":", "null", ";", "}" ]
Iterates over all items with the function. Returns the element when the function returns true. @param {Function} fnc Function to execute on each value in the list @param {Object} scope The this object @returns {*}
[ "Iterates", "over", "all", "items", "with", "the", "function", ".", "Returns", "the", "element", "when", "the", "function", "returns", "true", "." ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/List.js#L245-L259
26,853
rappid/rAppid.js
js/core/List.js
function () { var attributes = this._cloneAttribute(this.$); var items = this._cloneAttribute(this.$items); var ret = new this.factory(items, attributes); ret._$source = this; return ret; }
javascript
function () { var attributes = this._cloneAttribute(this.$); var items = this._cloneAttribute(this.$items); var ret = new this.factory(items, attributes); ret._$source = this; return ret; }
[ "function", "(", ")", "{", "var", "attributes", "=", "this", ".", "_cloneAttribute", "(", "this", ".", "$", ")", ";", "var", "items", "=", "this", ".", "_cloneAttribute", "(", "this", ".", "$items", ")", ";", "var", "ret", "=", "new", "this", ".", "factory", "(", "items", ",", "attributes", ")", ";", "ret", ".", "_$source", "=", "this", ";", "return", "ret", ";", "}" ]
Returns a fresh copy of the List @return {List} a fresh copy of the list
[ "Returns", "a", "fresh", "copy", "of", "the", "List" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/List.js#L277-L283
26,854
rappid/rAppid.js
js/core/List.js
function () { if (this._$source) { var item, items = []; for (var i = 0; i < this.$items.length; i++) { item = this.$items[i]; if (item instanceof Bindable && item.sync()) { item = item._$source; } items.push(item); } this._$source.reset(items); } return this.callBase(); }
javascript
function () { if (this._$source) { var item, items = []; for (var i = 0; i < this.$items.length; i++) { item = this.$items[i]; if (item instanceof Bindable && item.sync()) { item = item._$source; } items.push(item); } this._$source.reset(items); } return this.callBase(); }
[ "function", "(", ")", "{", "if", "(", "this", ".", "_$source", ")", "{", "var", "item", ",", "items", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "$items", ".", "length", ";", "i", "++", ")", "{", "item", "=", "this", ".", "$items", "[", "i", "]", ";", "if", "(", "item", "instanceof", "Bindable", "&&", "item", ".", "sync", "(", ")", ")", "{", "item", "=", "item", ".", "_$source", ";", "}", "items", ".", "push", "(", "item", ")", ";", "}", "this", ".", "_$source", ".", "reset", "(", "items", ")", ";", "}", "return", "this", ".", "callBase", "(", ")", ";", "}" ]
Syncs the items back to the source @return {*}
[ "Syncs", "the", "items", "back", "to", "the", "source" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/List.js#L288-L301
26,855
rappid/rAppid.js
js/core/List.js
function (list) { if (list.size() !== this.size()) { return false; } var isEqual = true, a, b; for (var i = 0; i < this.$items.length; i++) { a = this.$items[i]; b = list.at(i); if (a instanceof Bindable && b instanceof Bindable) { if (!a.isDeepEqual(b)) { return false; } } else if (a instanceof Bindable || b instanceof Bindable) { return false; } else { isEqual = _.isEqual(a, b); } } return isEqual; }
javascript
function (list) { if (list.size() !== this.size()) { return false; } var isEqual = true, a, b; for (var i = 0; i < this.$items.length; i++) { a = this.$items[i]; b = list.at(i); if (a instanceof Bindable && b instanceof Bindable) { if (!a.isDeepEqual(b)) { return false; } } else if (a instanceof Bindable || b instanceof Bindable) { return false; } else { isEqual = _.isEqual(a, b); } } return isEqual; }
[ "function", "(", "list", ")", "{", "if", "(", "list", ".", "size", "(", ")", "!==", "this", ".", "size", "(", ")", ")", "{", "return", "false", ";", "}", "var", "isEqual", "=", "true", ",", "a", ",", "b", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "$items", ".", "length", ";", "i", "++", ")", "{", "a", "=", "this", ".", "$items", "[", "i", "]", ";", "b", "=", "list", ".", "at", "(", "i", ")", ";", "if", "(", "a", "instanceof", "Bindable", "&&", "b", "instanceof", "Bindable", ")", "{", "if", "(", "!", "a", ".", "isDeepEqual", "(", "b", ")", ")", "{", "return", "false", ";", "}", "}", "else", "if", "(", "a", "instanceof", "Bindable", "||", "b", "instanceof", "Bindable", ")", "{", "return", "false", ";", "}", "else", "{", "isEqual", "=", "_", ".", "isEqual", "(", "a", ",", "b", ")", ";", "}", "}", "return", "isEqual", ";", "}" ]
Checks if items are deep equal @param {js.core.List} list @return {boolean}
[ "Checks", "if", "items", "are", "deep", "equal" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/List.js#L375-L396
26,856
rappid/rAppid.js
js/core/ModuleLoader.js
function (moduleName, moduleInstance, callback, routeContext, cachedInstance) { var self = this; //noinspection JSValidateTypes flow() .seq(function (cb) { self.$moduleInstance = moduleInstance; var currentModule = self.$.currentModule; if (currentModule) { currentModule._unload(cb); } else { cb(); } }) .seq(function (cb) { // start module moduleInstance.start(function (err) { if (err || cachedInstance) { cb(err); } else { if (routeContext) { // fresh instance with maybe new routers -> exec routes for new router var routeExecutionStack = []; for (var i = 0; i < moduleInstance.$routers.length; i++) { var router = moduleInstance.$routers[i]; router.set("module", moduleInstance); routeExecutionStack = routeExecutionStack.concat(router.generateRoutingStack(routeContext.fragment)); } flow() .seqEach(routeExecutionStack, function (routingFunction, cb) { routingFunction(cb); }) .exec(cb); } else { cb(); } } }, routeContext); }) .seq(function () { if (moduleInstance === self.$moduleInstance) { self._clearContentPlaceHolders(); self.set('currentModuleName', moduleName); var contentPlaceHolders = self.getContentPlaceHolders("external"); // set content for (var i = 0; i < contentPlaceHolders.length; i++) { var contentPlaceHolder = contentPlaceHolders[i]; contentPlaceHolder.set("content", moduleInstance.findContent(contentPlaceHolder.$.name)); } } }) .exec(function (err) { var moduleInstance = self.$moduleInstance; self.set({ state: err ? 'error' : null, currentModule: moduleInstance }); self.$moduleInstance = null; if (callback) { callback(err, moduleInstance); } }); }
javascript
function (moduleName, moduleInstance, callback, routeContext, cachedInstance) { var self = this; //noinspection JSValidateTypes flow() .seq(function (cb) { self.$moduleInstance = moduleInstance; var currentModule = self.$.currentModule; if (currentModule) { currentModule._unload(cb); } else { cb(); } }) .seq(function (cb) { // start module moduleInstance.start(function (err) { if (err || cachedInstance) { cb(err); } else { if (routeContext) { // fresh instance with maybe new routers -> exec routes for new router var routeExecutionStack = []; for (var i = 0; i < moduleInstance.$routers.length; i++) { var router = moduleInstance.$routers[i]; router.set("module", moduleInstance); routeExecutionStack = routeExecutionStack.concat(router.generateRoutingStack(routeContext.fragment)); } flow() .seqEach(routeExecutionStack, function (routingFunction, cb) { routingFunction(cb); }) .exec(cb); } else { cb(); } } }, routeContext); }) .seq(function () { if (moduleInstance === self.$moduleInstance) { self._clearContentPlaceHolders(); self.set('currentModuleName', moduleName); var contentPlaceHolders = self.getContentPlaceHolders("external"); // set content for (var i = 0; i < contentPlaceHolders.length; i++) { var contentPlaceHolder = contentPlaceHolders[i]; contentPlaceHolder.set("content", moduleInstance.findContent(contentPlaceHolder.$.name)); } } }) .exec(function (err) { var moduleInstance = self.$moduleInstance; self.set({ state: err ? 'error' : null, currentModule: moduleInstance }); self.$moduleInstance = null; if (callback) { callback(err, moduleInstance); } }); }
[ "function", "(", "moduleName", ",", "moduleInstance", ",", "callback", ",", "routeContext", ",", "cachedInstance", ")", "{", "var", "self", "=", "this", ";", "//noinspection JSValidateTypes", "flow", "(", ")", ".", "seq", "(", "function", "(", "cb", ")", "{", "self", ".", "$moduleInstance", "=", "moduleInstance", ";", "var", "currentModule", "=", "self", ".", "$", ".", "currentModule", ";", "if", "(", "currentModule", ")", "{", "currentModule", ".", "_unload", "(", "cb", ")", ";", "}", "else", "{", "cb", "(", ")", ";", "}", "}", ")", ".", "seq", "(", "function", "(", "cb", ")", "{", "// start module", "moduleInstance", ".", "start", "(", "function", "(", "err", ")", "{", "if", "(", "err", "||", "cachedInstance", ")", "{", "cb", "(", "err", ")", ";", "}", "else", "{", "if", "(", "routeContext", ")", "{", "// fresh instance with maybe new routers -> exec routes for new router", "var", "routeExecutionStack", "=", "[", "]", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "moduleInstance", ".", "$routers", ".", "length", ";", "i", "++", ")", "{", "var", "router", "=", "moduleInstance", ".", "$routers", "[", "i", "]", ";", "router", ".", "set", "(", "\"module\"", ",", "moduleInstance", ")", ";", "routeExecutionStack", "=", "routeExecutionStack", ".", "concat", "(", "router", ".", "generateRoutingStack", "(", "routeContext", ".", "fragment", ")", ")", ";", "}", "flow", "(", ")", ".", "seqEach", "(", "routeExecutionStack", ",", "function", "(", "routingFunction", ",", "cb", ")", "{", "routingFunction", "(", "cb", ")", ";", "}", ")", ".", "exec", "(", "cb", ")", ";", "}", "else", "{", "cb", "(", ")", ";", "}", "}", "}", ",", "routeContext", ")", ";", "}", ")", ".", "seq", "(", "function", "(", ")", "{", "if", "(", "moduleInstance", "===", "self", ".", "$moduleInstance", ")", "{", "self", ".", "_clearContentPlaceHolders", "(", ")", ";", "self", ".", "set", "(", "'currentModuleName'", ",", "moduleName", ")", ";", "var", "contentPlaceHolders", "=", "self", ".", "getContentPlaceHolders", "(", "\"external\"", ")", ";", "// set content", "for", "(", "var", "i", "=", "0", ";", "i", "<", "contentPlaceHolders", ".", "length", ";", "i", "++", ")", "{", "var", "contentPlaceHolder", "=", "contentPlaceHolders", "[", "i", "]", ";", "contentPlaceHolder", ".", "set", "(", "\"content\"", ",", "moduleInstance", ".", "findContent", "(", "contentPlaceHolder", ".", "$", ".", "name", ")", ")", ";", "}", "}", "}", ")", ".", "exec", "(", "function", "(", "err", ")", "{", "var", "moduleInstance", "=", "self", ".", "$moduleInstance", ";", "self", ".", "set", "(", "{", "state", ":", "err", "?", "'error'", ":", "null", ",", "currentModule", ":", "moduleInstance", "}", ")", ";", "self", ".", "$moduleInstance", "=", "null", ";", "if", "(", "callback", ")", "{", "callback", "(", "err", ",", "moduleInstance", ")", ";", "}", "}", ")", ";", "}" ]
Starts the module with the given name @param {String} moduleName - The name of the module @param {js.core.Module} moduleInstance - the module instance @param {Function} callback - the callback function @param {Object} routeContext - the route context @param {Object} [cachedInstance] @private
[ "Starts", "the", "module", "with", "the", "given", "name" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/ModuleLoader.js#L112-L193
26,857
rappid/rAppid.js
js/core/TooltipManager.js
function (templateName, target, attributes, options) { if (!this.$container) { this.$container = this.createComponent(HtmlElement, {"class": this.$.containerClass, "tagName": "div"}); this.$stage.addChild(this.$container); } var tooltip = this.getTooltipByNameAndTarget(templateName, target); if (tooltip) { return tooltip; } else { options = options || {}; if (target && target.isRendered()) { var content = options.content, animationClass = this.$.animationClass || options.animationClass, duration = this.$.duration || options.duration; var rect = target.$el.getBoundingClientRect(); // create a instance tooltip = this.createComponent(Tooltip, { manager: this, "class": templateName, animationClass: animationClass, left: rect.left, top: rect.top, width: rect.width, height: 0 // due to missing pointer event support in IE } ); var templateInstance = this.$templates[templateName].createInstance(attributes || {}); templateInstance.$classAttributes = templateInstance.$classAttributes || []; // add class attributes for (var key in attributes) { if (attributes.hasOwnProperty(key)) { templateInstance.$classAttributes.push(key); } } // add template instance tooltip.addChild(templateInstance); tooltip.bind('dom:remove', function () { tooltip.destroy(); }); // if content if (content) { templateInstance.$children = content.getChildren(); templateInstance._renderChildren(templateInstance.$children); } this.$tooltips.push({ target: target, templateName: templateName, instance: tooltip }); this.$container.addChild(tooltip); var self = this; if (duration && duration > 0) { setTimeout(function () { self.hideTooltip(tooltip); }, duration) } return tooltip; } else { throw new Error("No target for tooltip specified"); } } }
javascript
function (templateName, target, attributes, options) { if (!this.$container) { this.$container = this.createComponent(HtmlElement, {"class": this.$.containerClass, "tagName": "div"}); this.$stage.addChild(this.$container); } var tooltip = this.getTooltipByNameAndTarget(templateName, target); if (tooltip) { return tooltip; } else { options = options || {}; if (target && target.isRendered()) { var content = options.content, animationClass = this.$.animationClass || options.animationClass, duration = this.$.duration || options.duration; var rect = target.$el.getBoundingClientRect(); // create a instance tooltip = this.createComponent(Tooltip, { manager: this, "class": templateName, animationClass: animationClass, left: rect.left, top: rect.top, width: rect.width, height: 0 // due to missing pointer event support in IE } ); var templateInstance = this.$templates[templateName].createInstance(attributes || {}); templateInstance.$classAttributes = templateInstance.$classAttributes || []; // add class attributes for (var key in attributes) { if (attributes.hasOwnProperty(key)) { templateInstance.$classAttributes.push(key); } } // add template instance tooltip.addChild(templateInstance); tooltip.bind('dom:remove', function () { tooltip.destroy(); }); // if content if (content) { templateInstance.$children = content.getChildren(); templateInstance._renderChildren(templateInstance.$children); } this.$tooltips.push({ target: target, templateName: templateName, instance: tooltip }); this.$container.addChild(tooltip); var self = this; if (duration && duration > 0) { setTimeout(function () { self.hideTooltip(tooltip); }, duration) } return tooltip; } else { throw new Error("No target for tooltip specified"); } } }
[ "function", "(", "templateName", ",", "target", ",", "attributes", ",", "options", ")", "{", "if", "(", "!", "this", ".", "$container", ")", "{", "this", ".", "$container", "=", "this", ".", "createComponent", "(", "HtmlElement", ",", "{", "\"class\"", ":", "this", ".", "$", ".", "containerClass", ",", "\"tagName\"", ":", "\"div\"", "}", ")", ";", "this", ".", "$stage", ".", "addChild", "(", "this", ".", "$container", ")", ";", "}", "var", "tooltip", "=", "this", ".", "getTooltipByNameAndTarget", "(", "templateName", ",", "target", ")", ";", "if", "(", "tooltip", ")", "{", "return", "tooltip", ";", "}", "else", "{", "options", "=", "options", "||", "{", "}", ";", "if", "(", "target", "&&", "target", ".", "isRendered", "(", ")", ")", "{", "var", "content", "=", "options", ".", "content", ",", "animationClass", "=", "this", ".", "$", ".", "animationClass", "||", "options", ".", "animationClass", ",", "duration", "=", "this", ".", "$", ".", "duration", "||", "options", ".", "duration", ";", "var", "rect", "=", "target", ".", "$el", ".", "getBoundingClientRect", "(", ")", ";", "// create a instance", "tooltip", "=", "this", ".", "createComponent", "(", "Tooltip", ",", "{", "manager", ":", "this", ",", "\"class\"", ":", "templateName", ",", "animationClass", ":", "animationClass", ",", "left", ":", "rect", ".", "left", ",", "top", ":", "rect", ".", "top", ",", "width", ":", "rect", ".", "width", ",", "height", ":", "0", "// due to missing pointer event support in IE", "}", ")", ";", "var", "templateInstance", "=", "this", ".", "$templates", "[", "templateName", "]", ".", "createInstance", "(", "attributes", "||", "{", "}", ")", ";", "templateInstance", ".", "$classAttributes", "=", "templateInstance", ".", "$classAttributes", "||", "[", "]", ";", "// add class attributes", "for", "(", "var", "key", "in", "attributes", ")", "{", "if", "(", "attributes", ".", "hasOwnProperty", "(", "key", ")", ")", "{", "templateInstance", ".", "$classAttributes", ".", "push", "(", "key", ")", ";", "}", "}", "// add template instance", "tooltip", ".", "addChild", "(", "templateInstance", ")", ";", "tooltip", ".", "bind", "(", "'dom:remove'", ",", "function", "(", ")", "{", "tooltip", ".", "destroy", "(", ")", ";", "}", ")", ";", "// if content", "if", "(", "content", ")", "{", "templateInstance", ".", "$children", "=", "content", ".", "getChildren", "(", ")", ";", "templateInstance", ".", "_renderChildren", "(", "templateInstance", ".", "$children", ")", ";", "}", "this", ".", "$tooltips", ".", "push", "(", "{", "target", ":", "target", ",", "templateName", ":", "templateName", ",", "instance", ":", "tooltip", "}", ")", ";", "this", ".", "$container", ".", "addChild", "(", "tooltip", ")", ";", "var", "self", "=", "this", ";", "if", "(", "duration", "&&", "duration", ">", "0", ")", "{", "setTimeout", "(", "function", "(", ")", "{", "self", ".", "hideTooltip", "(", "tooltip", ")", ";", "}", ",", "duration", ")", "}", "return", "tooltip", ";", "}", "else", "{", "throw", "new", "Error", "(", "\"No target for tooltip specified\"", ")", ";", "}", "}", "}" ]
Shows a tooltip with the given template add the target element @param {String} templateName - The name of the template to use @param {js.core.Component} target - The target element @param {Object} attributes - the @param {Object} options - Options for displaying the @param {Number} options.duration - default is false. Duration for auto-hide of tooltip @param {String} options.animationClass - default is set by TooltipManager. @returns {js.core.TooltipManager.Tooltip}
[ "Shows", "a", "tooltip", "with", "the", "given", "template", "add", "the", "target", "element" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/TooltipManager.js#L49-L122
26,858
rappid/rAppid.js
js/core/TooltipManager.js
function (tooltip, target) { if (!(tooltip instanceof Tooltip)) { tooltip = this.getTooltipByNameAndTarget(tooltip, target); } if (tooltip) { var i = this.$tooltips.indexOf(tooltip); this.$tooltips.splice(i, 1); this.$container.removeChild(tooltip); } }
javascript
function (tooltip, target) { if (!(tooltip instanceof Tooltip)) { tooltip = this.getTooltipByNameAndTarget(tooltip, target); } if (tooltip) { var i = this.$tooltips.indexOf(tooltip); this.$tooltips.splice(i, 1); this.$container.removeChild(tooltip); } }
[ "function", "(", "tooltip", ",", "target", ")", "{", "if", "(", "!", "(", "tooltip", "instanceof", "Tooltip", ")", ")", "{", "tooltip", "=", "this", ".", "getTooltipByNameAndTarget", "(", "tooltip", ",", "target", ")", ";", "}", "if", "(", "tooltip", ")", "{", "var", "i", "=", "this", ".", "$tooltips", ".", "indexOf", "(", "tooltip", ")", ";", "this", ".", "$tooltips", ".", "splice", "(", "i", ",", "1", ")", ";", "this", ".", "$container", ".", "removeChild", "(", "tooltip", ")", ";", "}", "}" ]
Closes a tooltip by name and target element or tooltip Instance @param {js.core.TooltipManager.Tooltip|String} tooltip - The tooltip instance or the templateName @param {js.core.Component} [target] - The target element of the tooltip
[ "Closes", "a", "tooltip", "by", "name", "and", "target", "element", "or", "tooltip", "Instance" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/TooltipManager.js#L131-L140
26,859
rappid/rAppid.js
js/core/TooltipManager.js
function (templateName, target) { var tooltip; for (var i = 0; i < this.$tooltips.length; i++) { tooltip = this.$tooltips[i]; if (tooltip.templateName === templateName && tooltip.target === target) { return tooltip.instance; } } return null; }
javascript
function (templateName, target) { var tooltip; for (var i = 0; i < this.$tooltips.length; i++) { tooltip = this.$tooltips[i]; if (tooltip.templateName === templateName && tooltip.target === target) { return tooltip.instance; } } return null; }
[ "function", "(", "templateName", ",", "target", ")", "{", "var", "tooltip", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "this", ".", "$tooltips", ".", "length", ";", "i", "++", ")", "{", "tooltip", "=", "this", ".", "$tooltips", "[", "i", "]", ";", "if", "(", "tooltip", ".", "templateName", "===", "templateName", "&&", "tooltip", ".", "target", "===", "target", ")", "{", "return", "tooltip", ".", "instance", ";", "}", "}", "return", "null", ";", "}" ]
Returns a tooltip instance by name and target element @param {String} templateName @param {js.core.Component} target @returns {js.core.TooltipManager.Tooltip}
[ "Returns", "a", "tooltip", "instance", "by", "name", "and", "target", "element" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/core/TooltipManager.js#L149-L158
26,860
rappid/rAppid.js
js/lib/rAppid.js
function (xhr) { this.xhr = xhr; this.status = xhr.status; this.$nativeResponseHeaders = xhr.getAllResponseHeaders(); this.responses = {}; var xml = xhr.responseXML; // Construct response list if (xml && xml.documentElement) { this.responses.xml = xml; } this.responses.text = xhr.responseText; try { this.statusText = xhr.statusText; } catch (e) { this.statusText = ""; } }
javascript
function (xhr) { this.xhr = xhr; this.status = xhr.status; this.$nativeResponseHeaders = xhr.getAllResponseHeaders(); this.responses = {}; var xml = xhr.responseXML; // Construct response list if (xml && xml.documentElement) { this.responses.xml = xml; } this.responses.text = xhr.responseText; try { this.statusText = xhr.statusText; } catch (e) { this.statusText = ""; } }
[ "function", "(", "xhr", ")", "{", "this", ".", "xhr", "=", "xhr", ";", "this", ".", "status", "=", "xhr", ".", "status", ";", "this", ".", "$nativeResponseHeaders", "=", "xhr", ".", "getAllResponseHeaders", "(", ")", ";", "this", ".", "responses", "=", "{", "}", ";", "var", "xml", "=", "xhr", ".", "responseXML", ";", "// Construct response list", "if", "(", "xml", "&&", "xml", ".", "documentElement", ")", "{", "this", ".", "responses", ".", "xml", "=", "xml", ";", "}", "this", ".", "responses", ".", "text", "=", "xhr", ".", "responseText", ";", "try", "{", "this", ".", "statusText", "=", "xhr", ".", "statusText", ";", "}", "catch", "(", "e", ")", "{", "this", ".", "statusText", "=", "\"\"", ";", "}", "}" ]
IE leaves an \r character at EOL
[ "IE", "leaves", "an", "\\", "r", "character", "at", "EOL" ]
38ebcdcd73b06ae7825aba1111c734b56202abe9
https://github.com/rappid/rAppid.js/blob/38ebcdcd73b06ae7825aba1111c734b56202abe9/js/lib/rAppid.js#L398-L417
26,861
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.haml.js
parse_attribs
function parse_attribs(line) { var attributes = {}, l = line.length, i, c, count = 1, quote = false, skip = false, open, close, joiner, seperator, pair = { start: 1, middle: null, end: null }; if (!(l > 0 && (line.charAt(0) === '{' || line.charAt(0) === '('))) { return { content: line[0] === ' ' ? line.substr(1, l) : line }; } open = line.charAt(0); close = (open === '{') ? '}' : ')'; joiner = (open === '{') ? ':' : '='; seperator = (open === '{') ? ',' : ' '; function process_pair() { if (typeof pair.start === 'number' && typeof pair.middle === 'number' && typeof pair.end === 'number') { var key = line.substr(pair.start, pair.middle - pair.start).trim(), value = line.substr(pair.middle + 1, pair.end - pair.middle - 1).trim(); attributes[key] = value; } pair = { start: null, middle: null, end: null }; } for (i = 1; count > 0; i += 1) { // If we reach the end of the line, then there is a problem if (i > l) { throw "Malformed attribute block"; } c = line.charAt(i); if (skip) { skip = false; } else { if (quote) { if (c === '\\') { skip = true; } if (c === quote) { quote = false; } } else { if (c === '"' || c === "'") { quote = c; } if (count === 1) { if (c === joiner) { pair.middle = i; } if (c === seperator || c === close) { pair.end = i; process_pair(); if (c === seperator) { pair.start = i + 1; } } } if (c === open) { count += 1; } if (c === close) { count -= 1; } } } } attributes.content = line.substr(i, line.length); return attributes; }
javascript
function parse_attribs(line) { var attributes = {}, l = line.length, i, c, count = 1, quote = false, skip = false, open, close, joiner, seperator, pair = { start: 1, middle: null, end: null }; if (!(l > 0 && (line.charAt(0) === '{' || line.charAt(0) === '('))) { return { content: line[0] === ' ' ? line.substr(1, l) : line }; } open = line.charAt(0); close = (open === '{') ? '}' : ')'; joiner = (open === '{') ? ':' : '='; seperator = (open === '{') ? ',' : ' '; function process_pair() { if (typeof pair.start === 'number' && typeof pair.middle === 'number' && typeof pair.end === 'number') { var key = line.substr(pair.start, pair.middle - pair.start).trim(), value = line.substr(pair.middle + 1, pair.end - pair.middle - 1).trim(); attributes[key] = value; } pair = { start: null, middle: null, end: null }; } for (i = 1; count > 0; i += 1) { // If we reach the end of the line, then there is a problem if (i > l) { throw "Malformed attribute block"; } c = line.charAt(i); if (skip) { skip = false; } else { if (quote) { if (c === '\\') { skip = true; } if (c === quote) { quote = false; } } else { if (c === '"' || c === "'") { quote = c; } if (count === 1) { if (c === joiner) { pair.middle = i; } if (c === seperator || c === close) { pair.end = i; process_pair(); if (c === seperator) { pair.start = i + 1; } } } if (c === open) { count += 1; } if (c === close) { count -= 1; } } } } attributes.content = line.substr(i, line.length); return attributes; }
[ "function", "parse_attribs", "(", "line", ")", "{", "var", "attributes", "=", "{", "}", ",", "l", "=", "line", ".", "length", ",", "i", ",", "c", ",", "count", "=", "1", ",", "quote", "=", "false", ",", "skip", "=", "false", ",", "open", ",", "close", ",", "joiner", ",", "seperator", ",", "pair", "=", "{", "start", ":", "1", ",", "middle", ":", "null", ",", "end", ":", "null", "}", ";", "if", "(", "!", "(", "l", ">", "0", "&&", "(", "line", ".", "charAt", "(", "0", ")", "===", "'{'", "||", "line", ".", "charAt", "(", "0", ")", "===", "'('", ")", ")", ")", "{", "return", "{", "content", ":", "line", "[", "0", "]", "===", "' '", "?", "line", ".", "substr", "(", "1", ",", "l", ")", ":", "line", "}", ";", "}", "open", "=", "line", ".", "charAt", "(", "0", ")", ";", "close", "=", "(", "open", "===", "'{'", ")", "?", "'}'", ":", "')'", ";", "joiner", "=", "(", "open", "===", "'{'", ")", "?", "':'", ":", "'='", ";", "seperator", "=", "(", "open", "===", "'{'", ")", "?", "','", ":", "' '", ";", "function", "process_pair", "(", ")", "{", "if", "(", "typeof", "pair", ".", "start", "===", "'number'", "&&", "typeof", "pair", ".", "middle", "===", "'number'", "&&", "typeof", "pair", ".", "end", "===", "'number'", ")", "{", "var", "key", "=", "line", ".", "substr", "(", "pair", ".", "start", ",", "pair", ".", "middle", "-", "pair", ".", "start", ")", ".", "trim", "(", ")", ",", "value", "=", "line", ".", "substr", "(", "pair", ".", "middle", "+", "1", ",", "pair", ".", "end", "-", "pair", ".", "middle", "-", "1", ")", ".", "trim", "(", ")", ";", "attributes", "[", "key", "]", "=", "value", ";", "}", "pair", "=", "{", "start", ":", "null", ",", "middle", ":", "null", ",", "end", ":", "null", "}", ";", "}", "for", "(", "i", "=", "1", ";", "count", ">", "0", ";", "i", "+=", "1", ")", "{", "// If we reach the end of the line, then there is a problem", "if", "(", "i", ">", "l", ")", "{", "throw", "\"Malformed attribute block\"", ";", "}", "c", "=", "line", ".", "charAt", "(", "i", ")", ";", "if", "(", "skip", ")", "{", "skip", "=", "false", ";", "}", "else", "{", "if", "(", "quote", ")", "{", "if", "(", "c", "===", "'\\\\'", ")", "{", "skip", "=", "true", ";", "}", "if", "(", "c", "===", "quote", ")", "{", "quote", "=", "false", ";", "}", "}", "else", "{", "if", "(", "c", "===", "'\"'", "||", "c", "===", "\"'\"", ")", "{", "quote", "=", "c", ";", "}", "if", "(", "count", "===", "1", ")", "{", "if", "(", "c", "===", "joiner", ")", "{", "pair", ".", "middle", "=", "i", ";", "}", "if", "(", "c", "===", "seperator", "||", "c", "===", "close", ")", "{", "pair", ".", "end", "=", "i", ";", "process_pair", "(", ")", ";", "if", "(", "c", "===", "seperator", ")", "{", "pair", ".", "start", "=", "i", "+", "1", ";", "}", "}", "}", "if", "(", "c", "===", "open", ")", "{", "count", "+=", "1", ";", "}", "if", "(", "c", "===", "close", ")", "{", "count", "-=", "1", ";", "}", "}", "}", "}", "attributes", ".", "content", "=", "line", ".", "substr", "(", "i", ",", "line", ".", "length", ")", ";", "return", "attributes", ";", "}" ]
Parse the attribute block using a state machine
[ "Parse", "the", "attribute", "block", "using", "a", "state", "machine" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.haml.js#L50-L136
26,862
mikeal/node.couchapp.js
boiler/attachments/sammy/plugins/sammy.haml.js
parse_interpol
function parse_interpol(value) { var items = [], pos = 0, next = 0, match; while (true) { // Match up to embedded string next = value.substr(pos).search(embedder); if (next < 0) { if (pos < value.length) { items.push(JSON.stringify(value.substr(pos))); } break; } items.push(JSON.stringify(value.substr(pos, next))); pos += next; // Match embedded string match = value.substr(pos).match(embedder); next = match[0].length; if (next < 0) { break; } items.push(match[1] || match[2]); pos += next; } return items.filter(function (part) { return part && part.length > 0}).join(" +\n"); }
javascript
function parse_interpol(value) { var items = [], pos = 0, next = 0, match; while (true) { // Match up to embedded string next = value.substr(pos).search(embedder); if (next < 0) { if (pos < value.length) { items.push(JSON.stringify(value.substr(pos))); } break; } items.push(JSON.stringify(value.substr(pos, next))); pos += next; // Match embedded string match = value.substr(pos).match(embedder); next = match[0].length; if (next < 0) { break; } items.push(match[1] || match[2]); pos += next; } return items.filter(function (part) { return part && part.length > 0}).join(" +\n"); }
[ "function", "parse_interpol", "(", "value", ")", "{", "var", "items", "=", "[", "]", ",", "pos", "=", "0", ",", "next", "=", "0", ",", "match", ";", "while", "(", "true", ")", "{", "// Match up to embedded string", "next", "=", "value", ".", "substr", "(", "pos", ")", ".", "search", "(", "embedder", ")", ";", "if", "(", "next", "<", "0", ")", "{", "if", "(", "pos", "<", "value", ".", "length", ")", "{", "items", ".", "push", "(", "JSON", ".", "stringify", "(", "value", ".", "substr", "(", "pos", ")", ")", ")", ";", "}", "break", ";", "}", "items", ".", "push", "(", "JSON", ".", "stringify", "(", "value", ".", "substr", "(", "pos", ",", "next", ")", ")", ")", ";", "pos", "+=", "next", ";", "// Match embedded string", "match", "=", "value", ".", "substr", "(", "pos", ")", ".", "match", "(", "embedder", ")", ";", "next", "=", "match", "[", "0", "]", ".", "length", ";", "if", "(", "next", "<", "0", ")", "{", "break", ";", "}", "items", ".", "push", "(", "match", "[", "1", "]", "||", "match", "[", "2", "]", ")", ";", "pos", "+=", "next", ";", "}", "return", "items", ".", "filter", "(", "function", "(", "part", ")", "{", "return", "part", "&&", "part", ".", "length", ">", "0", "}", ")", ".", "join", "(", "\" +\\n\"", ")", ";", "}" ]
Split interpolated strings into an array of literals and code fragments.
[ "Split", "interpolated", "strings", "into", "an", "array", "of", "literals", "and", "code", "fragments", "." ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/boiler/attachments/sammy/plugins/sammy.haml.js#L139-L164
26,863
mikeal/node.couchapp.js
main.js
loadFiles
function loadFiles(dir, options) { var listings = fs.readdirSync(dir) , options = options || {} , obj = {}; listings.forEach(function (listing) { var file = path.join(dir, listing) , prop = listing.split('.')[0] // probably want regexp or something more robust , stat = fs.statSync(file); if (stat.isFile()) { var content = fs.readFileSync(file).toString(); if (options.operators) { options.operators.forEach(function (op) { content = op(content, options); }); } obj[prop] = content; } else if (stat.isDirectory()) { obj[listing] = loadFiles(file, options); } }); return obj; }
javascript
function loadFiles(dir, options) { var listings = fs.readdirSync(dir) , options = options || {} , obj = {}; listings.forEach(function (listing) { var file = path.join(dir, listing) , prop = listing.split('.')[0] // probably want regexp or something more robust , stat = fs.statSync(file); if (stat.isFile()) { var content = fs.readFileSync(file).toString(); if (options.operators) { options.operators.forEach(function (op) { content = op(content, options); }); } obj[prop] = content; } else if (stat.isDirectory()) { obj[listing] = loadFiles(file, options); } }); return obj; }
[ "function", "loadFiles", "(", "dir", ",", "options", ")", "{", "var", "listings", "=", "fs", ".", "readdirSync", "(", "dir", ")", ",", "options", "=", "options", "||", "{", "}", ",", "obj", "=", "{", "}", ";", "listings", ".", "forEach", "(", "function", "(", "listing", ")", "{", "var", "file", "=", "path", ".", "join", "(", "dir", ",", "listing", ")", ",", "prop", "=", "listing", ".", "split", "(", "'.'", ")", "[", "0", "]", "// probably want regexp or something more robust", ",", "stat", "=", "fs", ".", "statSync", "(", "file", ")", ";", "if", "(", "stat", ".", "isFile", "(", ")", ")", "{", "var", "content", "=", "fs", ".", "readFileSync", "(", "file", ")", ".", "toString", "(", ")", ";", "if", "(", "options", ".", "operators", ")", "{", "options", ".", "operators", ".", "forEach", "(", "function", "(", "op", ")", "{", "content", "=", "op", "(", "content", ",", "options", ")", ";", "}", ")", ";", "}", "obj", "[", "prop", "]", "=", "content", ";", "}", "else", "if", "(", "stat", ".", "isDirectory", "(", ")", ")", "{", "obj", "[", "listing", "]", "=", "loadFiles", "(", "file", ",", "options", ")", ";", "}", "}", ")", ";", "return", "obj", ";", "}" ]
Recursively load directory contents into ddoc It's really convenient to see the main couchapp code in single file, rather than mapped into little files in lots of directories like the python couchapp. But there are definitely cases where we might want to use some module or another on the server side. This addition loads file contents from a given directory (recursively) into a js object that can be added to a design document and require()'d in lists, shows, etc. Use couchapp.loadFiles() in app.js like this: ddoc = { _id: '_design/app' , views: {} , ... , lib: couchapp.loadFiles('./lib') , vendor: couchapp.loadFiles('./vendor') } Optionally, pass in operators to process file contents. For example, generate mustache templates from jade templates. In yourapp/templates/index.jade !!!5 html head //- jade locals.title title!= title body .item //- mustache variable for server-side rendering h1 {{ heading }} in yourapp/app.js var couchapp = require('couchapp') , jade = require('jade') , options = { , operators: [ function renderJade (content, options) { var compiler = jade.compile(content); return compiler(options.locals || {}); } ] , locals: { title: 'Now we\'re cookin with gas!' } }; ddoc = { ... }; ddoc.templates = loadFiles(dir, options);
[ "Recursively", "load", "directory", "contents", "into", "ddoc" ]
e4ce61c342595148c37ad1ea1a88e7b53120c668
https://github.com/mikeal/node.couchapp.js/blob/e4ce61c342595148c37ad1ea1a88e7b53120c668/main.js#L83-L107
26,864
nuzzio/grunt-strip-code
tasks/strip_code.js
function () { if (arguments.length === 0) { grunt.warn(strings[options.locale]['translate.param.missing']); } var key = arguments[0]; if (!(key in strings[options.locale])) { grunt.warn(strings[options.locale]['string.key.missing'] + ': ' + key); } var string = strings[options.locale][key]; for (var i = 1; i < arguments.length; i++) { var replacementKey = '%' + i; string = string.replace(replacementKey, arguments[i]); } return string; }
javascript
function () { if (arguments.length === 0) { grunt.warn(strings[options.locale]['translate.param.missing']); } var key = arguments[0]; if (!(key in strings[options.locale])) { grunt.warn(strings[options.locale]['string.key.missing'] + ': ' + key); } var string = strings[options.locale][key]; for (var i = 1; i < arguments.length; i++) { var replacementKey = '%' + i; string = string.replace(replacementKey, arguments[i]); } return string; }
[ "function", "(", ")", "{", "if", "(", "arguments", ".", "length", "===", "0", ")", "{", "grunt", ".", "warn", "(", "strings", "[", "options", ".", "locale", "]", "[", "'translate.param.missing'", "]", ")", ";", "}", "var", "key", "=", "arguments", "[", "0", "]", ";", "if", "(", "!", "(", "key", "in", "strings", "[", "options", ".", "locale", "]", ")", ")", "{", "grunt", ".", "warn", "(", "strings", "[", "options", ".", "locale", "]", "[", "'string.key.missing'", "]", "+", "': '", "+", "key", ")", ";", "}", "var", "string", "=", "strings", "[", "options", ".", "locale", "]", "[", "key", "]", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "arguments", ".", "length", ";", "i", "++", ")", "{", "var", "replacementKey", "=", "'%'", "+", "i", ";", "string", "=", "string", ".", "replace", "(", "replacementKey", ",", "arguments", "[", "i", "]", ")", ";", "}", "return", "string", ";", "}" ]
Takes in dynamic parameters and expects first param to be a key for a string, subsequent params will substitute the variables in the string in the order they are declared. For the string: "my.key": "I will do my %1 then my %2" translate('my.key', 'first replacement', 'second replacement') the first replacement argument will replace %1, second %2 and so on. @param key string
[ "Takes", "in", "dynamic", "parameters", "and", "expects", "first", "param", "to", "be", "a", "key", "for", "a", "string", "subsequent", "params", "will", "substitute", "the", "variables", "in", "the", "string", "in", "the", "order", "they", "are", "declared", "." ]
4a84e8bb823b740839df5a6a37d528178f4df906
https://github.com/nuzzio/grunt-strip-code/blob/4a84e8bb823b740839df5a6a37d528178f4df906/tasks/strip_code.js#L83-L103
26,865
nuzzio/grunt-strip-code
tasks/strip_code.js
function (params) { var message = translate(errors[params.caseNum]) .replace('%n', (params.lineNum + 1).toString()) .replace('%p', params.pattern) .replace('%x', params.start) .replace('%y', (params.endLineNum + 1).toString()) .replace('%f', currentFile); if (options.testMode === true) { grunt.log.writeln(message); } else { grunt.warn(message); } }
javascript
function (params) { var message = translate(errors[params.caseNum]) .replace('%n', (params.lineNum + 1).toString()) .replace('%p', params.pattern) .replace('%x', params.start) .replace('%y', (params.endLineNum + 1).toString()) .replace('%f', currentFile); if (options.testMode === true) { grunt.log.writeln(message); } else { grunt.warn(message); } }
[ "function", "(", "params", ")", "{", "var", "message", "=", "translate", "(", "errors", "[", "params", ".", "caseNum", "]", ")", ".", "replace", "(", "'%n'", ",", "(", "params", ".", "lineNum", "+", "1", ")", ".", "toString", "(", ")", ")", ".", "replace", "(", "'%p'", ",", "params", ".", "pattern", ")", ".", "replace", "(", "'%x'", ",", "params", ".", "start", ")", ".", "replace", "(", "'%y'", ",", "(", "params", ".", "endLineNum", "+", "1", ")", ".", "toString", "(", ")", ")", ".", "replace", "(", "'%f'", ",", "currentFile", ")", ";", "if", "(", "options", ".", "testMode", "===", "true", ")", "{", "grunt", ".", "log", ".", "writeln", "(", "message", ")", ";", "}", "else", "{", "grunt", ".", "warn", "(", "message", ")", ";", "}", "}" ]
Generates error messages for block and pattern errors then quits.
[ "Generates", "error", "messages", "for", "block", "and", "pattern", "errors", "then", "quits", "." ]
4a84e8bb823b740839df5a6a37d528178f4df906
https://github.com/nuzzio/grunt-strip-code/blob/4a84e8bb823b740839df5a6a37d528178f4df906/tasks/strip_code.js#L205-L218
26,866
nuzzio/grunt-strip-code
tasks/strip_code.js
function (line, lineNum) { if (line.trim() === '') { return; } function logAnyDelimiterType(line) { blocks.forEach(function (blockDef, blockIdx) { if (blockDef.start.test(line) === true) { fileStartDelimiters.push([blockIdx, lineNum, line.trim()]); } if (blockDef.end.test(line) === true) { fileEndDelimiters.push([blockIdx, lineNum, line.trim()]); } }); } logAnyDelimiterType(line); var startCount = fileStartDelimiters.length; var endCount = fileEndDelimiters.length; /** * Checks that amount of start/end blocks are equal. * * @param blockDef * @param blockIdx */ var checkBlocksParity = function (blockDef, blockIdx) { var block = blockStats[blockIdx]; /** * 'if' for start block check */ if (blockDef.start.test(line) === true) { block.lastStartLine = lineNum; if (block.startCount > block.endCount) { generateMessage({ pattern: line.trim(), lineNum: block.lastStartLine, caseNum: 1 }); } block.startCount++; } /** * 'if' for end block check */ if (blockDef.end.test(line) === true) { block.lastEndLine = lineNum; if (block.endCount >= block.startCount) { generateMessage({ pattern: line.trim(), lineNum: block.lastEndLine, caseNum: 2 }); } block.endCount++; } }; /** * Checks if any two (or more) pairs of start/end * blocks are intersecting. * * @param blockDef * @param blockIdx */ var checkBlocksIntersection = function (blockDef, blockIdx) { if (blockDef.start.test(line)) { blocksStack.push([blockIdx, lineNum, line.trim()]); } if (blockDef.end.test(line) && typeof last(blocksStack) !== "undefined") { if (last(blocksStack)[0] === blockIdx) { blocksStack.pop(); } else { generateMessage({ start: last(blocksStack)[2], pattern: line.trim(), lineNum: last(blocksStack)[1], endLineNum: lineNum, caseNum: 3 }); } } else if (startCount - endCount > 1) { generateMessage({ start: last(blocksStack)[2], pattern: line.trim(), lineNum: last(blocksStack)[1], endLineNum: lineNum, caseNum: 3 }); } }; if (options.parityCheck === true) { blocks.forEach(checkBlocksParity); } if (options.intersectionCheck === true) { blocks.forEach(checkBlocksIntersection); } }
javascript
function (line, lineNum) { if (line.trim() === '') { return; } function logAnyDelimiterType(line) { blocks.forEach(function (blockDef, blockIdx) { if (blockDef.start.test(line) === true) { fileStartDelimiters.push([blockIdx, lineNum, line.trim()]); } if (blockDef.end.test(line) === true) { fileEndDelimiters.push([blockIdx, lineNum, line.trim()]); } }); } logAnyDelimiterType(line); var startCount = fileStartDelimiters.length; var endCount = fileEndDelimiters.length; /** * Checks that amount of start/end blocks are equal. * * @param blockDef * @param blockIdx */ var checkBlocksParity = function (blockDef, blockIdx) { var block = blockStats[blockIdx]; /** * 'if' for start block check */ if (blockDef.start.test(line) === true) { block.lastStartLine = lineNum; if (block.startCount > block.endCount) { generateMessage({ pattern: line.trim(), lineNum: block.lastStartLine, caseNum: 1 }); } block.startCount++; } /** * 'if' for end block check */ if (blockDef.end.test(line) === true) { block.lastEndLine = lineNum; if (block.endCount >= block.startCount) { generateMessage({ pattern: line.trim(), lineNum: block.lastEndLine, caseNum: 2 }); } block.endCount++; } }; /** * Checks if any two (or more) pairs of start/end * blocks are intersecting. * * @param blockDef * @param blockIdx */ var checkBlocksIntersection = function (blockDef, blockIdx) { if (blockDef.start.test(line)) { blocksStack.push([blockIdx, lineNum, line.trim()]); } if (blockDef.end.test(line) && typeof last(blocksStack) !== "undefined") { if (last(blocksStack)[0] === blockIdx) { blocksStack.pop(); } else { generateMessage({ start: last(blocksStack)[2], pattern: line.trim(), lineNum: last(blocksStack)[1], endLineNum: lineNum, caseNum: 3 }); } } else if (startCount - endCount > 1) { generateMessage({ start: last(blocksStack)[2], pattern: line.trim(), lineNum: last(blocksStack)[1], endLineNum: lineNum, caseNum: 3 }); } }; if (options.parityCheck === true) { blocks.forEach(checkBlocksParity); } if (options.intersectionCheck === true) { blocks.forEach(checkBlocksIntersection); } }
[ "function", "(", "line", ",", "lineNum", ")", "{", "if", "(", "line", ".", "trim", "(", ")", "===", "''", ")", "{", "return", ";", "}", "function", "logAnyDelimiterType", "(", "line", ")", "{", "blocks", ".", "forEach", "(", "function", "(", "blockDef", ",", "blockIdx", ")", "{", "if", "(", "blockDef", ".", "start", ".", "test", "(", "line", ")", "===", "true", ")", "{", "fileStartDelimiters", ".", "push", "(", "[", "blockIdx", ",", "lineNum", ",", "line", ".", "trim", "(", ")", "]", ")", ";", "}", "if", "(", "blockDef", ".", "end", ".", "test", "(", "line", ")", "===", "true", ")", "{", "fileEndDelimiters", ".", "push", "(", "[", "blockIdx", ",", "lineNum", ",", "line", ".", "trim", "(", ")", "]", ")", ";", "}", "}", ")", ";", "}", "logAnyDelimiterType", "(", "line", ")", ";", "var", "startCount", "=", "fileStartDelimiters", ".", "length", ";", "var", "endCount", "=", "fileEndDelimiters", ".", "length", ";", "/**\n * Checks that amount of start/end blocks are equal.\n *\n * @param blockDef\n * @param blockIdx\n */", "var", "checkBlocksParity", "=", "function", "(", "blockDef", ",", "blockIdx", ")", "{", "var", "block", "=", "blockStats", "[", "blockIdx", "]", ";", "/**\n * 'if' for start block check\n */", "if", "(", "blockDef", ".", "start", ".", "test", "(", "line", ")", "===", "true", ")", "{", "block", ".", "lastStartLine", "=", "lineNum", ";", "if", "(", "block", ".", "startCount", ">", "block", ".", "endCount", ")", "{", "generateMessage", "(", "{", "pattern", ":", "line", ".", "trim", "(", ")", ",", "lineNum", ":", "block", ".", "lastStartLine", ",", "caseNum", ":", "1", "}", ")", ";", "}", "block", ".", "startCount", "++", ";", "}", "/**\n * 'if' for end block check\n */", "if", "(", "blockDef", ".", "end", ".", "test", "(", "line", ")", "===", "true", ")", "{", "block", ".", "lastEndLine", "=", "lineNum", ";", "if", "(", "block", ".", "endCount", ">=", "block", ".", "startCount", ")", "{", "generateMessage", "(", "{", "pattern", ":", "line", ".", "trim", "(", ")", ",", "lineNum", ":", "block", ".", "lastEndLine", ",", "caseNum", ":", "2", "}", ")", ";", "}", "block", ".", "endCount", "++", ";", "}", "}", ";", "/**\n * Checks if any two (or more) pairs of start/end\n * blocks are intersecting.\n *\n * @param blockDef\n * @param blockIdx\n */", "var", "checkBlocksIntersection", "=", "function", "(", "blockDef", ",", "blockIdx", ")", "{", "if", "(", "blockDef", ".", "start", ".", "test", "(", "line", ")", ")", "{", "blocksStack", ".", "push", "(", "[", "blockIdx", ",", "lineNum", ",", "line", ".", "trim", "(", ")", "]", ")", ";", "}", "if", "(", "blockDef", ".", "end", ".", "test", "(", "line", ")", "&&", "typeof", "last", "(", "blocksStack", ")", "!==", "\"undefined\"", ")", "{", "if", "(", "last", "(", "blocksStack", ")", "[", "0", "]", "===", "blockIdx", ")", "{", "blocksStack", ".", "pop", "(", ")", ";", "}", "else", "{", "generateMessage", "(", "{", "start", ":", "last", "(", "blocksStack", ")", "[", "2", "]", ",", "pattern", ":", "line", ".", "trim", "(", ")", ",", "lineNum", ":", "last", "(", "blocksStack", ")", "[", "1", "]", ",", "endLineNum", ":", "lineNum", ",", "caseNum", ":", "3", "}", ")", ";", "}", "}", "else", "if", "(", "startCount", "-", "endCount", ">", "1", ")", "{", "generateMessage", "(", "{", "start", ":", "last", "(", "blocksStack", ")", "[", "2", "]", ",", "pattern", ":", "line", ".", "trim", "(", ")", ",", "lineNum", ":", "last", "(", "blocksStack", ")", "[", "1", "]", ",", "endLineNum", ":", "lineNum", ",", "caseNum", ":", "3", "}", ")", ";", "}", "}", ";", "if", "(", "options", ".", "parityCheck", "===", "true", ")", "{", "blocks", ".", "forEach", "(", "checkBlocksParity", ")", ";", "}", "if", "(", "options", ".", "intersectionCheck", "===", "true", ")", "{", "blocks", ".", "forEach", "(", "checkBlocksIntersection", ")", ";", "}", "}" ]
Checks each line of the file. Sub-functions check intersection and parity. @param line @param lineNum
[ "Checks", "each", "line", "of", "the", "file", ".", "Sub", "-", "functions", "check", "intersection", "and", "parity", "." ]
4a84e8bb823b740839df5a6a37d528178f4df906
https://github.com/nuzzio/grunt-strip-code/blob/4a84e8bb823b740839df5a6a37d528178f4df906/tasks/strip_code.js#L227-L340
26,867
uber/potter
cli/builtin/plugin.js
function(cb) { fs.exists(potterHome, function(exists) { if(exists) { cb(null); } else { mkdirp(potterHome, cb); } }); }
javascript
function(cb) { fs.exists(potterHome, function(exists) { if(exists) { cb(null); } else { mkdirp(potterHome, cb); } }); }
[ "function", "(", "cb", ")", "{", "fs", ".", "exists", "(", "potterHome", ",", "function", "(", "exists", ")", "{", "if", "(", "exists", ")", "{", "cb", "(", "null", ")", ";", "}", "else", "{", "mkdirp", "(", "potterHome", ",", "cb", ")", ";", "}", "}", ")", ";", "}" ]
make sure the potter folder exists
[ "make", "sure", "the", "potter", "folder", "exists" ]
ada4ebbb5955996be8eb2cfb4beeac01e3409aea
https://github.com/uber/potter/blob/ada4ebbb5955996be8eb2cfb4beeac01e3409aea/cli/builtin/plugin.js#L65-L73
26,868
uber/potter
cli/builtin/plugin.js
function(cb) { fs.exists(path.join(potterHome, 'package.json'), function(exists) { if(exists) { cb(null); } else { var packagejson = '{"dependencies":{}}'; fs.writeFile(path.join(potterHome, 'package.json'), packagejson, cb); } }); }
javascript
function(cb) { fs.exists(path.join(potterHome, 'package.json'), function(exists) { if(exists) { cb(null); } else { var packagejson = '{"dependencies":{}}'; fs.writeFile(path.join(potterHome, 'package.json'), packagejson, cb); } }); }
[ "function", "(", "cb", ")", "{", "fs", ".", "exists", "(", "path", ".", "join", "(", "potterHome", ",", "'package.json'", ")", ",", "function", "(", "exists", ")", "{", "if", "(", "exists", ")", "{", "cb", "(", "null", ")", ";", "}", "else", "{", "var", "packagejson", "=", "'{\"dependencies\":{}}'", ";", "fs", ".", "writeFile", "(", "path", ".", "join", "(", "potterHome", ",", "'package.json'", ")", ",", "packagejson", ",", "cb", ")", ";", "}", "}", ")", ";", "}" ]
make sure a package.json exists
[ "make", "sure", "a", "package", ".", "json", "exists" ]
ada4ebbb5955996be8eb2cfb4beeac01e3409aea
https://github.com/uber/potter/blob/ada4ebbb5955996be8eb2cfb4beeac01e3409aea/cli/builtin/plugin.js#L75-L84
26,869
steve-gray/swagger-codegen
src/definition-mapper.js
mapDefinitionsFromModel
function mapDefinitionsFromModel(model) { const definitionMap = []; /* istanbul ignore else */ if (model && model.definitions) { debug('Parsing %s definitions', Object.keys(model.definitions).length); for (const definitionName of Object.keys(model.definitions)) { debug(' Reading definition for %s', definitionName); const definitionKey = util.format('#/definitions/%s', definitionName); const currentDef = model.definitions[definitionName]; currentDef.definitionName = definitionName; currentDef.referencePath = definitionKey; definitionMap[definitionKey] = currentDef; } } return definitionMap; }
javascript
function mapDefinitionsFromModel(model) { const definitionMap = []; /* istanbul ignore else */ if (model && model.definitions) { debug('Parsing %s definitions', Object.keys(model.definitions).length); for (const definitionName of Object.keys(model.definitions)) { debug(' Reading definition for %s', definitionName); const definitionKey = util.format('#/definitions/%s', definitionName); const currentDef = model.definitions[definitionName]; currentDef.definitionName = definitionName; currentDef.referencePath = definitionKey; definitionMap[definitionKey] = currentDef; } } return definitionMap; }
[ "function", "mapDefinitionsFromModel", "(", "model", ")", "{", "const", "definitionMap", "=", "[", "]", ";", "/* istanbul ignore else */", "if", "(", "model", "&&", "model", ".", "definitions", ")", "{", "debug", "(", "'Parsing %s definitions'", ",", "Object", ".", "keys", "(", "model", ".", "definitions", ")", ".", "length", ")", ";", "for", "(", "const", "definitionName", "of", "Object", ".", "keys", "(", "model", ".", "definitions", ")", ")", "{", "debug", "(", "' Reading definition for %s'", ",", "definitionName", ")", ";", "const", "definitionKey", "=", "util", ".", "format", "(", "'#/definitions/%s'", ",", "definitionName", ")", ";", "const", "currentDef", "=", "model", ".", "definitions", "[", "definitionName", "]", ";", "currentDef", ".", "definitionName", "=", "definitionName", ";", "currentDef", ".", "referencePath", "=", "definitionKey", ";", "definitionMap", "[", "definitionKey", "]", "=", "currentDef", ";", "}", "}", "return", "definitionMap", ";", "}" ]
Map the definitions from a Swagger model @param {object} model - Swagger model @return - Map of definition name to definition body
[ "Map", "the", "definitions", "from", "a", "Swagger", "model" ]
cd712aa062ed06ba50f37ff30d5c51d50a9819ad
https://github.com/steve-gray/swagger-codegen/blob/cd712aa062ed06ba50f37ff30d5c51d50a9819ad/src/definition-mapper.js#L11-L28
26,870
waterlock/waterlock-local-auth
lib/controllers/actions/reset.js
handleGet
function handleGet(req, res, sails, params){ validateToken(req, res, sails, params); }
javascript
function handleGet(req, res, sails, params){ validateToken(req, res, sails, params); }
[ "function", "handleGet", "(", "req", ",", "res", ",", "sails", ",", "params", ")", "{", "validateToken", "(", "req", ",", "res", ",", "sails", ",", "params", ")", ";", "}" ]
Handles the GET method for this request @param object req the express request object @param object res the express response object @param waterlineDAO User the waterline User dao @param waterlineDAO ResetToken the waterline ResetToken dao @param object params all params for this request
[ "Handles", "the", "GET", "method", "for", "this", "request" ]
5ac2f153e41cefaf91d5f90ffc86b50dab2dde0f
https://github.com/waterlock/waterlock-local-auth/blob/5ac2f153e41cefaf91d5f90ffc86b50dab2dde0f/lib/controllers/actions/reset.js#L50-L52
26,871
waterlock/waterlock-local-auth
lib/controllers/actions/reset.js
handlePost
function handlePost(req, res, sails, params){ var func; if(!_.isUndefined(params.email)){ func = sendEmail; }else if(!_.isUndefined(req.session.resetToken) && req.session.resetToken && !_.isUndefined(params.password)){ func = issuePasswordReset; } if(!_.isUndefined(func)){ func(req, res, sails, params); }else{ res.status(404).json(404); } }
javascript
function handlePost(req, res, sails, params){ var func; if(!_.isUndefined(params.email)){ func = sendEmail; }else if(!_.isUndefined(req.session.resetToken) && req.session.resetToken && !_.isUndefined(params.password)){ func = issuePasswordReset; } if(!_.isUndefined(func)){ func(req, res, sails, params); }else{ res.status(404).json(404); } }
[ "function", "handlePost", "(", "req", ",", "res", ",", "sails", ",", "params", ")", "{", "var", "func", ";", "if", "(", "!", "_", ".", "isUndefined", "(", "params", ".", "email", ")", ")", "{", "func", "=", "sendEmail", ";", "}", "else", "if", "(", "!", "_", ".", "isUndefined", "(", "req", ".", "session", ".", "resetToken", ")", "&&", "req", ".", "session", ".", "resetToken", "&&", "!", "_", ".", "isUndefined", "(", "params", ".", "password", ")", ")", "{", "func", "=", "issuePasswordReset", ";", "}", "if", "(", "!", "_", ".", "isUndefined", "(", "func", ")", ")", "{", "func", "(", "req", ",", "res", ",", "sails", ",", "params", ")", ";", "}", "else", "{", "res", ".", "status", "(", "404", ")", ".", "json", "(", "404", ")", ";", "}", "}" ]
Handles the POST method for this request @param object req the express request object @param object res the express response object @param waterlineDAO User the waterline User dao @param waterlineDAO ResetToken the waterline ResetToken dao @param object params all params for this request
[ "Handles", "the", "POST", "method", "for", "this", "request" ]
5ac2f153e41cefaf91d5f90ffc86b50dab2dde0f
https://github.com/waterlock/waterlock-local-auth/blob/5ac2f153e41cefaf91d5f90ffc86b50dab2dde0f/lib/controllers/actions/reset.js#L62-L79
26,872
waterlock/waterlock-local-auth
lib/controllers/actions/reset.js
sendEmail
function sendEmail(req, res, sails, params){ sails.models.auth.findOne({email: params.email}).populate('user').exec(function(err, a){ if(a){ sails.models.resettoken.create({owner: a.id}).exec(function(err, t){ if(err){ return res.serverError(err); } sails.models.auth.update({id: a.id}, {resetToken: t.id}).exec(function(err){ if(err){ return res.serverError(err); } res.json(200); }); }); } else { return res.forbidden('Email not found'); } }); }
javascript
function sendEmail(req, res, sails, params){ sails.models.auth.findOne({email: params.email}).populate('user').exec(function(err, a){ if(a){ sails.models.resettoken.create({owner: a.id}).exec(function(err, t){ if(err){ return res.serverError(err); } sails.models.auth.update({id: a.id}, {resetToken: t.id}).exec(function(err){ if(err){ return res.serverError(err); } res.json(200); }); }); } else { return res.forbidden('Email not found'); } }); }
[ "function", "sendEmail", "(", "req", ",", "res", ",", "sails", ",", "params", ")", "{", "sails", ".", "models", ".", "auth", ".", "findOne", "(", "{", "email", ":", "params", ".", "email", "}", ")", ".", "populate", "(", "'user'", ")", ".", "exec", "(", "function", "(", "err", ",", "a", ")", "{", "if", "(", "a", ")", "{", "sails", ".", "models", ".", "resettoken", ".", "create", "(", "{", "owner", ":", "a", ".", "id", "}", ")", ".", "exec", "(", "function", "(", "err", ",", "t", ")", "{", "if", "(", "err", ")", "{", "return", "res", ".", "serverError", "(", "err", ")", ";", "}", "sails", ".", "models", ".", "auth", ".", "update", "(", "{", "id", ":", "a", ".", "id", "}", ",", "{", "resetToken", ":", "t", ".", "id", "}", ")", ".", "exec", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "return", "res", ".", "serverError", "(", "err", ")", ";", "}", "res", ".", "json", "(", "200", ")", ";", "}", ")", ";", "}", ")", ";", "}", "else", "{", "return", "res", ".", "forbidden", "(", "'Email not found'", ")", ";", "}", "}", ")", ";", "}" ]
Begins the reset process by creating a new reset token and sending an email to the user @param object req the express request object @param object res the express response object @param waterlineDAO User the waterline User dao @param waterlineDAO ResetToken the waterline ResetToken dao @param object params all params for this request
[ "Begins", "the", "reset", "process", "by", "creating", "a", "new", "reset", "token", "and", "sending", "an", "email", "to", "the", "user" ]
5ac2f153e41cefaf91d5f90ffc86b50dab2dde0f
https://github.com/waterlock/waterlock-local-auth/blob/5ac2f153e41cefaf91d5f90ffc86b50dab2dde0f/lib/controllers/actions/reset.js#L90-L108
26,873
waterlock/waterlock-local-auth
lib/controllers/actions/reset.js
validateToken
function validateToken(req, res, sails, params){ var config = wl.config; var authConfig = wl.authConfig; if(params.token){ try{ // decode the token var _token = jwt.decode(params.token, config.jsonWebTokens.secret); // set the time of the request var _reqTime = Date.now(); // If token is expired if(_token.exp <= _reqTime){ return res.forbidden('Your token is expired.'); } // If token is early if(_reqTime <= _token.nbf){ return res.forbidden('This token is early.'); } // If audience doesn't match if(config.jsonWebTokens.audience !== _token.aud){ return res.forbidden('This token cannot be accepted for this domain.'); } // If the subject doesn't match if('password reset' !== _token.sub){ return res.forbidden('This token cannot be used for this request.'); } sails.models.auth.findOne(_token.iss).populate('resetToken').exec(function(err, auth){ if(typeof auth.resetToken === 'undefined' || params.token !== auth.resetToken.token){ return res.forbidden('This token cannot be used.'); } req.session.resetToken = auth.resetToken; if(authConfig.passwordReset.mail.forwardUrl){ res.redirect(authConfig.passwordReset.mail.forwardUrl + '?token=' + auth.resetToken.token); }else{ res.json(200); } }); } catch(err){ return res.serverError(err); } }else{ //TODO limit attempts? req.session.resetToken = false; res.forbidden(); } }
javascript
function validateToken(req, res, sails, params){ var config = wl.config; var authConfig = wl.authConfig; if(params.token){ try{ // decode the token var _token = jwt.decode(params.token, config.jsonWebTokens.secret); // set the time of the request var _reqTime = Date.now(); // If token is expired if(_token.exp <= _reqTime){ return res.forbidden('Your token is expired.'); } // If token is early if(_reqTime <= _token.nbf){ return res.forbidden('This token is early.'); } // If audience doesn't match if(config.jsonWebTokens.audience !== _token.aud){ return res.forbidden('This token cannot be accepted for this domain.'); } // If the subject doesn't match if('password reset' !== _token.sub){ return res.forbidden('This token cannot be used for this request.'); } sails.models.auth.findOne(_token.iss).populate('resetToken').exec(function(err, auth){ if(typeof auth.resetToken === 'undefined' || params.token !== auth.resetToken.token){ return res.forbidden('This token cannot be used.'); } req.session.resetToken = auth.resetToken; if(authConfig.passwordReset.mail.forwardUrl){ res.redirect(authConfig.passwordReset.mail.forwardUrl + '?token=' + auth.resetToken.token); }else{ res.json(200); } }); } catch(err){ return res.serverError(err); } }else{ //TODO limit attempts? req.session.resetToken = false; res.forbidden(); } }
[ "function", "validateToken", "(", "req", ",", "res", ",", "sails", ",", "params", ")", "{", "var", "config", "=", "wl", ".", "config", ";", "var", "authConfig", "=", "wl", ".", "authConfig", ";", "if", "(", "params", ".", "token", ")", "{", "try", "{", "// decode the token", "var", "_token", "=", "jwt", ".", "decode", "(", "params", ".", "token", ",", "config", ".", "jsonWebTokens", ".", "secret", ")", ";", "// set the time of the request", "var", "_reqTime", "=", "Date", ".", "now", "(", ")", ";", "// If token is expired", "if", "(", "_token", ".", "exp", "<=", "_reqTime", ")", "{", "return", "res", ".", "forbidden", "(", "'Your token is expired.'", ")", ";", "}", "// If token is early", "if", "(", "_reqTime", "<=", "_token", ".", "nbf", ")", "{", "return", "res", ".", "forbidden", "(", "'This token is early.'", ")", ";", "}", "// If audience doesn't match", "if", "(", "config", ".", "jsonWebTokens", ".", "audience", "!==", "_token", ".", "aud", ")", "{", "return", "res", ".", "forbidden", "(", "'This token cannot be accepted for this domain.'", ")", ";", "}", "// If the subject doesn't match", "if", "(", "'password reset'", "!==", "_token", ".", "sub", ")", "{", "return", "res", ".", "forbidden", "(", "'This token cannot be used for this request.'", ")", ";", "}", "sails", ".", "models", ".", "auth", ".", "findOne", "(", "_token", ".", "iss", ")", ".", "populate", "(", "'resetToken'", ")", ".", "exec", "(", "function", "(", "err", ",", "auth", ")", "{", "if", "(", "typeof", "auth", ".", "resetToken", "===", "'undefined'", "||", "params", ".", "token", "!==", "auth", ".", "resetToken", ".", "token", ")", "{", "return", "res", ".", "forbidden", "(", "'This token cannot be used.'", ")", ";", "}", "req", ".", "session", ".", "resetToken", "=", "auth", ".", "resetToken", ";", "if", "(", "authConfig", ".", "passwordReset", ".", "mail", ".", "forwardUrl", ")", "{", "res", ".", "redirect", "(", "authConfig", ".", "passwordReset", ".", "mail", ".", "forwardUrl", "+", "'?token='", "+", "auth", ".", "resetToken", ".", "token", ")", ";", "}", "else", "{", "res", ".", "json", "(", "200", ")", ";", "}", "}", ")", ";", "}", "catch", "(", "err", ")", "{", "return", "res", ".", "serverError", "(", "err", ")", ";", "}", "}", "else", "{", "//TODO limit attempts?", "req", ".", "session", ".", "resetToken", "=", "false", ";", "res", ".", "forbidden", "(", ")", ";", "}", "}" ]
validates a users token and redirects them to the new url if provided @param object req the express request object @param object res the express response object @param waterlineDAO User the waterline User dao @param waterlineDAO ResetToken the waterline ResetToken dao @param object params all params for this request
[ "validates", "a", "users", "token", "and", "redirects", "them", "to", "the", "new", "url", "if", "provided" ]
5ac2f153e41cefaf91d5f90ffc86b50dab2dde0f
https://github.com/waterlock/waterlock-local-auth/blob/5ac2f153e41cefaf91d5f90ffc86b50dab2dde0f/lib/controllers/actions/reset.js#L152-L206
26,874
knpwrs/babel-plugin-remove-webpack
src/index.js
isMemberCall
function isMemberCall({ callee }, obj, prop) { return callee.type === 'MemberExpression' && callee.object.name === obj && callee.property.name === prop; }
javascript
function isMemberCall({ callee }, obj, prop) { return callee.type === 'MemberExpression' && callee.object.name === obj && callee.property.name === prop; }
[ "function", "isMemberCall", "(", "{", "callee", "}", ",", "obj", ",", "prop", ")", "{", "return", "callee", ".", "type", "===", "'MemberExpression'", "&&", "callee", ".", "object", ".", "name", "===", "obj", "&&", "callee", ".", "property", ".", "name", "===", "prop", ";", "}" ]
Determines if a given node represents a call to prop on object. @param {Object} node The ast node. @param {string} obj The object identity. @param {string} prop The property identity. @return {Boolean} `true` if node represents `obj[prop]()`. `false` otherwise.
[ "Determines", "if", "a", "given", "node", "represents", "a", "call", "to", "prop", "on", "object", "." ]
dc239cf44d9f857eafc46ead9446205aede32409
https://github.com/knpwrs/babel-plugin-remove-webpack/blob/dc239cf44d9f857eafc46ead9446205aede32409/src/index.js#L8-L12
26,875
AmpersandJS/ampersand-collection
ampersand-collection.js
function () { var list = slice.call(this.indexes || []); var i = 0; list.push(this.mainIndex); list.push('cid'); var l = list.length; this.models = []; this._indexes = {}; for (; i < l; i++) { this._indexes[list[i]] = {}; } }
javascript
function () { var list = slice.call(this.indexes || []); var i = 0; list.push(this.mainIndex); list.push('cid'); var l = list.length; this.models = []; this._indexes = {}; for (; i < l; i++) { this._indexes[list[i]] = {}; } }
[ "function", "(", ")", "{", "var", "list", "=", "slice", ".", "call", "(", "this", ".", "indexes", "||", "[", "]", ")", ";", "var", "i", "=", "0", ";", "list", ".", "push", "(", "this", ".", "mainIndex", ")", ";", "list", ".", "push", "(", "'cid'", ")", ";", "var", "l", "=", "list", ".", "length", ";", "this", ".", "models", "=", "[", "]", ";", "this", ".", "_indexes", "=", "{", "}", ";", "for", "(", ";", "i", "<", "l", ";", "i", "++", ")", "{", "this", ".", "_indexes", "[", "list", "[", "i", "]", "]", "=", "{", "}", ";", "}", "}" ]
Private method to reset all internal state. Called when the collection is first initialized or reset.
[ "Private", "method", "to", "reset", "all", "internal", "state", ".", "Called", "when", "the", "collection", "is", "first", "initialized", "or", "reset", "." ]
6cf9b8e7077363af6618c51133b46bb8996caa44
https://github.com/AmpersandJS/ampersand-collection/blob/6cf9b8e7077363af6618c51133b46bb8996caa44/ampersand-collection.js#L269-L280
26,876
steve-gray/swagger-codegen
src/handlebars-engine.js
handlebarsEngine
function handlebarsEngine(taskOptions) { debug('Initializing new instance of hbs'); const handlebars = hbs.create(); /* istanbul ignore else */ if (taskOptions.helpers) { for (const helper of Object.keys(taskOptions.helpers)) { debug(' Registering helper: %s', helper); handlebars.registerHelper(helper, taskOptions.helpers[helper]); } } return handlebars; }
javascript
function handlebarsEngine(taskOptions) { debug('Initializing new instance of hbs'); const handlebars = hbs.create(); /* istanbul ignore else */ if (taskOptions.helpers) { for (const helper of Object.keys(taskOptions.helpers)) { debug(' Registering helper: %s', helper); handlebars.registerHelper(helper, taskOptions.helpers[helper]); } } return handlebars; }
[ "function", "handlebarsEngine", "(", "taskOptions", ")", "{", "debug", "(", "'Initializing new instance of hbs'", ")", ";", "const", "handlebars", "=", "hbs", ".", "create", "(", ")", ";", "/* istanbul ignore else */", "if", "(", "taskOptions", ".", "helpers", ")", "{", "for", "(", "const", "helper", "of", "Object", ".", "keys", "(", "taskOptions", ".", "helpers", ")", ")", "{", "debug", "(", "' Registering helper: %s'", ",", "helper", ")", ";", "handlebars", ".", "registerHelper", "(", "helper", ",", "taskOptions", ".", "helpers", "[", "helper", "]", ")", ";", "}", "}", "return", "handlebars", ";", "}" ]
The handlebarsEngine loads a new instance of handlebars and applies the task-specific helper functions
[ "The", "handlebarsEngine", "loads", "a", "new", "instance", "of", "handlebars", "and", "applies", "the", "task", "-", "specific", "helper", "functions" ]
cd712aa062ed06ba50f37ff30d5c51d50a9819ad
https://github.com/steve-gray/swagger-codegen/blob/cd712aa062ed06ba50f37ff30d5c51d50a9819ad/src/handlebars-engine.js#L10-L23
26,877
steve-gray/swagger-codegen
src/handlebars-helpers.js
arrayContainsItem
function arrayContainsItem(array, value, options) { if (array && _.indexOf(array, value) >= 0) { return options.fn(this); } return options.inverse(this); }
javascript
function arrayContainsItem(array, value, options) { if (array && _.indexOf(array, value) >= 0) { return options.fn(this); } return options.inverse(this); }
[ "function", "arrayContainsItem", "(", "array", ",", "value", ",", "options", ")", "{", "if", "(", "array", "&&", "_", ".", "indexOf", "(", "array", ",", "value", ")", ">=", "0", ")", "{", "return", "options", ".", "fn", "(", "this", ")", ";", "}", "return", "options", ".", "inverse", "(", "this", ")", ";", "}" ]
Does an array contain a value? @param {object} array - Array to scan @param {object} value - Value to find @param {object} options - Handlebars options. @returns {string} - Result
[ "Does", "an", "array", "contain", "a", "value?" ]
cd712aa062ed06ba50f37ff30d5c51d50a9819ad
https://github.com/steve-gray/swagger-codegen/blob/cd712aa062ed06ba50f37ff30d5c51d50a9819ad/src/handlebars-helpers.js#L14-L20
26,878
steve-gray/swagger-codegen
src/handlebars-helpers.js
compareValues
function compareValues(lvalue, operator, rvalue, options) { const operators = { '==': function compareEqual(l, r) { return l === r; }, '===': function compareIdentical(l, r) { return l === r; }, '!=': function compareNotEqual(l, r) { return l !== r; }, '<': function compareLessThan(l, r) { return l < r; }, '>': function compareGreaterThan(l, r) { return l > r; }, '<=': function compareLessThanEqual(l, r) { return l <= r; }, '>=': function compareGreaterThanEqual(l, r) { return l >= r; }, typeof: function compareTypeOf(l, r) { return typeof l === r; }, }; /* istanbul ignore if */ if (!operators[operator]) { throw new Error(util.format('Unknown compare operator: %s', operator)); } const result = operators[operator](lvalue, rvalue); if (result) { return options.fn(this); } return options.inverse(this); }
javascript
function compareValues(lvalue, operator, rvalue, options) { const operators = { '==': function compareEqual(l, r) { return l === r; }, '===': function compareIdentical(l, r) { return l === r; }, '!=': function compareNotEqual(l, r) { return l !== r; }, '<': function compareLessThan(l, r) { return l < r; }, '>': function compareGreaterThan(l, r) { return l > r; }, '<=': function compareLessThanEqual(l, r) { return l <= r; }, '>=': function compareGreaterThanEqual(l, r) { return l >= r; }, typeof: function compareTypeOf(l, r) { return typeof l === r; }, }; /* istanbul ignore if */ if (!operators[operator]) { throw new Error(util.format('Unknown compare operator: %s', operator)); } const result = operators[operator](lvalue, rvalue); if (result) { return options.fn(this); } return options.inverse(this); }
[ "function", "compareValues", "(", "lvalue", ",", "operator", ",", "rvalue", ",", "options", ")", "{", "const", "operators", "=", "{", "'=='", ":", "function", "compareEqual", "(", "l", ",", "r", ")", "{", "return", "l", "===", "r", ";", "}", ",", "'==='", ":", "function", "compareIdentical", "(", "l", ",", "r", ")", "{", "return", "l", "===", "r", ";", "}", ",", "'!='", ":", "function", "compareNotEqual", "(", "l", ",", "r", ")", "{", "return", "l", "!==", "r", ";", "}", ",", "'<'", ":", "function", "compareLessThan", "(", "l", ",", "r", ")", "{", "return", "l", "<", "r", ";", "}", ",", "'>'", ":", "function", "compareGreaterThan", "(", "l", ",", "r", ")", "{", "return", "l", ">", "r", ";", "}", ",", "'<='", ":", "function", "compareLessThanEqual", "(", "l", ",", "r", ")", "{", "return", "l", "<=", "r", ";", "}", ",", "'>='", ":", "function", "compareGreaterThanEqual", "(", "l", ",", "r", ")", "{", "return", "l", ">=", "r", ";", "}", ",", "typeof", ":", "function", "compareTypeOf", "(", "l", ",", "r", ")", "{", "return", "typeof", "l", "===", "r", ";", "}", ",", "}", ";", "/* istanbul ignore if */", "if", "(", "!", "operators", "[", "operator", "]", ")", "{", "throw", "new", "Error", "(", "util", ".", "format", "(", "'Unknown compare operator: %s'", ",", "operator", ")", ")", ";", "}", "const", "result", "=", "operators", "[", "operator", "]", "(", "lvalue", ",", "rvalue", ")", ";", "if", "(", "result", ")", "{", "return", "options", ".", "fn", "(", "this", ")", ";", "}", "return", "options", ".", "inverse", "(", "this", ")", ";", "}" ]
Compare two values with a predicate to determine some equivelence relation. @remarks Supported operators are ==, ===, !=, <, >, <= and >= @param {object} lvalue - Left operand @param {object} operator - Comparison operators @param {object} rvalue - Right operand @param {object} options - Handlebars options. @returns {string} - Result
[ "Compare", "two", "values", "with", "a", "predicate", "to", "determine", "some", "equivelence", "relation", "." ]
cd712aa062ed06ba50f37ff30d5c51d50a9819ad
https://github.com/steve-gray/swagger-codegen/blob/cd712aa062ed06ba50f37ff30d5c51d50a9819ad/src/handlebars-helpers.js#L32-L54
26,879
steve-gray/swagger-codegen
src/handlebars-helpers.js
lowercaseFirstLetter
function lowercaseFirstLetter(options) { const string = options.fn(this); return string.charAt(0).toLowerCase() + string.slice(1); }
javascript
function lowercaseFirstLetter(options) { const string = options.fn(this); return string.charAt(0).toLowerCase() + string.slice(1); }
[ "function", "lowercaseFirstLetter", "(", "options", ")", "{", "const", "string", "=", "options", ".", "fn", "(", "this", ")", ";", "return", "string", ".", "charAt", "(", "0", ")", ".", "toLowerCase", "(", ")", "+", "string", ".", "slice", "(", "1", ")", ";", "}" ]
Drop-case the first letter of a string @param {object} options - Handlebars options. @returns {string} - Original string with lowercased first letter.
[ "Drop", "-", "case", "the", "first", "letter", "of", "a", "string" ]
cd712aa062ed06ba50f37ff30d5c51d50a9819ad
https://github.com/steve-gray/swagger-codegen/blob/cd712aa062ed06ba50f37ff30d5c51d50a9819ad/src/handlebars-helpers.js#L61-L64
26,880
steve-gray/swagger-codegen
src/handlebars-helpers.js
capSplitAndJoin
function capSplitAndJoin(joiner, options) { const string = options.fn(this); const members = string.split(/(?=[A-Z])/); return members.join(joiner); }
javascript
function capSplitAndJoin(joiner, options) { const string = options.fn(this); const members = string.split(/(?=[A-Z])/); return members.join(joiner); }
[ "function", "capSplitAndJoin", "(", "joiner", ",", "options", ")", "{", "const", "string", "=", "options", ".", "fn", "(", "this", ")", ";", "const", "members", "=", "string", ".", "split", "(", "/", "(?=[A-Z])", "/", ")", ";", "return", "members", ".", "join", "(", "joiner", ")", ";", "}" ]
Split a string by capital letters and then re-join by another. @param {string} joiner - String to join with @param {object} options - Handlebars options. @return {string} - Handlebars result
[ "Split", "a", "string", "by", "capital", "letters", "and", "then", "re", "-", "join", "by", "another", "." ]
cd712aa062ed06ba50f37ff30d5c51d50a9819ad
https://github.com/steve-gray/swagger-codegen/blob/cd712aa062ed06ba50f37ff30d5c51d50a9819ad/src/handlebars-helpers.js#L81-L85
26,881
steve-gray/swagger-codegen
src/handlebars-helpers.js
propertyValueExtract
function propertyValueExtract(context, name, propName, options) { if (context[name] === undefined || context[name] === null) { return options.inverse(context); } this[propName] = context[name]; /* eslint-disable no-param-reassign */ context[propName] = context[name]; /* eslint-enable no-param-reassign */ return options.fn(context); }
javascript
function propertyValueExtract(context, name, propName, options) { if (context[name] === undefined || context[name] === null) { return options.inverse(context); } this[propName] = context[name]; /* eslint-disable no-param-reassign */ context[propName] = context[name]; /* eslint-enable no-param-reassign */ return options.fn(context); }
[ "function", "propertyValueExtract", "(", "context", ",", "name", ",", "propName", ",", "options", ")", "{", "if", "(", "context", "[", "name", "]", "===", "undefined", "||", "context", "[", "name", "]", "===", "null", ")", "{", "return", "options", ".", "inverse", "(", "context", ")", ";", "}", "this", "[", "propName", "]", "=", "context", "[", "name", "]", ";", "/* eslint-disable no-param-reassign */", "context", "[", "propName", "]", "=", "context", "[", "name", "]", ";", "/* eslint-enable no-param-reassign */", "return", "options", ".", "fn", "(", "context", ")", ";", "}" ]
Extract the name of a property with a handlebars-unfriendly name, such as hyphenated names. Sets the property called name into context.propName if it exists and excutes the first block with context value. Executes inverse block otherwise. @param {object} context - Object to look in. @param {string} name - Property name @param {string} propName - New target property name. @param {object} options - Handlebars options. @return {string} - Handlebars result
[ "Extract", "the", "name", "of", "a", "property", "with", "a", "handlebars", "-", "unfriendly", "name", "such", "as", "hyphenated", "names", ".", "Sets", "the", "property", "called", "name", "into", "context", ".", "propName", "if", "it", "exists", "and", "excutes", "the", "first", "block", "with", "context", "value", "." ]
cd712aa062ed06ba50f37ff30d5c51d50a9819ad
https://github.com/steve-gray/swagger-codegen/blob/cd712aa062ed06ba50f37ff30d5c51d50a9819ad/src/handlebars-helpers.js#L100-L109
26,882
steve-gray/swagger-codegen
src/handlebars-helpers.js
uppercaseFirstLetter
function uppercaseFirstLetter(options) { const string = options.fn(this); return string.charAt(0).toUpperCase() + string.slice(1); }
javascript
function uppercaseFirstLetter(options) { const string = options.fn(this); return string.charAt(0).toUpperCase() + string.slice(1); }
[ "function", "uppercaseFirstLetter", "(", "options", ")", "{", "const", "string", "=", "options", ".", "fn", "(", "this", ")", ";", "return", "string", ".", "charAt", "(", "0", ")", ".", "toUpperCase", "(", ")", "+", "string", ".", "slice", "(", "1", ")", ";", "}" ]
Capitalize the first letter of a string @param {object} options - Handlebars options. @returns {string} - Original string with capitalized first letter.
[ "Capitalize", "the", "first", "letter", "of", "a", "string" ]
cd712aa062ed06ba50f37ff30d5c51d50a9819ad
https://github.com/steve-gray/swagger-codegen/blob/cd712aa062ed06ba50f37ff30d5c51d50a9819ad/src/handlebars-helpers.js#L125-L128
26,883
pschroen/rollup-plugin-bundleutils
index.js
regex
function regex(replacements) { return { name: 'regex', renderChunk(code) { const magicString = new MagicString(code); let hasReplacements = false; replacements.forEach(replacement => { let [find, replace = ''] = replacement; if (typeof find === 'string') find = new RegExp(find); if (!find.global) find = new RegExp(find.source, 'g' + String(find).split('/').pop()); let match, start, end; while ((match = find.exec(code))) { hasReplacements = true; start = match.index; end = start + match[0].length; magicString.overwrite(start, end, typeof replace === 'function' ? replace.apply(null, match) || '' : replace.replace(/\$(\d+)/, (str, index) => match[index])); } }); if (!hasReplacements) return null; return { code: magicString.toString(), map: magicString.generateMap({ hires: true }) }; } }; }
javascript
function regex(replacements) { return { name: 'regex', renderChunk(code) { const magicString = new MagicString(code); let hasReplacements = false; replacements.forEach(replacement => { let [find, replace = ''] = replacement; if (typeof find === 'string') find = new RegExp(find); if (!find.global) find = new RegExp(find.source, 'g' + String(find).split('/').pop()); let match, start, end; while ((match = find.exec(code))) { hasReplacements = true; start = match.index; end = start + match[0].length; magicString.overwrite(start, end, typeof replace === 'function' ? replace.apply(null, match) || '' : replace.replace(/\$(\d+)/, (str, index) => match[index])); } }); if (!hasReplacements) return null; return { code: magicString.toString(), map: magicString.generateMap({ hires: true }) }; } }; }
[ "function", "regex", "(", "replacements", ")", "{", "return", "{", "name", ":", "'regex'", ",", "renderChunk", "(", "code", ")", "{", "const", "magicString", "=", "new", "MagicString", "(", "code", ")", ";", "let", "hasReplacements", "=", "false", ";", "replacements", ".", "forEach", "(", "replacement", "=>", "{", "let", "[", "find", ",", "replace", "=", "''", "]", "=", "replacement", ";", "if", "(", "typeof", "find", "===", "'string'", ")", "find", "=", "new", "RegExp", "(", "find", ")", ";", "if", "(", "!", "find", ".", "global", ")", "find", "=", "new", "RegExp", "(", "find", ".", "source", ",", "'g'", "+", "String", "(", "find", ")", ".", "split", "(", "'/'", ")", ".", "pop", "(", ")", ")", ";", "let", "match", ",", "start", ",", "end", ";", "while", "(", "(", "match", "=", "find", ".", "exec", "(", "code", ")", ")", ")", "{", "hasReplacements", "=", "true", ";", "start", "=", "match", ".", "index", ";", "end", "=", "start", "+", "match", "[", "0", "]", ".", "length", ";", "magicString", ".", "overwrite", "(", "start", ",", "end", ",", "typeof", "replace", "===", "'function'", "?", "replace", ".", "apply", "(", "null", ",", "match", ")", "||", "''", ":", "replace", ".", "replace", "(", "/", "\\$(\\d+)", "/", ",", "(", "str", ",", "index", ")", "=>", "match", "[", "index", "]", ")", ")", ";", "}", "}", ")", ";", "if", "(", "!", "hasReplacements", ")", "return", "null", ";", "return", "{", "code", ":", "magicString", ".", "toString", "(", ")", ",", "map", ":", "magicString", ".", "generateMap", "(", "{", "hires", ":", "true", "}", ")", "}", ";", "}", "}", ";", "}" ]
regex replace after tree shaking
[ "regex", "replace", "after", "tree", "shaking" ]
c9d044af0f8cab00cea0170b7a14028f5d2e3980
https://github.com/pschroen/rollup-plugin-bundleutils/blob/c9d044af0f8cab00cea0170b7a14028f5d2e3980/index.js#L26-L58
26,884
pschroen/rollup-plugin-bundleutils
index.js
babel
function babel(options = {}) { return { name: 'babel', renderChunk(code) { options.presets = [['env', { modules: false }]]; options.sourceMaps = true; return transform(code, options); } }; }
javascript
function babel(options = {}) { return { name: 'babel', renderChunk(code) { options.presets = [['env', { modules: false }]]; options.sourceMaps = true; return transform(code, options); } }; }
[ "function", "babel", "(", "options", "=", "{", "}", ")", "{", "return", "{", "name", ":", "'babel'", ",", "renderChunk", "(", "code", ")", "{", "options", ".", "presets", "=", "[", "[", "'env'", ",", "{", "modules", ":", "false", "}", "]", "]", ";", "options", ".", "sourceMaps", "=", "true", ";", "return", "transform", "(", "code", ",", "options", ")", ";", "}", "}", ";", "}" ]
transpile after tree shaking
[ "transpile", "after", "tree", "shaking" ]
c9d044af0f8cab00cea0170b7a14028f5d2e3980
https://github.com/pschroen/rollup-plugin-bundleutils/blob/c9d044af0f8cab00cea0170b7a14028f5d2e3980/index.js#L61-L71
26,885
pschroen/rollup-plugin-bundleutils
index.js
uglify
function uglify(options = {}) { return { name: 'uglify', renderChunk(code) { options.sourceMap = true; return minify(code, options); } }; }
javascript
function uglify(options = {}) { return { name: 'uglify', renderChunk(code) { options.sourceMap = true; return minify(code, options); } }; }
[ "function", "uglify", "(", "options", "=", "{", "}", ")", "{", "return", "{", "name", ":", "'uglify'", ",", "renderChunk", "(", "code", ")", "{", "options", ".", "sourceMap", "=", "true", ";", "return", "minify", "(", "code", ",", "options", ")", ";", "}", "}", ";", "}" ]
minify after tree shaking
[ "minify", "after", "tree", "shaking" ]
c9d044af0f8cab00cea0170b7a14028f5d2e3980
https://github.com/pschroen/rollup-plugin-bundleutils/blob/c9d044af0f8cab00cea0170b7a14028f5d2e3980/index.js#L74-L83
26,886
nelson-ai/semantic-graphql
src/graphql/getGraphqlName.js
getGraphqlName
function getGraphqlName(g, iri) { const { prefixes } = g.config; const localName = getIriLocalName(iri); const namespaceIri = iri.slice(0, -localName.length); const prefix = Object.keys(prefixes).find(key => prefixes[key] === namespaceIri) || ''; return capitalize(prefix + localName).replace(/\W/g, '_'); }
javascript
function getGraphqlName(g, iri) { const { prefixes } = g.config; const localName = getIriLocalName(iri); const namespaceIri = iri.slice(0, -localName.length); const prefix = Object.keys(prefixes).find(key => prefixes[key] === namespaceIri) || ''; return capitalize(prefix + localName).replace(/\W/g, '_'); }
[ "function", "getGraphqlName", "(", "g", ",", "iri", ")", "{", "const", "{", "prefixes", "}", "=", "g", ".", "config", ";", "const", "localName", "=", "getIriLocalName", "(", "iri", ")", ";", "const", "namespaceIri", "=", "iri", ".", "slice", "(", "0", ",", "-", "localName", ".", "length", ")", ";", "const", "prefix", "=", "Object", ".", "keys", "(", "prefixes", ")", ".", "find", "(", "key", "=>", "prefixes", "[", "key", "]", "===", "namespaceIri", ")", "||", "''", ";", "return", "capitalize", "(", "prefix", "+", "localName", ")", ".", "replace", "(", "/", "\\W", "/", "g", ",", "'_'", ")", ";", "}" ]
GraphQL-safe name for GraphQL types
[ "GraphQL", "-", "safe", "name", "for", "GraphQL", "types" ]
d2e678d898ce48435ebafa7b7603fe0e76a92f8c
https://github.com/nelson-ai/semantic-graphql/blob/d2e678d898ce48435ebafa7b7603fe0e76a92f8c/src/graphql/getGraphqlName.js#L6-L14
26,887
nelson-ai/semantic-graphql
src/requireGraphqlRelay.js
requireGraphqlRelay
function requireGraphqlRelay() { if (graphqlRelay) return graphqlRelay; try { graphqlRelay = require('graphql-relay'); } catch (ex) { // Nothing } if (!graphqlRelay) { // Go up until graphql-relay is found // Inspired by https://www.npmjs.com/package/parent-require for (let parent = module.parent; parent && !graphqlRelay; parent = parent.parent) { try { graphqlRelay = parent.require('graphql-relay'); } catch (ex) { // Nothing } } // No pity if (!graphqlRelay) throw new Error('semantic-graphql was not able to find "graphql-relay" as a dependency of your project. Run "npm install graphql-relay" or set the "relay" option to false.'); } return graphqlRelay; }
javascript
function requireGraphqlRelay() { if (graphqlRelay) return graphqlRelay; try { graphqlRelay = require('graphql-relay'); } catch (ex) { // Nothing } if (!graphqlRelay) { // Go up until graphql-relay is found // Inspired by https://www.npmjs.com/package/parent-require for (let parent = module.parent; parent && !graphqlRelay; parent = parent.parent) { try { graphqlRelay = parent.require('graphql-relay'); } catch (ex) { // Nothing } } // No pity if (!graphqlRelay) throw new Error('semantic-graphql was not able to find "graphql-relay" as a dependency of your project. Run "npm install graphql-relay" or set the "relay" option to false.'); } return graphqlRelay; }
[ "function", "requireGraphqlRelay", "(", ")", "{", "if", "(", "graphqlRelay", ")", "return", "graphqlRelay", ";", "try", "{", "graphqlRelay", "=", "require", "(", "'graphql-relay'", ")", ";", "}", "catch", "(", "ex", ")", "{", "// Nothing", "}", "if", "(", "!", "graphqlRelay", ")", "{", "// Go up until graphql-relay is found", "// Inspired by https://www.npmjs.com/package/parent-require", "for", "(", "let", "parent", "=", "module", ".", "parent", ";", "parent", "&&", "!", "graphqlRelay", ";", "parent", "=", "parent", ".", "parent", ")", "{", "try", "{", "graphqlRelay", "=", "parent", ".", "require", "(", "'graphql-relay'", ")", ";", "}", "catch", "(", "ex", ")", "{", "// Nothing", "}", "}", "// No pity", "if", "(", "!", "graphqlRelay", ")", "throw", "new", "Error", "(", "'semantic-graphql was not able to find \"graphql-relay\" as a dependency of your project. Run \"npm install graphql-relay\" or set the \"relay\" option to false.'", ")", ";", "}", "return", "graphqlRelay", ";", "}" ]
optionalPeerDependencies still don't exist, so graphql-relay is a ghost dep let's find it
[ "optionalPeerDependencies", "still", "don", "t", "exist", "so", "graphql", "-", "relay", "is", "a", "ghost", "dep", "let", "s", "find", "it" ]
d2e678d898ce48435ebafa7b7603fe0e76a92f8c
https://github.com/nelson-ai/semantic-graphql/blob/d2e678d898ce48435ebafa7b7603fe0e76a92f8c/src/requireGraphqlRelay.js#L5-L32
26,888
demmer/node-cassandra-native-driver
lib/client.js
parseArgs
function parseArgs() { var args = Array.prototype.slice.call(arguments); var ret = { query: args[0], params: [], options: {}, callback: undefined, endCallback: undefined }; args.shift(); // If specified, params must be an array if (args[0] instanceof Array) { ret.params = args[0]; args.shift(); } // If specified, options must be a non-Function object if (! (args[0] instanceof Function)) { ret.options = args[0]; args.shift(); } ret.callback = args[0]; ret.endCallback = args[1]; if (ret.query === undefined || ret.callback === undefined) { throw new Error('query and callback are required'); } return ret; }
javascript
function parseArgs() { var args = Array.prototype.slice.call(arguments); var ret = { query: args[0], params: [], options: {}, callback: undefined, endCallback: undefined }; args.shift(); // If specified, params must be an array if (args[0] instanceof Array) { ret.params = args[0]; args.shift(); } // If specified, options must be a non-Function object if (! (args[0] instanceof Function)) { ret.options = args[0]; args.shift(); } ret.callback = args[0]; ret.endCallback = args[1]; if (ret.query === undefined || ret.callback === undefined) { throw new Error('query and callback are required'); } return ret; }
[ "function", "parseArgs", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", ";", "var", "ret", "=", "{", "query", ":", "args", "[", "0", "]", ",", "params", ":", "[", "]", ",", "options", ":", "{", "}", ",", "callback", ":", "undefined", ",", "endCallback", ":", "undefined", "}", ";", "args", ".", "shift", "(", ")", ";", "// If specified, params must be an array", "if", "(", "args", "[", "0", "]", "instanceof", "Array", ")", "{", "ret", ".", "params", "=", "args", "[", "0", "]", ";", "args", ".", "shift", "(", ")", ";", "}", "// If specified, options must be a non-Function object", "if", "(", "!", "(", "args", "[", "0", "]", "instanceof", "Function", ")", ")", "{", "ret", ".", "options", "=", "args", "[", "0", "]", ";", "args", ".", "shift", "(", ")", ";", "}", "ret", ".", "callback", "=", "args", "[", "0", "]", ";", "ret", ".", "endCallback", "=", "args", "[", "1", "]", ";", "if", "(", "ret", ".", "query", "===", "undefined", "||", "ret", ".", "callback", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "'query and callback are required'", ")", ";", "}", "return", "ret", ";", "}" ]
Utility to parse the query function args
[ "Utility", "to", "parse", "the", "query", "function", "args" ]
7a0d9043d661fa255ab9ead21cdce1976a31b88b
https://github.com/demmer/node-cassandra-native-driver/blob/7a0d9043d661fa255ab9ead21cdce1976a31b88b/lib/client.js#L14-L47
26,889
helpers/logging-helpers
index.js
createArgs
function createArgs(args, color) { var last = args[args.length - 1]; if (args.length > 1 && isObject(last && last.hash)) { args.pop(); } if (typeof color === 'string' && utils[color]) { args[0] = utils[color](args[0]); } return args; }
javascript
function createArgs(args, color) { var last = args[args.length - 1]; if (args.length > 1 && isObject(last && last.hash)) { args.pop(); } if (typeof color === 'string' && utils[color]) { args[0] = utils[color](args[0]); } return args; }
[ "function", "createArgs", "(", "args", ",", "color", ")", "{", "var", "last", "=", "args", "[", "args", ".", "length", "-", "1", "]", ";", "if", "(", "args", ".", "length", ">", "1", "&&", "isObject", "(", "last", "&&", "last", ".", "hash", ")", ")", "{", "args", ".", "pop", "(", ")", ";", "}", "if", "(", "typeof", "color", "===", "'string'", "&&", "utils", "[", "color", "]", ")", "{", "args", "[", "0", "]", "=", "utils", "[", "color", "]", "(", "args", "[", "0", "]", ")", ";", "}", "return", "args", ";", "}" ]
Remove handlebars options from the arguments if more than one argument is passed, and apply a color to the first argument if specified
[ "Remove", "handlebars", "options", "from", "the", "arguments", "if", "more", "than", "one", "argument", "is", "passed", "and", "apply", "a", "color", "to", "the", "first", "argument", "if", "specified" ]
1c85a1eeb142142e18693d9122ac9d9a106e21e9
https://github.com/helpers/logging-helpers/blob/1c85a1eeb142142e18693d9122ac9d9a106e21e9/index.js#L239-L248
26,890
helpers/logging-helpers
index.js
switchOutput
function switchOutput(type, json) { if (type[0] === '.') type = type.slice(1); var result = ''; switch (type) { case 'md': result = '' + '\n```json\n' + json + '\n```\n'; break; case 'html': result = '' + '<div class="highlight highlight-json">\n' + '<pre><code>\n' + json + '</code></pre>' + '</div>'; break; default: { result = json; break; } } return result; }
javascript
function switchOutput(type, json) { if (type[0] === '.') type = type.slice(1); var result = ''; switch (type) { case 'md': result = '' + '\n```json\n' + json + '\n```\n'; break; case 'html': result = '' + '<div class="highlight highlight-json">\n' + '<pre><code>\n' + json + '</code></pre>' + '</div>'; break; default: { result = json; break; } } return result; }
[ "function", "switchOutput", "(", "type", ",", "json", ")", "{", "if", "(", "type", "[", "0", "]", "===", "'.'", ")", "type", "=", "type", ".", "slice", "(", "1", ")", ";", "var", "result", "=", "''", ";", "switch", "(", "type", ")", "{", "case", "'md'", ":", "result", "=", "''", "+", "'\\n```json\\n'", "+", "json", "+", "'\\n```\\n'", ";", "break", ";", "case", "'html'", ":", "result", "=", "''", "+", "'<div class=\"highlight highlight-json\">\\n'", "+", "'<pre><code>\\n'", "+", "json", "+", "'</code></pre>'", "+", "'</div>'", ";", "break", ";", "default", ":", "{", "result", "=", "json", ";", "break", ";", "}", "}", "return", "result", ";", "}" ]
Generate output for the `_inspect` helper based on the given `type`
[ "Generate", "output", "for", "the", "_inspect", "helper", "based", "on", "the", "given", "type" ]
1c85a1eeb142142e18693d9122ac9d9a106e21e9
https://github.com/helpers/logging-helpers/blob/1c85a1eeb142142e18693d9122ac9d9a106e21e9/index.js#L255-L280
26,891
ChauffeurPrive/stakhanov
lib/lib.js
promisifyWithTimeout
function promisifyWithTimeout(yieldable, name, timeout) { return new Promise((resolve, reject) => { const timeoutId = setTimeout(() => reject(new Error(`Yieldable timeout in ${name}`)), timeout); co(yieldable) .then((...args) => { clearTimeout(timeoutId); resolve(...args); }) .catch((...args) => { clearTimeout(timeoutId); reject(...args); }); }); }
javascript
function promisifyWithTimeout(yieldable, name, timeout) { return new Promise((resolve, reject) => { const timeoutId = setTimeout(() => reject(new Error(`Yieldable timeout in ${name}`)), timeout); co(yieldable) .then((...args) => { clearTimeout(timeoutId); resolve(...args); }) .catch((...args) => { clearTimeout(timeoutId); reject(...args); }); }); }
[ "function", "promisifyWithTimeout", "(", "yieldable", ",", "name", ",", "timeout", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "timeoutId", "=", "setTimeout", "(", "(", ")", "=>", "reject", "(", "new", "Error", "(", "`", "${", "name", "}", "`", ")", ")", ",", "timeout", ")", ";", "co", "(", "yieldable", ")", ".", "then", "(", "(", "...", "args", ")", "=>", "{", "clearTimeout", "(", "timeoutId", ")", ";", "resolve", "(", "...", "args", ")", ";", "}", ")", ".", "catch", "(", "(", "...", "args", ")", "=>", "{", "clearTimeout", "(", "timeoutId", ")", ";", "reject", "(", "...", "args", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Make a promise outside of a yieldable. To avoid unhandled callbacks resulting in unacked messages piling up in amqp, the returned promise will fail after a specified timeout. @param {Promise|Generator|Function} yieldable a yieldable (generator or promise) @param {String} name Name for error handling @param {Number} timeout Time after which the promise fails @returns {Promise} the promise
[ "Make", "a", "promise", "outside", "of", "a", "yieldable", ".", "To", "avoid", "unhandled", "callbacks", "resulting", "in", "unacked", "messages", "piling", "up", "in", "amqp", "the", "returned", "promise", "will", "fail", "after", "a", "specified", "timeout", "." ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/lib.js#L14-L27
26,892
ChauffeurPrive/stakhanov
lib/createWorkers.js
_wait
function _wait(eventName, timeout = 1000) { return new Promise((resolve, reject) => { let timeoutId = null; timeoutId = setTimeout(() => { timeoutId = null; reject(new Error(`event ${eventName} didn't occur after ${timeout}ms`)); }, timeout); emitter.once(eventName, () => { if (timeoutId !== null) { clearTimeout(timeoutId); resolve(); } }); }); }
javascript
function _wait(eventName, timeout = 1000) { return new Promise((resolve, reject) => { let timeoutId = null; timeoutId = setTimeout(() => { timeoutId = null; reject(new Error(`event ${eventName} didn't occur after ${timeout}ms`)); }, timeout); emitter.once(eventName, () => { if (timeoutId !== null) { clearTimeout(timeoutId); resolve(); } }); }); }
[ "function", "_wait", "(", "eventName", ",", "timeout", "=", "1000", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "timeoutId", "=", "null", ";", "timeoutId", "=", "setTimeout", "(", "(", ")", "=>", "{", "timeoutId", "=", "null", ";", "reject", "(", "new", "Error", "(", "`", "${", "eventName", "}", "${", "timeout", "}", "`", ")", ")", ";", "}", ",", "timeout", ")", ";", "emitter", ".", "once", "(", "eventName", ",", "(", ")", "=>", "{", "if", "(", "timeoutId", "!==", "null", ")", "{", "clearTimeout", "(", "timeoutId", ")", ";", "resolve", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Wait for an event for a given amount of time. @param {string} eventName The name of the event to wait for. @param {number} timeout The maximum number of milliseconds to wait for, defaults to 1000. @return {Promise} A promise which is resolved when the event emitted, or rejected if the timeout occurs first. @private
[ "Wait", "for", "an", "event", "for", "a", "given", "amount", "of", "time", "." ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L84-L100
26,893
ChauffeurPrive/stakhanov
lib/createWorkers.js
_closeOnSignal
function _closeOnSignal(signal) { process.on(signal, onSignal); /** * @returns {void} */ function onSignal() { logger.info({ workerName: configuration.workerName, signal }, '[worker#listen] Received exit signal, stopping workers...'); workers.close(true); } }
javascript
function _closeOnSignal(signal) { process.on(signal, onSignal); /** * @returns {void} */ function onSignal() { logger.info({ workerName: configuration.workerName, signal }, '[worker#listen] Received exit signal, stopping workers...'); workers.close(true); } }
[ "function", "_closeOnSignal", "(", "signal", ")", "{", "process", ".", "on", "(", "signal", ",", "onSignal", ")", ";", "/**\n * @returns {void}\n */", "function", "onSignal", "(", ")", "{", "logger", ".", "info", "(", "{", "workerName", ":", "configuration", ".", "workerName", ",", "signal", "}", ",", "'[worker#listen] Received exit signal, stopping workers...'", ")", ";", "workers", ".", "close", "(", "true", ")", ";", "}", "}" ]
Listen to exit signal such as SIGINT and close the workers @param {String} signal name (e.g. SIGINT) @returns {void} @private
[ "Listen", "to", "exit", "signal", "such", "as", "SIGINT", "and", "close", "the", "workers" ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L149-L160
26,894
ChauffeurPrive/stakhanov
lib/createWorkers.js
_getMessageConsumer
function _getMessageConsumer(channel, handle, validate, routingKey) { return function* _consumeMessage(message) { try { logger.debug({ message, routingKey }, '[worker#listen] received message'); const content = _parseMessage(message); if (!content) return channel.ack(message); const validatedContent = _validateMessage(validate, content); if (_.isError(validatedContent)) return channel.ack(message); const handleSuccess = yield _handleMessage( handle, validatedContent || content, message.fields ); if (!handleSuccess) return channel.nack(message); return channel.ack(message); } catch (err) { logger.error({ err, routingKey }, '[worker#listen] failed to ack/nack'); return null; } }; }
javascript
function _getMessageConsumer(channel, handle, validate, routingKey) { return function* _consumeMessage(message) { try { logger.debug({ message, routingKey }, '[worker#listen] received message'); const content = _parseMessage(message); if (!content) return channel.ack(message); const validatedContent = _validateMessage(validate, content); if (_.isError(validatedContent)) return channel.ack(message); const handleSuccess = yield _handleMessage( handle, validatedContent || content, message.fields ); if (!handleSuccess) return channel.nack(message); return channel.ack(message); } catch (err) { logger.error({ err, routingKey }, '[worker#listen] failed to ack/nack'); return null; } }; }
[ "function", "_getMessageConsumer", "(", "channel", ",", "handle", ",", "validate", ",", "routingKey", ")", "{", "return", "function", "*", "_consumeMessage", "(", "message", ")", "{", "try", "{", "logger", ".", "debug", "(", "{", "message", ",", "routingKey", "}", ",", "'[worker#listen] received message'", ")", ";", "const", "content", "=", "_parseMessage", "(", "message", ")", ";", "if", "(", "!", "content", ")", "return", "channel", ".", "ack", "(", "message", ")", ";", "const", "validatedContent", "=", "_validateMessage", "(", "validate", ",", "content", ")", ";", "if", "(", "_", ".", "isError", "(", "validatedContent", ")", ")", "return", "channel", ".", "ack", "(", "message", ")", ";", "const", "handleSuccess", "=", "yield", "_handleMessage", "(", "handle", ",", "validatedContent", "||", "content", ",", "message", ".", "fields", ")", ";", "if", "(", "!", "handleSuccess", ")", "return", "channel", ".", "nack", "(", "message", ")", ";", "return", "channel", ".", "ack", "(", "message", ")", ";", "}", "catch", "(", "err", ")", "{", "logger", ".", "error", "(", "{", "err", ",", "routingKey", "}", ",", "'[worker#listen] failed to ack/nack'", ")", ";", "return", "null", ";", "}", "}", ";", "}" ]
Create an AMQP message consumer with the given handler @param {Object} channel The AMQP channel. @param {function} handle the message handler @param {function} validate the message validator @returns {function} The generator function that consumes an AMQP message @param {String} routingKey routing key to bind on @private
[ "Create", "an", "AMQP", "message", "consumer", "with", "the", "given", "handler" ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L227-L250
26,895
ChauffeurPrive/stakhanov
lib/createWorkers.js
_parseMessage
function _parseMessage(message) { try { const contentString = message && message.content && message.content.toString(); return JSON.parse(contentString); } catch (err) { _emit(TASK_FAILED); logger.warn( { err, message, options: configWithoutFuncs }, '[worker#listen] Content is not a valid JSON' ); return null; } }
javascript
function _parseMessage(message) { try { const contentString = message && message.content && message.content.toString(); return JSON.parse(contentString); } catch (err) { _emit(TASK_FAILED); logger.warn( { err, message, options: configWithoutFuncs }, '[worker#listen] Content is not a valid JSON' ); return null; } }
[ "function", "_parseMessage", "(", "message", ")", "{", "try", "{", "const", "contentString", "=", "message", "&&", "message", ".", "content", "&&", "message", ".", "content", ".", "toString", "(", ")", ";", "return", "JSON", ".", "parse", "(", "contentString", ")", ";", "}", "catch", "(", "err", ")", "{", "_emit", "(", "TASK_FAILED", ")", ";", "logger", ".", "warn", "(", "{", "err", ",", "message", ",", "options", ":", "configWithoutFuncs", "}", ",", "'[worker#listen] Content is not a valid JSON'", ")", ";", "return", "null", ";", "}", "}" ]
Parse a message and return content @param {Object} message the message from the queue @returns {String|null} message content or null if parsing failed @private
[ "Parse", "a", "message", "and", "return", "content" ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L259-L271
26,896
ChauffeurPrive/stakhanov
lib/createWorkers.js
_validateMessage
function _validateMessage(validate, message) { const { workerName } = configuration; try { return validate(message); } catch (err) { _emit(TASK_FAILED); logger.warn( { err, message, options: configWithoutFuncs, workerName }, '[worker#listen] Message validation failed' ); return err; } }
javascript
function _validateMessage(validate, message) { const { workerName } = configuration; try { return validate(message); } catch (err) { _emit(TASK_FAILED); logger.warn( { err, message, options: configWithoutFuncs, workerName }, '[worker#listen] Message validation failed' ); return err; } }
[ "function", "_validateMessage", "(", "validate", ",", "message", ")", "{", "const", "{", "workerName", "}", "=", "configuration", ";", "try", "{", "return", "validate", "(", "message", ")", ";", "}", "catch", "(", "err", ")", "{", "_emit", "(", "TASK_FAILED", ")", ";", "logger", ".", "warn", "(", "{", "err", ",", "message", ",", "options", ":", "configWithoutFuncs", ",", "workerName", "}", ",", "'[worker#listen] Message validation failed'", ")", ";", "return", "err", ";", "}", "}" ]
Validate a message against custom validator if any @param {function} validate the message validator @param {String} message content of the message @returns {Object|null} The validated object, or null if validation failed @private
[ "Validate", "a", "message", "against", "custom", "validator", "if", "any" ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L281-L293
26,897
ChauffeurPrive/stakhanov
lib/createWorkers.js
_subscribeToConnectionEvents
function _subscribeToConnectionEvents(connection, workerName) { connection.on('close', errCode => { logger.info({ workerName, errCode }, '[AMQP] Connection closing, exiting'); // The workerConnection isn't working anymore... workerConnection = null; workers.close(); }); connection.on('error', err => { logger.error({ err, workerName }, '[AMQP] Connection closing because of an error'); }); connection.on('blocked', reason => { logger.warn({ reason, workerName }, '[AMQP] Connection blocked'); }); }
javascript
function _subscribeToConnectionEvents(connection, workerName) { connection.on('close', errCode => { logger.info({ workerName, errCode }, '[AMQP] Connection closing, exiting'); // The workerConnection isn't working anymore... workerConnection = null; workers.close(); }); connection.on('error', err => { logger.error({ err, workerName }, '[AMQP] Connection closing because of an error'); }); connection.on('blocked', reason => { logger.warn({ reason, workerName }, '[AMQP] Connection blocked'); }); }
[ "function", "_subscribeToConnectionEvents", "(", "connection", ",", "workerName", ")", "{", "connection", ".", "on", "(", "'close'", ",", "errCode", "=>", "{", "logger", ".", "info", "(", "{", "workerName", ",", "errCode", "}", ",", "'[AMQP] Connection closing, exiting'", ")", ";", "// The workerConnection isn't working anymore...", "workerConnection", "=", "null", ";", "workers", ".", "close", "(", ")", ";", "}", ")", ";", "connection", ".", "on", "(", "'error'", ",", "err", "=>", "{", "logger", ".", "error", "(", "{", "err", ",", "workerName", "}", ",", "'[AMQP] Connection closing because of an error'", ")", ";", "}", ")", ";", "connection", ".", "on", "(", "'blocked'", ",", "reason", "=>", "{", "logger", ".", "warn", "(", "{", "reason", ",", "workerName", "}", ",", "'[AMQP] Connection blocked'", ")", ";", "}", ")", ";", "}" ]
Bind a logger to noticeable connection events @param {Object} connection the connection objext @param {String} workerName worker name @returns {*} - @private
[ "Bind", "a", "logger", "to", "noticeable", "connection", "events" ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L335-L348
26,898
ChauffeurPrive/stakhanov
lib/createWorkers.js
_subscribeToChannelEvents
function _subscribeToChannelEvents(channel, { exchangeName, queueName, channelPrefetch, workerName }) { channel.on('error', err => { logger.error( { err, exchangeName, queueName, channelPrefetch, workerName }, '[AMQP] channel error' ); }); channel.on('close', () => { logger.info( { exchangeName, queueName, channelPrefetch, workerName }, '[AMQP] channel closed' ); // Remove this channel because is closed workerChannels.delete(channel); workers.close(); }); }
javascript
function _subscribeToChannelEvents(channel, { exchangeName, queueName, channelPrefetch, workerName }) { channel.on('error', err => { logger.error( { err, exchangeName, queueName, channelPrefetch, workerName }, '[AMQP] channel error' ); }); channel.on('close', () => { logger.info( { exchangeName, queueName, channelPrefetch, workerName }, '[AMQP] channel closed' ); // Remove this channel because is closed workerChannels.delete(channel); workers.close(); }); }
[ "function", "_subscribeToChannelEvents", "(", "channel", ",", "{", "exchangeName", ",", "queueName", ",", "channelPrefetch", ",", "workerName", "}", ")", "{", "channel", ".", "on", "(", "'error'", ",", "err", "=>", "{", "logger", ".", "error", "(", "{", "err", ",", "exchangeName", ",", "queueName", ",", "channelPrefetch", ",", "workerName", "}", ",", "'[AMQP] channel error'", ")", ";", "}", ")", ";", "channel", ".", "on", "(", "'close'", ",", "(", ")", "=>", "{", "logger", ".", "info", "(", "{", "exchangeName", ",", "queueName", ",", "channelPrefetch", ",", "workerName", "}", ",", "'[AMQP] channel closed'", ")", ";", "// Remove this channel because is closed", "workerChannels", ".", "delete", "(", "channel", ")", ";", "workers", ".", "close", "(", ")", ";", "}", ")", ";", "}" ]
Bind a logger to noticeable channel events @param {Object} channel the channel object @param {String} exchangeName the exchange name to use @param {String} queueName the queue name to target @param {Number} channelPrefetch number of message to prefetch from channel @param {String} workerName the name of the worker (for logs) @returns {*} - @private
[ "Bind", "a", "logger", "to", "noticeable", "channel", "events" ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L389-L406
26,899
adrai/node-cqrs-eventdenormalizer
lib/replayHandler.js
function (callback) { var self = this; async.parallel([ function (callback) { async.each(self.dispatcher.tree.getCollections(), function (col, callback) { if (col.noReplay) { return callback(null); } col.repository.clear(callback); }, callback); }, function (callback) { self.store.clear(callback); } ], callback); }
javascript
function (callback) { var self = this; async.parallel([ function (callback) { async.each(self.dispatcher.tree.getCollections(), function (col, callback) { if (col.noReplay) { return callback(null); } col.repository.clear(callback); }, callback); }, function (callback) { self.store.clear(callback); } ], callback); }
[ "function", "(", "callback", ")", "{", "var", "self", "=", "this", ";", "async", ".", "parallel", "(", "[", "function", "(", "callback", ")", "{", "async", ".", "each", "(", "self", ".", "dispatcher", ".", "tree", ".", "getCollections", "(", ")", ",", "function", "(", "col", ",", "callback", ")", "{", "if", "(", "col", ".", "noReplay", ")", "{", "return", "callback", "(", "null", ")", ";", "}", "col", ".", "repository", ".", "clear", "(", "callback", ")", ";", "}", ",", "callback", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "self", ".", "store", ".", "clear", "(", "callback", ")", ";", "}", "]", ",", "callback", ")", ";", "}" ]
Clears all collections and the revisionGuardStore. @param {Function} callback The function, that will be called when this action is completed. `function(err){}`
[ "Clears", "all", "collections", "and", "the", "revisionGuardStore", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/replayHandler.js#L48-L63