repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
sequence
docstring
stringlengths
4
11.8k
docstring_tokens
sequence
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
_suspendBeforeObserver
function _suspendBeforeObserver(obj, path, target, method, callback) { return suspendListener(obj, beforeEvent(path), target, method, callback); }
javascript
function _suspendBeforeObserver(obj, path, target, method, callback) { return suspendListener(obj, beforeEvent(path), target, method, callback); }
[ "function", "_suspendBeforeObserver", "(", "obj", ",", "path", ",", "target", ",", "method", ",", "callback", ")", "{", "return", "suspendListener", "(", "obj", ",", "beforeEvent", "(", "path", ")", ",", "target", ",", "method", ",", "callback", ")", ";", "}" ]
Suspend observer during callback. This should only be used by the target of the observer while it is setting the observed path.
[ "Suspend", "observer", "during", "callback", ".", "This", "should", "only", "be", "used", "by", "the", "target", "of", "the", "observer", "while", "it", "is", "setting", "the", "observed", "path", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L16977-L16979
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
set
function set(obj, keyName, value, tolerant) { if (typeof obj === 'string') { Ember.assert("Path '" + obj + "' must be global if no obj is given.", IS_GLOBAL.test(obj)); value = keyName; keyName = obj; obj = null; } Ember.assert("Cannot call set with "+ keyName +" key.", !!keyName); if (!obj) { return setPath(obj, keyName, value, tolerant); } var meta = obj['__ember_meta__']; var desc = meta && meta.descs[keyName]; var isUnknown, currentValue; if (desc === undefined && isPath(keyName)) { return setPath(obj, keyName, value, tolerant); } Ember.assert("You need to provide an object and key to `set`.", !!obj && keyName !== undefined); Ember.assert('calling set on destroyed object', !obj.isDestroyed); if (desc !== undefined) { desc.set(obj, keyName, value); } else { if (typeof obj === 'object' && obj !== null && value !== undefined && obj[keyName] === value) { return value; } isUnknown = 'object' === typeof obj && !(keyName in obj); // setUnknownProperty is called if `obj` is an object, // the property does not already exist, and the // `setUnknownProperty` method exists on the object if (isUnknown && 'function' === typeof obj.setUnknownProperty) { obj.setUnknownProperty(keyName, value); } else if (meta && meta.watching[keyName] > 0) { if (hasPropertyAccessors) { currentValue = meta.values[keyName]; } else { currentValue = obj[keyName]; } // only trigger a change if the value has changed if (value !== currentValue) { propertyWillChange(obj, keyName); if (hasPropertyAccessors) { if ( (currentValue === undefined && !(keyName in obj)) || !Object.prototype.propertyIsEnumerable.call(obj, keyName) ) { defineProperty(obj, keyName, null, value); // setup mandatory setter } else { meta.values[keyName] = value; } } else { obj[keyName] = value; } propertyDidChange(obj, keyName); } } else { obj[keyName] = value; } } return value; }
javascript
function set(obj, keyName, value, tolerant) { if (typeof obj === 'string') { Ember.assert("Path '" + obj + "' must be global if no obj is given.", IS_GLOBAL.test(obj)); value = keyName; keyName = obj; obj = null; } Ember.assert("Cannot call set with "+ keyName +" key.", !!keyName); if (!obj) { return setPath(obj, keyName, value, tolerant); } var meta = obj['__ember_meta__']; var desc = meta && meta.descs[keyName]; var isUnknown, currentValue; if (desc === undefined && isPath(keyName)) { return setPath(obj, keyName, value, tolerant); } Ember.assert("You need to provide an object and key to `set`.", !!obj && keyName !== undefined); Ember.assert('calling set on destroyed object', !obj.isDestroyed); if (desc !== undefined) { desc.set(obj, keyName, value); } else { if (typeof obj === 'object' && obj !== null && value !== undefined && obj[keyName] === value) { return value; } isUnknown = 'object' === typeof obj && !(keyName in obj); // setUnknownProperty is called if `obj` is an object, // the property does not already exist, and the // `setUnknownProperty` method exists on the object if (isUnknown && 'function' === typeof obj.setUnknownProperty) { obj.setUnknownProperty(keyName, value); } else if (meta && meta.watching[keyName] > 0) { if (hasPropertyAccessors) { currentValue = meta.values[keyName]; } else { currentValue = obj[keyName]; } // only trigger a change if the value has changed if (value !== currentValue) { propertyWillChange(obj, keyName); if (hasPropertyAccessors) { if ( (currentValue === undefined && !(keyName in obj)) || !Object.prototype.propertyIsEnumerable.call(obj, keyName) ) { defineProperty(obj, keyName, null, value); // setup mandatory setter } else { meta.values[keyName] = value; } } else { obj[keyName] = value; } propertyDidChange(obj, keyName); } } else { obj[keyName] = value; } } return value; }
[ "function", "set", "(", "obj", ",", "keyName", ",", "value", ",", "tolerant", ")", "{", "if", "(", "typeof", "obj", "===", "'string'", ")", "{", "Ember", ".", "assert", "(", "\"Path '\"", "+", "obj", "+", "\"' must be global if no obj is given.\"", ",", "IS_GLOBAL", ".", "test", "(", "obj", ")", ")", ";", "value", "=", "keyName", ";", "keyName", "=", "obj", ";", "obj", "=", "null", ";", "}", "Ember", ".", "assert", "(", "\"Cannot call set with \"", "+", "keyName", "+", "\" key.\"", ",", "!", "!", "keyName", ")", ";", "if", "(", "!", "obj", ")", "{", "return", "setPath", "(", "obj", ",", "keyName", ",", "value", ",", "tolerant", ")", ";", "}", "var", "meta", "=", "obj", "[", "'__ember_meta__'", "]", ";", "var", "desc", "=", "meta", "&&", "meta", ".", "descs", "[", "keyName", "]", ";", "var", "isUnknown", ",", "currentValue", ";", "if", "(", "desc", "===", "undefined", "&&", "isPath", "(", "keyName", ")", ")", "{", "return", "setPath", "(", "obj", ",", "keyName", ",", "value", ",", "tolerant", ")", ";", "}", "Ember", ".", "assert", "(", "\"You need to provide an object and key to `set`.\"", ",", "!", "!", "obj", "&&", "keyName", "!==", "undefined", ")", ";", "Ember", ".", "assert", "(", "'calling set on destroyed object'", ",", "!", "obj", ".", "isDestroyed", ")", ";", "if", "(", "desc", "!==", "undefined", ")", "{", "desc", ".", "set", "(", "obj", ",", "keyName", ",", "value", ")", ";", "}", "else", "{", "if", "(", "typeof", "obj", "===", "'object'", "&&", "obj", "!==", "null", "&&", "value", "!==", "undefined", "&&", "obj", "[", "keyName", "]", "===", "value", ")", "{", "return", "value", ";", "}", "isUnknown", "=", "'object'", "===", "typeof", "obj", "&&", "!", "(", "keyName", "in", "obj", ")", ";", "if", "(", "isUnknown", "&&", "'function'", "===", "typeof", "obj", ".", "setUnknownProperty", ")", "{", "obj", ".", "setUnknownProperty", "(", "keyName", ",", "value", ")", ";", "}", "else", "if", "(", "meta", "&&", "meta", ".", "watching", "[", "keyName", "]", ">", "0", ")", "{", "if", "(", "hasPropertyAccessors", ")", "{", "currentValue", "=", "meta", ".", "values", "[", "keyName", "]", ";", "}", "else", "{", "currentValue", "=", "obj", "[", "keyName", "]", ";", "}", "if", "(", "value", "!==", "currentValue", ")", "{", "propertyWillChange", "(", "obj", ",", "keyName", ")", ";", "if", "(", "hasPropertyAccessors", ")", "{", "if", "(", "(", "currentValue", "===", "undefined", "&&", "!", "(", "keyName", "in", "obj", ")", ")", "||", "!", "Object", ".", "prototype", ".", "propertyIsEnumerable", ".", "call", "(", "obj", ",", "keyName", ")", ")", "{", "defineProperty", "(", "obj", ",", "keyName", ",", "null", ",", "value", ")", ";", "}", "else", "{", "meta", ".", "values", "[", "keyName", "]", "=", "value", ";", "}", "}", "else", "{", "obj", "[", "keyName", "]", "=", "value", ";", "}", "propertyDidChange", "(", "obj", ",", "keyName", ")", ";", "}", "}", "else", "{", "obj", "[", "keyName", "]", "=", "value", ";", "}", "}", "return", "value", ";", "}" ]
Sets the value of a property on an object, respecting computed properties and notifying observers and other listeners of the change. If the property is not defined but the object implements the `setUnknownProperty` method then that will be invoked as well. @method set @for Ember @param {Object} obj The object to modify. @param {String} keyName The property key to set @param {Object} value The value to set @return {Object} the passed value.
[ "Sets", "the", "value", "of", "a", "property", "on", "an", "object", "respecting", "computed", "properties", "and", "notifying", "observers", "and", "other", "listeners", "of", "the", "change", ".", "If", "the", "property", "is", "not", "defined", "but", "the", "object", "implements", "the", "setUnknownProperty", "method", "then", "that", "will", "be", "invoked", "as", "well", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L18028-L18098
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
intern
function intern(str) { var obj = {}; obj[str] = 1; for (var key in obj) { if (key === str) return key; } return str; }
javascript
function intern(str) { var obj = {}; obj[str] = 1; for (var key in obj) { if (key === str) return key; } return str; }
[ "function", "intern", "(", "str", ")", "{", "var", "obj", "=", "{", "}", ";", "obj", "[", "str", "]", "=", "1", ";", "for", "(", "var", "key", "in", "obj", ")", "{", "if", "(", "key", "===", "str", ")", "return", "key", ";", "}", "return", "str", ";", "}" ]
Strongly hint runtimes to intern the provided string. When do I need to use this function? For the most part, never. Pre-mature optimization is bad, and often the runtime does exactly what you need it to, and more often the trade-off isn't worth it. Why? Runtimes store strings in at least 2 different representations: Ropes and Symbols (interned strings). The Rope provides a memory efficient data-structure for strings created from concatenation or some other string manipulation like splitting. Unfortunately checking equality of different ropes can be quite costly as runtimes must resort to clever string comparison algorithims. These algorithims typically cost in proportion to the length of the string. Luckily, this is where the Symbols (interned strings) shine. As Symbols are unique by their string content, equality checks can be done by pointer comparision. How do I know if my string is a rope or symbol? Typically (warning general sweeping statement, but truthy in runtimes at present) static strings created as part of the JS source are interned. Strings often used for comparisions can be interned at runtime if some criteria are met. One of these criteria can be the size of the entire rope. For example, in chrome 38 a rope longer then 12 characters will not intern, nor will segments of that rope. Some numbers: http://jsperf.com/eval-vs-keys/8 Known Trick™ @private @return {String} interned version of the provided string
[ "Strongly", "hint", "runtimes", "to", "intern", "the", "provided", "string", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L18923-L18930
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
makeArray
function makeArray(obj) { if (obj === null || obj === undefined) { return []; } return isArray(obj) ? obj : [obj]; }
javascript
function makeArray(obj) { if (obj === null || obj === undefined) { return []; } return isArray(obj) ? obj : [obj]; }
[ "function", "makeArray", "(", "obj", ")", "{", "if", "(", "obj", "===", "null", "||", "obj", "===", "undefined", ")", "{", "return", "[", "]", ";", "}", "return", "isArray", "(", "obj", ")", "?", "obj", ":", "[", "obj", "]", ";", "}" ]
Forces the passed object to be part of an array. If the object is already an array or array-like, returns the object. Otherwise adds the object to an array. If obj is `null` or `undefined`, returns an empty array. ```javascript Ember.makeArray(); // [] Ember.makeArray(null); // [] Ember.makeArray(undefined); // [] Ember.makeArray('lindsay'); // ['lindsay'] Ember.makeArray([1, 2, 42]); // [1, 2, 42] var controller = Ember.ArrayProxy.create({ content: [] }); Ember.makeArray(controller) === controller; // true ``` @method makeArray @for Ember @param {Object} obj the object @return {Array}
[ "Forces", "the", "passed", "object", "to", "be", "part", "of", "an", "array", ".", "If", "the", "object", "is", "already", "an", "array", "or", "array", "-", "like", "returns", "the", "object", ".", "Otherwise", "adds", "the", "object", "to", "an", "array", ".", "If", "obj", "is", "null", "or", "undefined", "returns", "an", "empty", "array", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L19327-L19330
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
typeOf
function typeOf(item) { var ret, modulePath; // ES6TODO: Depends on Ember.Object which is defined in runtime. if (typeof EmberObject === "undefined") { modulePath = 'ember-runtime/system/object'; if (Ember.__loader.registry[modulePath]) { EmberObject = Ember.__loader.require(modulePath)['default']; } } ret = (item === null || item === undefined) ? String(item) : TYPE_MAP[toString.call(item)] || 'object'; if (ret === 'function') { if (EmberObject && EmberObject.detect(item)) ret = 'class'; } else if (ret === 'object') { if (item instanceof Error) ret = 'error'; else if (EmberObject && item instanceof EmberObject) ret = 'instance'; else if (item instanceof Date) ret = 'date'; } return ret; }
javascript
function typeOf(item) { var ret, modulePath; // ES6TODO: Depends on Ember.Object which is defined in runtime. if (typeof EmberObject === "undefined") { modulePath = 'ember-runtime/system/object'; if (Ember.__loader.registry[modulePath]) { EmberObject = Ember.__loader.require(modulePath)['default']; } } ret = (item === null || item === undefined) ? String(item) : TYPE_MAP[toString.call(item)] || 'object'; if (ret === 'function') { if (EmberObject && EmberObject.detect(item)) ret = 'class'; } else if (ret === 'object') { if (item instanceof Error) ret = 'error'; else if (EmberObject && item instanceof EmberObject) ret = 'instance'; else if (item instanceof Date) ret = 'date'; } return ret; }
[ "function", "typeOf", "(", "item", ")", "{", "var", "ret", ",", "modulePath", ";", "if", "(", "typeof", "EmberObject", "===", "\"undefined\"", ")", "{", "modulePath", "=", "'ember-runtime/system/object'", ";", "if", "(", "Ember", ".", "__loader", ".", "registry", "[", "modulePath", "]", ")", "{", "EmberObject", "=", "Ember", ".", "__loader", ".", "require", "(", "modulePath", ")", "[", "'default'", "]", ";", "}", "}", "ret", "=", "(", "item", "===", "null", "||", "item", "===", "undefined", ")", "?", "String", "(", "item", ")", ":", "TYPE_MAP", "[", "toString", ".", "call", "(", "item", ")", "]", "||", "'object'", ";", "if", "(", "ret", "===", "'function'", ")", "{", "if", "(", "EmberObject", "&&", "EmberObject", ".", "detect", "(", "item", ")", ")", "ret", "=", "'class'", ";", "}", "else", "if", "(", "ret", "===", "'object'", ")", "{", "if", "(", "item", "instanceof", "Error", ")", "ret", "=", "'error'", ";", "else", "if", "(", "EmberObject", "&&", "item", "instanceof", "EmberObject", ")", "ret", "=", "'instance'", ";", "else", "if", "(", "item", "instanceof", "Date", ")", "ret", "=", "'date'", ";", "}", "return", "ret", ";", "}" ]
Returns a consistent type for the passed item. Use this instead of the built-in `typeof` to get the type of an item. It will return the same result across all browsers and includes a bit more detail. Here is what will be returned: | Return Value | Meaning | |---------------|------------------------------------------------------| | 'string' | String primitive or String object. | | 'number' | Number primitive or Number object. | | 'boolean' | Boolean primitive or Boolean object. | | 'null' | Null value | | 'undefined' | Undefined value | | 'function' | A function | | 'array' | An instance of Array | | 'regexp' | An instance of RegExp | | 'date' | An instance of Date | | 'class' | An Ember class (created using Ember.Object.extend()) | | 'instance' | An Ember object instance | | 'error' | An instance of the Error object | | 'object' | A JavaScript object not inheriting from Ember.Object | Examples: ```javascript Ember.typeOf(); // 'undefined' Ember.typeOf(null); // 'null' Ember.typeOf(undefined); // 'undefined' Ember.typeOf('michael'); // 'string' Ember.typeOf(new String('michael')); // 'string' Ember.typeOf(101); // 'number' Ember.typeOf(new Number(101)); // 'number' Ember.typeOf(true); // 'boolean' Ember.typeOf(new Boolean(true)); // 'boolean' Ember.typeOf(Ember.makeArray); // 'function' Ember.typeOf([1, 2, 90]); // 'array' Ember.typeOf(/abc/); // 'regexp' Ember.typeOf(new Date()); // 'date' Ember.typeOf(Ember.Object.extend()); // 'class' Ember.typeOf(Ember.Object.create()); // 'instance' Ember.typeOf(new Error('teamocil')); // 'error' 'normal' JavaScript object Ember.typeOf({ a: 'b' }); // 'object' ``` @method typeOf @for Ember @param {Object} item the item to check @return {String} the type
[ "Returns", "a", "consistent", "type", "for", "the", "passed", "item", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L19602-L19624
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
watchKey
function watchKey(obj, keyName, meta) { // can't watch length on Array - it is special... if (keyName === 'length' && typeOf(obj) === 'array') { return; } var m = meta || metaFor(obj), watching = m.watching; // activate watching first time if (!watching[keyName]) { watching[keyName] = 1; var desc = m.descs[keyName]; if (desc && desc.willWatch) { desc.willWatch(obj, keyName); } if ('function' === typeof obj.willWatchProperty) { obj.willWatchProperty(keyName); } if (hasPropertyAccessors) { handleMandatorySetter(m, obj, keyName); } } else { watching[keyName] = (watching[keyName] || 0) + 1; } }
javascript
function watchKey(obj, keyName, meta) { // can't watch length on Array - it is special... if (keyName === 'length' && typeOf(obj) === 'array') { return; } var m = meta || metaFor(obj), watching = m.watching; // activate watching first time if (!watching[keyName]) { watching[keyName] = 1; var desc = m.descs[keyName]; if (desc && desc.willWatch) { desc.willWatch(obj, keyName); } if ('function' === typeof obj.willWatchProperty) { obj.willWatchProperty(keyName); } if (hasPropertyAccessors) { handleMandatorySetter(m, obj, keyName); } } else { watching[keyName] = (watching[keyName] || 0) + 1; } }
[ "function", "watchKey", "(", "obj", ",", "keyName", ",", "meta", ")", "{", "if", "(", "keyName", "===", "'length'", "&&", "typeOf", "(", "obj", ")", "===", "'array'", ")", "{", "return", ";", "}", "var", "m", "=", "meta", "||", "metaFor", "(", "obj", ")", ",", "watching", "=", "m", ".", "watching", ";", "if", "(", "!", "watching", "[", "keyName", "]", ")", "{", "watching", "[", "keyName", "]", "=", "1", ";", "var", "desc", "=", "m", ".", "descs", "[", "keyName", "]", ";", "if", "(", "desc", "&&", "desc", ".", "willWatch", ")", "{", "desc", ".", "willWatch", "(", "obj", ",", "keyName", ")", ";", "}", "if", "(", "'function'", "===", "typeof", "obj", ".", "willWatchProperty", ")", "{", "obj", ".", "willWatchProperty", "(", "keyName", ")", ";", "}", "if", "(", "hasPropertyAccessors", ")", "{", "handleMandatorySetter", "(", "m", ",", "obj", ",", "keyName", ")", ";", "}", "}", "else", "{", "watching", "[", "keyName", "]", "=", "(", "watching", "[", "keyName", "]", "||", "0", ")", "+", "1", ";", "}", "}" ]
utils.js
[ "utils", ".", "js" ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L19720-L19745
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function() { this._super.apply(this, arguments); Ember.deprecate('Using currentWhen with {{link-to}} is deprecated in favor of `current-when`.', !this.currentWhen); // Map desired event name to invoke function var eventName = get(this, 'eventName'); this.on(eventName, this, this._invoke); }
javascript
function() { this._super.apply(this, arguments); Ember.deprecate('Using currentWhen with {{link-to}} is deprecated in favor of `current-when`.', !this.currentWhen); // Map desired event name to invoke function var eventName = get(this, 'eventName'); this.on(eventName, this, this._invoke); }
[ "function", "(", ")", "{", "this", ".", "_super", ".", "apply", "(", "this", ",", "arguments", ")", ";", "Ember", ".", "deprecate", "(", "'Using currentWhen with {{link-to}} is deprecated in favor of `current-when`.'", ",", "!", "this", ".", "currentWhen", ")", ";", "var", "eventName", "=", "get", "(", "this", ",", "'eventName'", ")", ";", "this", ".", "on", "(", "eventName", ",", "this", ",", "this", ".", "_invoke", ")", ";", "}" ]
this is doc'ed here so it shows up in the events section of the API documentation, which is where people will likely go looking for it. Triggers the `LinkView`'s routing behavior. If `eventName` is changed to a value other than `click` the routing behavior will trigger on that custom event instead. @event click An overridable method called when LinkView objects are instantiated. Example: ```javascript App.MyLinkView = Ember.LinkView.extend({ init: function() { this._super(); Ember.Logger.log('Event is ' + this.get('eventName')); } }); ``` NOTE: If you do override `init` for a framework class like `Ember.View` or `Ember.ArrayController`, be sure to call `this._super()` in your `init` declaration! If you don't, Ember may not have an opportunity to do important setup work, and you'll see strange behavior in your application. @method init
[ "this", "is", "doc", "ed", "here", "so", "it", "shows", "up", "in", "the", "events", "section", "of", "the", "API", "documentation", "which", "is", "where", "people", "will", "likely", "go", "looking", "for", "it", ".", "Triggers", "the", "LinkView", "s", "routing", "behavior", ".", "If", "eventName", "is", "changed", "to", "a", "value", "other", "than", "click", "the", "routing", "behavior", "will", "trigger", "on", "that", "custom", "event", "instead", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L20594-L20602
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(){ var helperParameters = this.parameters; var linkTextPath = helperParameters.options.linkTextPath; var paths = getResolvedPaths(helperParameters); var length = paths.length; var path, i, normalizedPath; if (linkTextPath) { normalizedPath = getNormalizedPath(linkTextPath, helperParameters); this.registerObserver(normalizedPath.root, normalizedPath.path, this, this.rerender); } for(i=0; i < length; i++) { path = paths[i]; if (null === path) { // A literal value was provided, not a path, so nothing to observe. continue; } normalizedPath = getNormalizedPath(path, helperParameters); this.registerObserver(normalizedPath.root, normalizedPath.path, this, this._paramsChanged); } var queryParamsObject = this.queryParamsObject; if (queryParamsObject) { var values = queryParamsObject.values; // Install observers for all of the hash options // provided in the (query-params) subexpression. for (var k in values) { if (!values.hasOwnProperty(k)) { continue; } if (queryParamsObject.types[k] === 'ID') { normalizedPath = getNormalizedPath(values[k], helperParameters); this.registerObserver(normalizedPath.root, normalizedPath.path, this, this._paramsChanged); } } } }
javascript
function(){ var helperParameters = this.parameters; var linkTextPath = helperParameters.options.linkTextPath; var paths = getResolvedPaths(helperParameters); var length = paths.length; var path, i, normalizedPath; if (linkTextPath) { normalizedPath = getNormalizedPath(linkTextPath, helperParameters); this.registerObserver(normalizedPath.root, normalizedPath.path, this, this.rerender); } for(i=0; i < length; i++) { path = paths[i]; if (null === path) { // A literal value was provided, not a path, so nothing to observe. continue; } normalizedPath = getNormalizedPath(path, helperParameters); this.registerObserver(normalizedPath.root, normalizedPath.path, this, this._paramsChanged); } var queryParamsObject = this.queryParamsObject; if (queryParamsObject) { var values = queryParamsObject.values; // Install observers for all of the hash options // provided in the (query-params) subexpression. for (var k in values) { if (!values.hasOwnProperty(k)) { continue; } if (queryParamsObject.types[k] === 'ID') { normalizedPath = getNormalizedPath(values[k], helperParameters); this.registerObserver(normalizedPath.root, normalizedPath.path, this, this._paramsChanged); } } } }
[ "function", "(", ")", "{", "var", "helperParameters", "=", "this", ".", "parameters", ";", "var", "linkTextPath", "=", "helperParameters", ".", "options", ".", "linkTextPath", ";", "var", "paths", "=", "getResolvedPaths", "(", "helperParameters", ")", ";", "var", "length", "=", "paths", ".", "length", ";", "var", "path", ",", "i", ",", "normalizedPath", ";", "if", "(", "linkTextPath", ")", "{", "normalizedPath", "=", "getNormalizedPath", "(", "linkTextPath", ",", "helperParameters", ")", ";", "this", ".", "registerObserver", "(", "normalizedPath", ".", "root", ",", "normalizedPath", ".", "path", ",", "this", ",", "this", ".", "rerender", ")", ";", "}", "for", "(", "i", "=", "0", ";", "i", "<", "length", ";", "i", "++", ")", "{", "path", "=", "paths", "[", "i", "]", ";", "if", "(", "null", "===", "path", ")", "{", "continue", ";", "}", "normalizedPath", "=", "getNormalizedPath", "(", "path", ",", "helperParameters", ")", ";", "this", ".", "registerObserver", "(", "normalizedPath", ".", "root", ",", "normalizedPath", ".", "path", ",", "this", ",", "this", ".", "_paramsChanged", ")", ";", "}", "var", "queryParamsObject", "=", "this", ".", "queryParamsObject", ";", "if", "(", "queryParamsObject", ")", "{", "var", "values", "=", "queryParamsObject", ".", "values", ";", "for", "(", "var", "k", "in", "values", ")", "{", "if", "(", "!", "values", ".", "hasOwnProperty", "(", "k", ")", ")", "{", "continue", ";", "}", "if", "(", "queryParamsObject", ".", "types", "[", "k", "]", "===", "'ID'", ")", "{", "normalizedPath", "=", "getNormalizedPath", "(", "values", "[", "k", "]", ",", "helperParameters", ")", ";", "this", ".", "registerObserver", "(", "normalizedPath", ".", "root", ",", "normalizedPath", ".", "path", ",", "this", ",", "this", ".", "_paramsChanged", ")", ";", "}", "}", "}", "}" ]
This is called to setup observers that will trigger a rerender. @private @method _setupPathObservers @since 1.3.0
[ "This", "is", "called", "to", "setup", "observers", "that", "will", "trigger", "a", "rerender", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L20623-L20661
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(params, transition) { var match, name, sawParams, value; var queryParams = get(this, '_qp.map'); for (var prop in params) { if (prop === 'queryParams' || (queryParams && prop in queryParams)) { continue; } if (match = prop.match(/^(.*)_id$/)) { name = match[1]; value = params[prop]; } sawParams = true; } if (!name && sawParams) { return copy(params); } else if (!name) { if (transition.resolveIndex < 1) { return; } var parentModel = transition.state.handlerInfos[transition.resolveIndex-1].context; return parentModel; } return this.findModel(name, value); }
javascript
function(params, transition) { var match, name, sawParams, value; var queryParams = get(this, '_qp.map'); for (var prop in params) { if (prop === 'queryParams' || (queryParams && prop in queryParams)) { continue; } if (match = prop.match(/^(.*)_id$/)) { name = match[1]; value = params[prop]; } sawParams = true; } if (!name && sawParams) { return copy(params); } else if (!name) { if (transition.resolveIndex < 1) { return; } var parentModel = transition.state.handlerInfos[transition.resolveIndex-1].context; return parentModel; } return this.findModel(name, value); }
[ "function", "(", "params", ",", "transition", ")", "{", "var", "match", ",", "name", ",", "sawParams", ",", "value", ";", "var", "queryParams", "=", "get", "(", "this", ",", "'_qp.map'", ")", ";", "for", "(", "var", "prop", "in", "params", ")", "{", "if", "(", "prop", "===", "'queryParams'", "||", "(", "queryParams", "&&", "prop", "in", "queryParams", ")", ")", "{", "continue", ";", "}", "if", "(", "match", "=", "prop", ".", "match", "(", "/", "^(.*)_id$", "/", ")", ")", "{", "name", "=", "match", "[", "1", "]", ";", "value", "=", "params", "[", "prop", "]", ";", "}", "sawParams", "=", "true", ";", "}", "if", "(", "!", "name", "&&", "sawParams", ")", "{", "return", "copy", "(", "params", ")", ";", "}", "else", "if", "(", "!", "name", ")", "{", "if", "(", "transition", ".", "resolveIndex", "<", "1", ")", "{", "return", ";", "}", "var", "parentModel", "=", "transition", ".", "state", ".", "handlerInfos", "[", "transition", ".", "resolveIndex", "-", "1", "]", ".", "context", ";", "return", "parentModel", ";", "}", "return", "this", ".", "findModel", "(", "name", ",", "value", ")", ";", "}" ]
A hook you can implement to convert the URL into the model for this route. ```js App.Router.map(function() { this.resource('post', {path: '/posts/:post_id'}); }); ``` The model for the `post` route is `store.find('post', params.post_id)`. By default, if your route has a dynamic segment ending in `_id`: The model class is determined from the segment (`post_id`'s class is `App.Post`) The find method is called on the model class with the value of the dynamic segment. Note that for routes with dynamic segments, this hook is not always executed. If the route is entered through a transition (e.g. when using the `link-to` Handlebars helper or the `transitionTo` method of routes), and a model context is already provided this hook is not called. A model context does not include a primitive string or number, which does cause the model hook to be called. Routes without dynamic segments will always execute the model hook. ```js no dynamic segment, model hook always called this.transitionTo('posts'); model passed in, so model hook not called thePost = store.find('post', 1); this.transitionTo('post', thePost); integer passed in, model hook is called this.transitionTo('post', 1); ``` This hook follows the asynchronous/promise semantics described in the documentation for `beforeModel`. In particular, if a promise returned from `model` fails, the error will be handled by the `error` hook on `Ember.Route`. Example ```js App.PostRoute = Ember.Route.extend({ model: function(params) { return this.store.find('post', params.post_id); } }); ``` @method model @param {Object} params the parameters extracted from the URL @param {Transition} transition @param {Object} queryParams the query params for this route @return {Object|Promise} the model for this route. If a promise is returned, the transition will pause until the promise resolves, and the resolved value of the promise will be used as the model for this route.
[ "A", "hook", "you", "can", "implement", "to", "convert", "the", "URL", "into", "the", "model", "for", "this", "route", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L24873-L24900
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(name, model) { var container = this.container; model = model || this.modelFor(name); return generateController(container, name, model); }
javascript
function(name, model) { var container = this.container; model = model || this.modelFor(name); return generateController(container, name, model); }
[ "function", "(", "name", ",", "model", ")", "{", "var", "container", "=", "this", ".", "container", ";", "model", "=", "model", "||", "this", ".", "modelFor", "(", "name", ")", ";", "return", "generateController", "(", "container", ",", "name", ",", "model", ")", ";", "}" ]
Generates a controller for a route. If the optional model is passed then the controller type is determined automatically, e.g., an ArrayController for arrays. Example ```js App.PostRoute = Ember.Route.extend({ setupController: function(controller, post) { this._super(controller, post); this.generateController('posts', post); } }); ``` @method generateController @param {String} name the name of the controller @param {Object} model the model to infer the type of the controller (optional)
[ "Generates", "a", "controller", "for", "a", "route", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L25150-L25156
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(infos) { updatePaths(this); this._cancelLoadingEvent(); this.notifyPropertyChange('url'); // Put this in the runloop so url will be accurate. Seems // less surprising than didTransition being out of sync. run.once(this, this.trigger, 'didTransition'); if (get(this, 'namespace').LOG_TRANSITIONS) { Ember.Logger.log("Transitioned into '" + EmberRouter._routePath(infos) + "'"); } }
javascript
function(infos) { updatePaths(this); this._cancelLoadingEvent(); this.notifyPropertyChange('url'); // Put this in the runloop so url will be accurate. Seems // less surprising than didTransition being out of sync. run.once(this, this.trigger, 'didTransition'); if (get(this, 'namespace').LOG_TRANSITIONS) { Ember.Logger.log("Transitioned into '" + EmberRouter._routePath(infos) + "'"); } }
[ "function", "(", "infos", ")", "{", "updatePaths", "(", "this", ")", ";", "this", ".", "_cancelLoadingEvent", "(", ")", ";", "this", ".", "notifyPropertyChange", "(", "'url'", ")", ";", "run", ".", "once", "(", "this", ",", "this", ".", "trigger", ",", "'didTransition'", ")", ";", "if", "(", "get", "(", "this", ",", "'namespace'", ")", ".", "LOG_TRANSITIONS", ")", "{", "Ember", ".", "Logger", ".", "log", "(", "\"Transitioned into '\"", "+", "EmberRouter", ".", "_routePath", "(", "infos", ")", "+", "\"'\"", ")", ";", "}", "}" ]
Handles updating the paths and notifying any listeners of the URL change. Triggers the router level `didTransition` hook. @method didTransition @private @since 1.2.0
[ "Handles", "updating", "the", "paths", "and", "notifying", "any", "listeners", "of", "the", "URL", "change", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L25804-L25818
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(routeName, models, queryParams) { var router = this.router; return router.isActive.apply(router, arguments); }
javascript
function(routeName, models, queryParams) { var router = this.router; return router.isActive.apply(router, arguments); }
[ "function", "(", "routeName", ",", "models", ",", "queryParams", ")", "{", "var", "router", "=", "this", ".", "router", ";", "return", "router", ".", "isActive", ".", "apply", "(", "router", ",", "arguments", ")", ";", "}" ]
An alternative form of `isActive` that doesn't require manual concatenation of the arguments into a single array. @method isActiveIntent @param routeName @param models @param queryParams @return {Boolean} @private @since 1.7.0
[ "An", "alternative", "form", "of", "isActive", "that", "doesn", "t", "require", "manual", "concatenation", "of", "the", "arguments", "into", "a", "single", "array", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L25893-L25896
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(callback) { var router = this.router; if (!router) { router = new Router(); router._triggerWillChangeContext = Ember.K; router._triggerWillLeave = Ember.K; router.callbacks = []; router.triggerEvent = triggerEvent; this.reopenClass({ router: router }); } var dsl = EmberRouterDSL.map(function() { this.resource('application', { path: "/" }, function() { for (var i=0; i < router.callbacks.length; i++) { router.callbacks[i].call(this); } callback.call(this); }); }); router.callbacks.push(callback); router.map(dsl.generate()); return router; }
javascript
function(callback) { var router = this.router; if (!router) { router = new Router(); router._triggerWillChangeContext = Ember.K; router._triggerWillLeave = Ember.K; router.callbacks = []; router.triggerEvent = triggerEvent; this.reopenClass({ router: router }); } var dsl = EmberRouterDSL.map(function() { this.resource('application', { path: "/" }, function() { for (var i=0; i < router.callbacks.length; i++) { router.callbacks[i].call(this); } callback.call(this); }); }); router.callbacks.push(callback); router.map(dsl.generate()); return router; }
[ "function", "(", "callback", ")", "{", "var", "router", "=", "this", ".", "router", ";", "if", "(", "!", "router", ")", "{", "router", "=", "new", "Router", "(", ")", ";", "router", ".", "_triggerWillChangeContext", "=", "Ember", ".", "K", ";", "router", ".", "_triggerWillLeave", "=", "Ember", ".", "K", ";", "router", ".", "callbacks", "=", "[", "]", ";", "router", ".", "triggerEvent", "=", "triggerEvent", ";", "this", ".", "reopenClass", "(", "{", "router", ":", "router", "}", ")", ";", "}", "var", "dsl", "=", "EmberRouterDSL", ".", "map", "(", "function", "(", ")", "{", "this", ".", "resource", "(", "'application'", ",", "{", "path", ":", "\"/\"", "}", ",", "function", "(", ")", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "router", ".", "callbacks", ".", "length", ";", "i", "++", ")", "{", "router", ".", "callbacks", "[", "i", "]", ".", "call", "(", "this", ")", ";", "}", "callback", ".", "call", "(", "this", ")", ";", "}", ")", ";", "}", ")", ";", "router", ".", "callbacks", ".", "push", "(", "callback", ")", ";", "router", ".", "map", "(", "dsl", ".", "generate", "(", ")", ")", ";", "return", "router", ";", "}" ]
The `Router.map` function allows you to define mappings from URLs to routes and resources in your application. These mappings are defined within the supplied callback function using `this.resource` and `this.route`. ```javascript App.Router.map(function({ this.route('about'); this.resource('article'); })); ``` For more detailed examples please see [the guides](http://emberjs.com/guides/routing/defining-your-routes/). @method map @param callback
[ "The", "Router", ".", "map", "function", "allows", "you", "to", "define", "mappings", "from", "URLs", "to", "routes", "and", "resources", "in", "your", "application", ".", "These", "mappings", "are", "defined", "within", "the", "supplied", "callback", "function", "using", "this", ".", "resource", "and", "this", ".", "route", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L26432-L26459
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
map
function map(dependentKey, callback) { var options = { addedItem: function(array, item, changeMeta, instanceMeta) { var mapped = callback.call(this, item, changeMeta.index); array.insertAt(changeMeta.index, mapped); return array; }, removedItem: function(array, item, changeMeta, instanceMeta) { array.removeAt(changeMeta.index, 1); return array; } }; return arrayComputed(dependentKey, options); }
javascript
function map(dependentKey, callback) { var options = { addedItem: function(array, item, changeMeta, instanceMeta) { var mapped = callback.call(this, item, changeMeta.index); array.insertAt(changeMeta.index, mapped); return array; }, removedItem: function(array, item, changeMeta, instanceMeta) { array.removeAt(changeMeta.index, 1); return array; } }; return arrayComputed(dependentKey, options); }
[ "function", "map", "(", "dependentKey", ",", "callback", ")", "{", "var", "options", "=", "{", "addedItem", ":", "function", "(", "array", ",", "item", ",", "changeMeta", ",", "instanceMeta", ")", "{", "var", "mapped", "=", "callback", ".", "call", "(", "this", ",", "item", ",", "changeMeta", ".", "index", ")", ";", "array", ".", "insertAt", "(", "changeMeta", ".", "index", ",", "mapped", ")", ";", "return", "array", ";", "}", ",", "removedItem", ":", "function", "(", "array", ",", "item", ",", "changeMeta", ",", "instanceMeta", ")", "{", "array", ".", "removeAt", "(", "changeMeta", ".", "index", ",", "1", ")", ";", "return", "array", ";", "}", "}", ";", "return", "arrayComputed", "(", "dependentKey", ",", "options", ")", ";", "}" ]
Returns an array mapped via the callback The callback method you provide should have the following signature. `item` is the current item in the iteration. `index` is the integer index of the current item in the iteration. ```javascript function(item, index); ``` Example ```javascript var Hamster = Ember.Object.extend({ excitingChores: Ember.computed.map('chores', function(chore, index) { return chore.toUpperCase() + '!'; }) }); var hamster = Hamster.create({ chores: ['clean', 'write more unit tests'] }); hamster.get('excitingChores'); // ['CLEAN!', 'WRITE MORE UNIT TESTS!'] ``` @method computed.map @for Ember @param {String} dependentKey @param {Function} callback @return {Ember.ComputedProperty} an array mapped via the callback
[ "Returns", "an", "array", "mapped", "via", "the", "callback" ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L28050-L28064
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
sort
function sort(itemsKey, sortDefinition) { Ember.assert('Ember.computed.sort requires two arguments: an array key to sort and ' + 'either a sort properties key or sort function', arguments.length === 2); if (typeof sortDefinition === 'function') { return customSort(itemsKey, sortDefinition); } else { return propertySort(itemsKey, sortDefinition); } }
javascript
function sort(itemsKey, sortDefinition) { Ember.assert('Ember.computed.sort requires two arguments: an array key to sort and ' + 'either a sort properties key or sort function', arguments.length === 2); if (typeof sortDefinition === 'function') { return customSort(itemsKey, sortDefinition); } else { return propertySort(itemsKey, sortDefinition); } }
[ "function", "sort", "(", "itemsKey", ",", "sortDefinition", ")", "{", "Ember", ".", "assert", "(", "'Ember.computed.sort requires two arguments: an array key to sort and '", "+", "'either a sort properties key or sort function'", ",", "arguments", ".", "length", "===", "2", ")", ";", "if", "(", "typeof", "sortDefinition", "===", "'function'", ")", "{", "return", "customSort", "(", "itemsKey", ",", "sortDefinition", ")", ";", "}", "else", "{", "return", "propertySort", "(", "itemsKey", ",", "sortDefinition", ")", ";", "}", "}" ]
A computed property which returns a new array with all the properties from the first dependent array sorted based on a property or sort function. The callback method you provide should have the following signature: ```javascript function(itemA, itemB); ``` - `itemA` the first item to compare. - `itemB` the second item to compare. This function should return negative number (e.g. `-1`) when `itemA` should come before `itemB`. It should return positive number (e.g. `1`) when `itemA` should come after `itemB`. If the `itemA` and `itemB` are equal this function should return `0`. Therefore, if this function is comparing some numeric values, simple `itemA - itemB` or `itemA.get( 'foo' ) - itemB.get( 'foo' )` can be used instead of series of `if`. Example ```javascript var ToDoList = Ember.Object.extend({ using standard ascending sort todosSorting: ['name'], sortedTodos: Ember.computed.sort('todos', 'todosSorting'), using descending sort todosSortingDesc: ['name:desc'], sortedTodosDesc: Ember.computed.sort('todos', 'todosSortingDesc'), using a custom sort function priorityTodos: Ember.computed.sort('todos', function(a, b){ if (a.priority > b.priority) { return 1; } else if (a.priority < b.priority) { return -1; } return 0; }) }); var todoList = ToDoList.create({todos: [ { name: 'Unit Test', priority: 2 }, { name: 'Documentation', priority: 3 }, { name: 'Release', priority: 1 } ]}); todoList.get('sortedTodos'); // [{ name:'Documentation', priority:3 }, { name:'Release', priority:1 }, { name:'Unit Test', priority:2 }] todoList.get('sortedTodosDesc'); // [{ name:'Unit Test', priority:2 }, { name:'Release', priority:1 }, { name:'Documentation', priority:3 }] todoList.get('priorityTodos'); // [{ name:'Release', priority:1 }, { name:'Unit Test', priority:2 }, { name:'Documentation', priority:3 }] ``` @method computed.sort @for Ember @param {String} dependentKey @param {String or Function} sortDefinition a dependent key to an array of sort properties (add `:desc` to the arrays sort properties to sort descending) or a function to use when sorting @return {Ember.ComputedProperty} computes a new sorted array based on the sort property array or callback function
[ "A", "computed", "property", "which", "returns", "a", "new", "array", "with", "all", "the", "properties", "from", "the", "first", "dependent", "array", "sorted", "based", "on", "a", "property", "or", "sort", "function", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L28558-L28567
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(actionName) { var args = [].slice.call(arguments, 1); var target; if (this._actions && this._actions[actionName]) { if (this._actions[actionName].apply(this, args) === true) { // handler returned true, so this action will bubble } else { return; } } if (target = get(this, 'target')) { Ember.assert("The `target` for " + this + " (" + target + ") does not have a `send` method", typeof target.send === 'function'); target.send.apply(target, arguments); } }
javascript
function(actionName) { var args = [].slice.call(arguments, 1); var target; if (this._actions && this._actions[actionName]) { if (this._actions[actionName].apply(this, args) === true) { // handler returned true, so this action will bubble } else { return; } } if (target = get(this, 'target')) { Ember.assert("The `target` for " + this + " (" + target + ") does not have a `send` method", typeof target.send === 'function'); target.send.apply(target, arguments); } }
[ "function", "(", "actionName", ")", "{", "var", "args", "=", "[", "]", ".", "slice", ".", "call", "(", "arguments", ",", "1", ")", ";", "var", "target", ";", "if", "(", "this", ".", "_actions", "&&", "this", ".", "_actions", "[", "actionName", "]", ")", "{", "if", "(", "this", ".", "_actions", "[", "actionName", "]", ".", "apply", "(", "this", ",", "args", ")", "===", "true", ")", "{", "}", "else", "{", "return", ";", "}", "}", "if", "(", "target", "=", "get", "(", "this", ",", "'target'", ")", ")", "{", "Ember", ".", "assert", "(", "\"The `target` for \"", "+", "this", "+", "\" (\"", "+", "target", "+", "\") does not have a `send` method\"", ",", "typeof", "target", ".", "send", "===", "'function'", ")", ";", "target", ".", "send", ".", "apply", "(", "target", ",", "arguments", ")", ";", "}", "}" ]
Triggers a named action on the `ActionHandler`. Any parameters supplied after the `actionName` string will be passed as arguments to the action target function. If the `ActionHandler` has its `target` property set, actions may bubble to the `target`. Bubbling happens when an `actionName` can not be found in the `ActionHandler`'s `actions` hash or if the action target function returns `true`. Example ```js App.WelcomeRoute = Ember.Route.extend({ actions: { playTheme: function() { this.send('playMusic', 'theme.mp3'); }, playMusic: function(track) { ... } } }); ``` @method send @param {String} actionName The action to trigger @param {*} context a context to send with the action
[ "Triggers", "a", "named", "action", "on", "the", "ActionHandler", ".", "Any", "parameters", "supplied", "after", "the", "actionName", "string", "will", "be", "passed", "as", "arguments", "to", "the", "action", "target", "function", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L29893-L29909
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(removing, adding) { var removeCnt, addCnt, hasDelta; if ('number' === typeof removing) removeCnt = removing; else if (removing) removeCnt = get(removing, 'length'); else removeCnt = removing = -1; if ('number' === typeof adding) addCnt = adding; else if (adding) addCnt = get(adding,'length'); else addCnt = adding = -1; hasDelta = addCnt<0 || removeCnt<0 || addCnt-removeCnt!==0; if (removing === -1) removing = null; if (adding === -1) adding = null; propertyWillChange(this, '[]'); if (hasDelta) propertyWillChange(this, 'length'); sendEvent(this, '@enumerable:before', [this, removing, adding]); return this; }
javascript
function(removing, adding) { var removeCnt, addCnt, hasDelta; if ('number' === typeof removing) removeCnt = removing; else if (removing) removeCnt = get(removing, 'length'); else removeCnt = removing = -1; if ('number' === typeof adding) addCnt = adding; else if (adding) addCnt = get(adding,'length'); else addCnt = adding = -1; hasDelta = addCnt<0 || removeCnt<0 || addCnt-removeCnt!==0; if (removing === -1) removing = null; if (adding === -1) adding = null; propertyWillChange(this, '[]'); if (hasDelta) propertyWillChange(this, 'length'); sendEvent(this, '@enumerable:before', [this, removing, adding]); return this; }
[ "function", "(", "removing", ",", "adding", ")", "{", "var", "removeCnt", ",", "addCnt", ",", "hasDelta", ";", "if", "(", "'number'", "===", "typeof", "removing", ")", "removeCnt", "=", "removing", ";", "else", "if", "(", "removing", ")", "removeCnt", "=", "get", "(", "removing", ",", "'length'", ")", ";", "else", "removeCnt", "=", "removing", "=", "-", "1", ";", "if", "(", "'number'", "===", "typeof", "adding", ")", "addCnt", "=", "adding", ";", "else", "if", "(", "adding", ")", "addCnt", "=", "get", "(", "adding", ",", "'length'", ")", ";", "else", "addCnt", "=", "adding", "=", "-", "1", ";", "hasDelta", "=", "addCnt", "<", "0", "||", "removeCnt", "<", "0", "||", "addCnt", "-", "removeCnt", "!==", "0", ";", "if", "(", "removing", "===", "-", "1", ")", "removing", "=", "null", ";", "if", "(", "adding", "===", "-", "1", ")", "adding", "=", "null", ";", "propertyWillChange", "(", "this", ",", "'[]'", ")", ";", "if", "(", "hasDelta", ")", "propertyWillChange", "(", "this", ",", "'length'", ")", ";", "sendEvent", "(", "this", ",", "'@enumerable:before'", ",", "[", "this", ",", "removing", ",", "adding", "]", ")", ";", "return", "this", ";", "}" ]
Invoke this method just before the contents of your enumerable will change. You can either omit the parameters completely or pass the objects to be removed or added if available or just a count. @method enumerableContentWillChange @param {Ember.Enumerable|Number} removing An enumerable of the objects to be removed or the number of items to be removed. @param {Ember.Enumerable|Number} adding An enumerable of the objects to be added or the number of items to be added. @chainable
[ "Invoke", "this", "method", "just", "before", "the", "contents", "of", "your", "enumerable", "will", "change", ".", "You", "can", "either", "omit", "the", "parameters", "completely", "or", "pass", "the", "objects", "to", "be", "removed", "or", "added", "if", "available", "or", "just", "a", "count", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L31705-L31727
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(name, target, method) { if (!method) { method = target; target = null; } addListener(this, name, target, method, true); return this; }
javascript
function(name, target, method) { if (!method) { method = target; target = null; } addListener(this, name, target, method, true); return this; }
[ "function", "(", "name", ",", "target", ",", "method", ")", "{", "if", "(", "!", "method", ")", "{", "method", "=", "target", ";", "target", "=", "null", ";", "}", "addListener", "(", "this", ",", "name", ",", "target", ",", "method", ",", "true", ")", ";", "return", "this", ";", "}" ]
Subscribes a function to a named event and then cancels the subscription after the first time the event is triggered. It is good to use ``one`` when you only care about the first time an event has taken place. This function takes an optional 2nd argument that will become the "this" value for the callback. If this argument is passed then the 3rd argument becomes the function. @method one @param {String} name The name of the event @param {Object} [target] The "this" binding for the callback @param {Function} method The callback to execute @return this
[ "Subscribes", "a", "function", "to", "a", "named", "event", "and", "then", "cancels", "the", "subscription", "after", "the", "first", "time", "the", "event", "is", "triggered", ".", "It", "is", "good", "to", "use", "one", "when", "you", "only", "care", "about", "the", "first", "time", "an", "event", "has", "taken", "place", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L31885-L31893
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(name) { var length = arguments.length; var args = new Array(length - 1); for (var i = 1; i < length; i++) { args[i - 1] = arguments[i]; } sendEvent(this, name, args); }
javascript
function(name) { var length = arguments.length; var args = new Array(length - 1); for (var i = 1; i < length; i++) { args[i - 1] = arguments[i]; } sendEvent(this, name, args); }
[ "function", "(", "name", ")", "{", "var", "length", "=", "arguments", ".", "length", ";", "var", "args", "=", "new", "Array", "(", "length", "-", "1", ")", ";", "for", "(", "var", "i", "=", "1", ";", "i", "<", "length", ";", "i", "++", ")", "{", "args", "[", "i", "-", "1", "]", "=", "arguments", "[", "i", "]", ";", "}", "sendEvent", "(", "this", ",", "name", ",", "args", ")", ";", "}" ]
Triggers a named event for the object. Any additional arguments will be passed as parameters to the functions that are subscribed to the event. ```javascript person.on('didEat', function(food) { console.log('person ate some ' + food); }); person.trigger('didEat', 'broccoli'); outputs: person ate some broccoli ``` @method trigger @param {String} name The name of the event @param {Object...} args Optional arguments to pass on
[ "Triggers", "a", "named", "event", "for", "the", "object", ".", "Any", "additional", "arguments", "will", "be", "passed", "as", "parameters", "to", "the", "functions", "that", "are", "subscribed", "to", "the", "event", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L31913-L31922
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(objects) { if (!(Enumerable.detect(objects) || isArray(objects))) { throw new TypeError("Must pass Ember.Enumerable to Ember.MutableArray#pushObjects"); } this.replace(get(this, 'length'), 0, objects); return this; }
javascript
function(objects) { if (!(Enumerable.detect(objects) || isArray(objects))) { throw new TypeError("Must pass Ember.Enumerable to Ember.MutableArray#pushObjects"); } this.replace(get(this, 'length'), 0, objects); return this; }
[ "function", "(", "objects", ")", "{", "if", "(", "!", "(", "Enumerable", ".", "detect", "(", "objects", ")", "||", "isArray", "(", "objects", ")", ")", ")", "{", "throw", "new", "TypeError", "(", "\"Must pass Ember.Enumerable to Ember.MutableArray#pushObjects\"", ")", ";", "}", "this", ".", "replace", "(", "get", "(", "this", ",", "'length'", ")", ",", "0", ",", "objects", ")", ";", "return", "this", ";", "}" ]
Add the objects in the passed numerable to the end of the array. Defers notifying observers of the change until all objects are added. ```javascript var colors = ["red"]; colors.pushObjects(["yellow", "orange"]); // ["red", "yellow", "orange"] ``` @method pushObjects @param {Ember.Enumerable} objects the objects to add @return {Ember.Array} receiver
[ "Add", "the", "objects", "in", "the", "passed", "numerable", "to", "the", "end", "of", "the", "array", ".", "Defers", "notifying", "observers", "of", "the", "change", "until", "all", "objects", "are", "added", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L32228-L32234
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(objects) { beginPropertyChanges(this); for (var i = objects.length - 1; i >= 0; i--) { this.removeObject(objects[i]); } endPropertyChanges(this); return this; }
javascript
function(objects) { beginPropertyChanges(this); for (var i = objects.length - 1; i >= 0; i--) { this.removeObject(objects[i]); } endPropertyChanges(this); return this; }
[ "function", "(", "objects", ")", "{", "beginPropertyChanges", "(", "this", ")", ";", "for", "(", "var", "i", "=", "objects", ".", "length", "-", "1", ";", "i", ">=", "0", ";", "i", "--", ")", "{", "this", ".", "removeObject", "(", "objects", "[", "i", "]", ")", ";", "}", "endPropertyChanges", "(", "this", ")", ";", "return", "this", ";", "}" ]
Removes each object in the passed enumerable from the receiver. @method removeObjects @param {Ember.Enumerable} objects the objects to remove @return {Object} receiver
[ "Removes", "each", "object", "in", "the", "passed", "enumerable", "from", "the", "receiver", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L32513-L32520
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function() { var C = this; var l = arguments.length; if (l > 0) { var args = new Array(l); for (var i = 0; i < l; i++) { args[i] = arguments[i]; } this._initProperties(args); } return new C(); }
javascript
function() { var C = this; var l = arguments.length; if (l > 0) { var args = new Array(l); for (var i = 0; i < l; i++) { args[i] = arguments[i]; } this._initProperties(args); } return new C(); }
[ "function", "(", ")", "{", "var", "C", "=", "this", ";", "var", "l", "=", "arguments", ".", "length", ";", "if", "(", "l", ">", "0", ")", "{", "var", "args", "=", "new", "Array", "(", "l", ")", ";", "for", "(", "var", "i", "=", "0", ";", "i", "<", "l", ";", "i", "++", ")", "{", "args", "[", "i", "]", "=", "arguments", "[", "i", "]", ";", "}", "this", ".", "_initProperties", "(", "args", ")", ";", "}", "return", "new", "C", "(", ")", ";", "}" ]
Creates an instance of a class. Accepts either no arguments, or an object containing values to initialize the newly instantiated object with. ```javascript App.Person = Ember.Object.extend({ helloWorld: function() { alert("Hi, my name is " + this.get('name')); } }); var tom = App.Person.create({ name: 'Tom Dale' }); tom.helloWorld(); // alerts "Hi, my name is Tom Dale". ``` `create` will call the `init` function if defined during `Ember.AnyObject.extend` If no arguments are passed to `create`, it will not set values to the new instance during initialization: ```javascript var noName = App.Person.create(); noName.helloWorld(); // alerts undefined ``` NOTE: For performance reasons, you cannot declare methods or computed properties during `create`. You should instead declare methods and computed properties when using `extend` or use the `createWithMixins` shorthand. @method create @static @param [arguments]*
[ "Creates", "an", "instance", "of", "a", "class", ".", "Accepts", "either", "no", "arguments", "or", "an", "object", "containing", "values", "to", "initialize", "the", "newly", "instantiated", "object", "with", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L34719-L34730
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(obj) { // fail fast if (!Enumerable.detect(obj)) return false; var loc = get(this, 'length'); if (get(obj, 'length') !== loc) return false; while(--loc >= 0) { if (!obj.contains(this[loc])) return false; } return true; }
javascript
function(obj) { // fail fast if (!Enumerable.detect(obj)) return false; var loc = get(this, 'length'); if (get(obj, 'length') !== loc) return false; while(--loc >= 0) { if (!obj.contains(this[loc])) return false; } return true; }
[ "function", "(", "obj", ")", "{", "if", "(", "!", "Enumerable", ".", "detect", "(", "obj", ")", ")", "return", "false", ";", "var", "loc", "=", "get", "(", "this", ",", "'length'", ")", ";", "if", "(", "get", "(", "obj", ",", "'length'", ")", "!==", "loc", ")", "return", "false", ";", "while", "(", "--", "loc", ">=", "0", ")", "{", "if", "(", "!", "obj", ".", "contains", "(", "this", "[", "loc", "]", ")", ")", "return", "false", ";", "}", "return", "true", ";", "}" ]
Returns true if the passed object is also an enumerable that contains the same objects as the receiver. ```javascript var colors = ["red", "green", "blue"], same_colors = new Ember.Set(colors); same_colors.isEqual(colors); // true same_colors.isEqual(["purple", "brown"]); // false ``` @method isEqual @param {Ember.Set} obj the other object. @return {Boolean}
[ "Returns", "true", "if", "the", "passed", "object", "is", "also", "an", "enumerable", "that", "contains", "the", "same", "objects", "as", "the", "receiver", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L35999-L36011
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function() { if (get(this, 'isFrozen')) throw new EmberError(FROZEN_ERROR); var obj = this.length > 0 ? this[this.length-1] : null; this.remove(obj); return obj; }
javascript
function() { if (get(this, 'isFrozen')) throw new EmberError(FROZEN_ERROR); var obj = this.length > 0 ? this[this.length-1] : null; this.remove(obj); return obj; }
[ "function", "(", ")", "{", "if", "(", "get", "(", "this", ",", "'isFrozen'", ")", ")", "throw", "new", "EmberError", "(", "FROZEN_ERROR", ")", ";", "var", "obj", "=", "this", ".", "length", ">", "0", "?", "this", "[", "this", ".", "length", "-", "1", "]", ":", "null", ";", "this", ".", "remove", "(", "obj", ")", ";", "return", "obj", ";", "}" ]
Removes the last element from the set and returns it, or `null` if it's empty. ```javascript var colors = new Ember.Set(["green", "blue"]); colors.pop(); // "blue" colors.pop(); // "green" colors.pop(); // null ``` @method pop @return {Object} The removed object from the set or null.
[ "Removes", "the", "last", "element", "from", "the", "set", "and", "returns", "it", "or", "null", "if", "it", "s", "empty", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L36066-L36071
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function (index) { var split = false; var arrayOperationIndex, arrayOperation, arrayOperationRangeStart, arrayOperationRangeEnd, len; // OPTIMIZE: we could search these faster if we kept a balanced tree. // find leftmost arrayOperation to the right of `index` for (arrayOperationIndex = arrayOperationRangeStart = 0, len = this._operations.length; arrayOperationIndex < len; ++arrayOperationIndex) { arrayOperation = this._operations[arrayOperationIndex]; if (arrayOperation.type === DELETE) { continue; } arrayOperationRangeEnd = arrayOperationRangeStart + arrayOperation.count - 1; if (index === arrayOperationRangeStart) { break; } else if (index > arrayOperationRangeStart && index <= arrayOperationRangeEnd) { split = true; break; } else { arrayOperationRangeStart = arrayOperationRangeEnd + 1; } } return new ArrayOperationMatch(arrayOperation, arrayOperationIndex, split, arrayOperationRangeStart); }
javascript
function (index) { var split = false; var arrayOperationIndex, arrayOperation, arrayOperationRangeStart, arrayOperationRangeEnd, len; // OPTIMIZE: we could search these faster if we kept a balanced tree. // find leftmost arrayOperation to the right of `index` for (arrayOperationIndex = arrayOperationRangeStart = 0, len = this._operations.length; arrayOperationIndex < len; ++arrayOperationIndex) { arrayOperation = this._operations[arrayOperationIndex]; if (arrayOperation.type === DELETE) { continue; } arrayOperationRangeEnd = arrayOperationRangeStart + arrayOperation.count - 1; if (index === arrayOperationRangeStart) { break; } else if (index > arrayOperationRangeStart && index <= arrayOperationRangeEnd) { split = true; break; } else { arrayOperationRangeStart = arrayOperationRangeEnd + 1; } } return new ArrayOperationMatch(arrayOperation, arrayOperationIndex, split, arrayOperationRangeStart); }
[ "function", "(", "index", ")", "{", "var", "split", "=", "false", ";", "var", "arrayOperationIndex", ",", "arrayOperation", ",", "arrayOperationRangeStart", ",", "arrayOperationRangeEnd", ",", "len", ";", "for", "(", "arrayOperationIndex", "=", "arrayOperationRangeStart", "=", "0", ",", "len", "=", "this", ".", "_operations", ".", "length", ";", "arrayOperationIndex", "<", "len", ";", "++", "arrayOperationIndex", ")", "{", "arrayOperation", "=", "this", ".", "_operations", "[", "arrayOperationIndex", "]", ";", "if", "(", "arrayOperation", ".", "type", "===", "DELETE", ")", "{", "continue", ";", "}", "arrayOperationRangeEnd", "=", "arrayOperationRangeStart", "+", "arrayOperation", ".", "count", "-", "1", ";", "if", "(", "index", "===", "arrayOperationRangeStart", ")", "{", "break", ";", "}", "else", "if", "(", "index", ">", "arrayOperationRangeStart", "&&", "index", "<=", "arrayOperationRangeEnd", ")", "{", "split", "=", "true", ";", "break", ";", "}", "else", "{", "arrayOperationRangeStart", "=", "arrayOperationRangeEnd", "+", "1", ";", "}", "}", "return", "new", "ArrayOperationMatch", "(", "arrayOperation", ",", "arrayOperationIndex", ",", "split", ",", "arrayOperationRangeStart", ")", ";", "}" ]
Return an `ArrayOperationMatch` for the operation that contains the item at `index`. @method _findArrayOperation @param {Number} index the index of the item whose operation information should be returned. @private
[ "Return", "an", "ArrayOperationMatch", "for", "the", "operation", "that", "contains", "the", "item", "at", "index", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L36918-L36944
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(rootElement, event, eventName) { var self = this; rootElement.on(event + '.ember', '.ember-view', function(evt, triggeringManager) { var view = View.views[this.id]; var result = true; var manager = self.canDispatchToEventManager ? self._findNearestEventManager(view, eventName) : null; if (manager && manager !== triggeringManager) { result = self._dispatchEvent(manager, evt, eventName, view); } else if (view) { result = self._bubbleEvent(view, evt, eventName); } return result; }); rootElement.on(event + '.ember', '[data-ember-action]', function(evt) { var actionId = jQuery(evt.currentTarget).attr('data-ember-action'); var action = ActionManager.registeredActions[actionId]; // We have to check for action here since in some cases, jQuery will trigger // an event on `removeChild` (i.e. focusout) after we've already torn down the // action handlers for the view. if (action && action.eventName === eventName) { return action.handler(evt); } }); }
javascript
function(rootElement, event, eventName) { var self = this; rootElement.on(event + '.ember', '.ember-view', function(evt, triggeringManager) { var view = View.views[this.id]; var result = true; var manager = self.canDispatchToEventManager ? self._findNearestEventManager(view, eventName) : null; if (manager && manager !== triggeringManager) { result = self._dispatchEvent(manager, evt, eventName, view); } else if (view) { result = self._bubbleEvent(view, evt, eventName); } return result; }); rootElement.on(event + '.ember', '[data-ember-action]', function(evt) { var actionId = jQuery(evt.currentTarget).attr('data-ember-action'); var action = ActionManager.registeredActions[actionId]; // We have to check for action here since in some cases, jQuery will trigger // an event on `removeChild` (i.e. focusout) after we've already torn down the // action handlers for the view. if (action && action.eventName === eventName) { return action.handler(evt); } }); }
[ "function", "(", "rootElement", ",", "event", ",", "eventName", ")", "{", "var", "self", "=", "this", ";", "rootElement", ".", "on", "(", "event", "+", "'.ember'", ",", "'.ember-view'", ",", "function", "(", "evt", ",", "triggeringManager", ")", "{", "var", "view", "=", "View", ".", "views", "[", "this", ".", "id", "]", ";", "var", "result", "=", "true", ";", "var", "manager", "=", "self", ".", "canDispatchToEventManager", "?", "self", ".", "_findNearestEventManager", "(", "view", ",", "eventName", ")", ":", "null", ";", "if", "(", "manager", "&&", "manager", "!==", "triggeringManager", ")", "{", "result", "=", "self", ".", "_dispatchEvent", "(", "manager", ",", "evt", ",", "eventName", ",", "view", ")", ";", "}", "else", "if", "(", "view", ")", "{", "result", "=", "self", ".", "_bubbleEvent", "(", "view", ",", "evt", ",", "eventName", ")", ";", "}", "return", "result", ";", "}", ")", ";", "rootElement", ".", "on", "(", "event", "+", "'.ember'", ",", "'[data-ember-action]'", ",", "function", "(", "evt", ")", "{", "var", "actionId", "=", "jQuery", "(", "evt", ".", "currentTarget", ")", ".", "attr", "(", "'data-ember-action'", ")", ";", "var", "action", "=", "ActionManager", ".", "registeredActions", "[", "actionId", "]", ";", "if", "(", "action", "&&", "action", ".", "eventName", "===", "eventName", ")", "{", "return", "action", ".", "handler", "(", "evt", ")", ";", "}", "}", ")", ";", "}" ]
Registers an event listener on the rootElement. If the given event is triggered, the provided event handler will be triggered on the target view. If the target view does not implement the event handler, or if the handler returns `false`, the parent view will be called. The event will continue to bubble to each successive parent view until it reaches the top. @private @method setupHandler @param {Element} rootElement @param {String} event the browser-originated event to listen to @param {String} eventName the name of the method to call on the view
[ "Registers", "an", "event", "listener", "on", "the", "rootElement", ".", "If", "the", "given", "event", "is", "triggered", "the", "provided", "event", "handler", "will", "be", "triggered", "on", "the", "target", "view", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L38698-L38727
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(content, start, removedCount) { // If the contents were empty before and this template collection has an // empty view remove it now. var emptyView = get(this, 'emptyView'); if (emptyView && emptyView instanceof View) { emptyView.removeFromParent(); } // Loop through child views that correspond with the removed items. // Note that we loop from the end of the array to the beginning because // we are mutating it as we go. var childViews = this._childViews; var childView, idx; for (idx = start + removedCount - 1; idx >= start; idx--) { childView = childViews[idx]; childView.destroy(); } }
javascript
function(content, start, removedCount) { // If the contents were empty before and this template collection has an // empty view remove it now. var emptyView = get(this, 'emptyView'); if (emptyView && emptyView instanceof View) { emptyView.removeFromParent(); } // Loop through child views that correspond with the removed items. // Note that we loop from the end of the array to the beginning because // we are mutating it as we go. var childViews = this._childViews; var childView, idx; for (idx = start + removedCount - 1; idx >= start; idx--) { childView = childViews[idx]; childView.destroy(); } }
[ "function", "(", "content", ",", "start", ",", "removedCount", ")", "{", "var", "emptyView", "=", "get", "(", "this", ",", "'emptyView'", ")", ";", "if", "(", "emptyView", "&&", "emptyView", "instanceof", "View", ")", "{", "emptyView", ".", "removeFromParent", "(", ")", ";", "}", "var", "childViews", "=", "this", ".", "_childViews", ";", "var", "childView", ",", "idx", ";", "for", "(", "idx", "=", "start", "+", "removedCount", "-", "1", ";", "idx", ">=", "start", ";", "idx", "--", ")", "{", "childView", "=", "childViews", "[", "idx", "]", ";", "childView", ".", "destroy", "(", ")", ";", "}", "}" ]
Called when a mutation to the underlying content array will occur. This method will remove any views that are no longer in the underlying content array. Invokes whenever the content array itself will change. @method arrayWillChange @param {Array} content the managed collection of objects @param {Number} start the index at which the changes will occurr @param {Number} removed number of object to be removed from content
[ "Called", "when", "a", "mutation", "to", "the", "underlying", "content", "array", "will", "occur", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L39935-L39953
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(content, start, removed, added) { var addedViews = []; var view, item, idx, len, itemViewClass, emptyView; len = content ? get(content, 'length') : 0; if (len) { itemViewClass = get(this, 'itemViewClass'); itemViewClass = handlebarsGetView(content, itemViewClass, this.container); for (idx = start; idx < start+added; idx++) { item = content.objectAt(idx); view = this.createChildView(itemViewClass, { content: item, contentIndex: idx }); addedViews.push(view); } } else { emptyView = get(this, 'emptyView'); if (!emptyView) { return; } if ('string' === typeof emptyView && isGlobalPath(emptyView)) { emptyView = get(emptyView) || emptyView; } emptyView = this.createChildView(emptyView); addedViews.push(emptyView); set(this, 'emptyView', emptyView); if (CoreView.detect(emptyView)) { this._createdEmptyView = emptyView; } } this.replace(start, 0, addedViews); }
javascript
function(content, start, removed, added) { var addedViews = []; var view, item, idx, len, itemViewClass, emptyView; len = content ? get(content, 'length') : 0; if (len) { itemViewClass = get(this, 'itemViewClass'); itemViewClass = handlebarsGetView(content, itemViewClass, this.container); for (idx = start; idx < start+added; idx++) { item = content.objectAt(idx); view = this.createChildView(itemViewClass, { content: item, contentIndex: idx }); addedViews.push(view); } } else { emptyView = get(this, 'emptyView'); if (!emptyView) { return; } if ('string' === typeof emptyView && isGlobalPath(emptyView)) { emptyView = get(emptyView) || emptyView; } emptyView = this.createChildView(emptyView); addedViews.push(emptyView); set(this, 'emptyView', emptyView); if (CoreView.detect(emptyView)) { this._createdEmptyView = emptyView; } } this.replace(start, 0, addedViews); }
[ "function", "(", "content", ",", "start", ",", "removed", ",", "added", ")", "{", "var", "addedViews", "=", "[", "]", ";", "var", "view", ",", "item", ",", "idx", ",", "len", ",", "itemViewClass", ",", "emptyView", ";", "len", "=", "content", "?", "get", "(", "content", ",", "'length'", ")", ":", "0", ";", "if", "(", "len", ")", "{", "itemViewClass", "=", "get", "(", "this", ",", "'itemViewClass'", ")", ";", "itemViewClass", "=", "handlebarsGetView", "(", "content", ",", "itemViewClass", ",", "this", ".", "container", ")", ";", "for", "(", "idx", "=", "start", ";", "idx", "<", "start", "+", "added", ";", "idx", "++", ")", "{", "item", "=", "content", ".", "objectAt", "(", "idx", ")", ";", "view", "=", "this", ".", "createChildView", "(", "itemViewClass", ",", "{", "content", ":", "item", ",", "contentIndex", ":", "idx", "}", ")", ";", "addedViews", ".", "push", "(", "view", ")", ";", "}", "}", "else", "{", "emptyView", "=", "get", "(", "this", ",", "'emptyView'", ")", ";", "if", "(", "!", "emptyView", ")", "{", "return", ";", "}", "if", "(", "'string'", "===", "typeof", "emptyView", "&&", "isGlobalPath", "(", "emptyView", ")", ")", "{", "emptyView", "=", "get", "(", "emptyView", ")", "||", "emptyView", ";", "}", "emptyView", "=", "this", ".", "createChildView", "(", "emptyView", ")", ";", "addedViews", ".", "push", "(", "emptyView", ")", ";", "set", "(", "this", ",", "'emptyView'", ",", "emptyView", ")", ";", "if", "(", "CoreView", ".", "detect", "(", "emptyView", ")", ")", "{", "this", ".", "_createdEmptyView", "=", "emptyView", ";", "}", "}", "this", ".", "replace", "(", "start", ",", "0", ",", "addedViews", ")", ";", "}" ]
Called when a mutation to the underlying content array occurs. This method will replay that mutation against the views that compose the `Ember.CollectionView`, ensuring that the view reflects the model. This array observer is added in `contentDidChange`. @method arrayDidChange @param {Array} content the managed collection of objects @param {Number} start the index at which the changes occurred @param {Number} removed number of object removed from content @param {Number} added number of object added to content
[ "Called", "when", "a", "mutation", "to", "the", "underlying", "content", "array", "occurs", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L39969-L40008
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(classBindings) { var classNames = this.classNames; var elem, newClass, dasherizedClass; // Loop through all of the configured bindings. These will be either // property names ('isUrgent') or property paths relative to the view // ('content.isUrgent') forEach(classBindings, function(binding) { Ember.assert("classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. ['foo', ':bar']", binding.indexOf(' ') === -1); // Variable in which the old class value is saved. The observer function // closes over this variable, so it knows which string to remove when // the property changes. var oldClass; // Extract just the property name from bindings like 'foo:bar' var parsedPath = View._parsePropertyPath(binding); // Set up an observer on the context. If the property changes, toggle the // class name. var observer = function() { // Get the current value of the property newClass = this._classStringForProperty(binding); elem = this.$(); // If we had previously added a class to the element, remove it. if (oldClass) { elem.removeClass(oldClass); // Also remove from classNames so that if the view gets rerendered, // the class doesn't get added back to the DOM. classNames.removeObject(oldClass); } // If necessary, add a new class. Make sure we keep track of it so // it can be removed in the future. if (newClass) { elem.addClass(newClass); oldClass = newClass; } else { oldClass = null; } }; // Get the class name for the property at its current value dasherizedClass = this._classStringForProperty(binding); if (dasherizedClass) { // Ensure that it gets into the classNames array // so it is displayed when we render. addObject(classNames, dasherizedClass); // Save a reference to the class name so we can remove it // if the observer fires. Remember that this variable has // been closed over by the observer. oldClass = dasherizedClass; } this.registerObserver(this, parsedPath.path, observer); // Remove className so when the view is rerendered, // the className is added based on binding reevaluation this.one('willClearRender', function() { if (oldClass) { classNames.removeObject(oldClass); oldClass = null; } }); }, this); }
javascript
function(classBindings) { var classNames = this.classNames; var elem, newClass, dasherizedClass; // Loop through all of the configured bindings. These will be either // property names ('isUrgent') or property paths relative to the view // ('content.isUrgent') forEach(classBindings, function(binding) { Ember.assert("classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. ['foo', ':bar']", binding.indexOf(' ') === -1); // Variable in which the old class value is saved. The observer function // closes over this variable, so it knows which string to remove when // the property changes. var oldClass; // Extract just the property name from bindings like 'foo:bar' var parsedPath = View._parsePropertyPath(binding); // Set up an observer on the context. If the property changes, toggle the // class name. var observer = function() { // Get the current value of the property newClass = this._classStringForProperty(binding); elem = this.$(); // If we had previously added a class to the element, remove it. if (oldClass) { elem.removeClass(oldClass); // Also remove from classNames so that if the view gets rerendered, // the class doesn't get added back to the DOM. classNames.removeObject(oldClass); } // If necessary, add a new class. Make sure we keep track of it so // it can be removed in the future. if (newClass) { elem.addClass(newClass); oldClass = newClass; } else { oldClass = null; } }; // Get the class name for the property at its current value dasherizedClass = this._classStringForProperty(binding); if (dasherizedClass) { // Ensure that it gets into the classNames array // so it is displayed when we render. addObject(classNames, dasherizedClass); // Save a reference to the class name so we can remove it // if the observer fires. Remember that this variable has // been closed over by the observer. oldClass = dasherizedClass; } this.registerObserver(this, parsedPath.path, observer); // Remove className so when the view is rerendered, // the className is added based on binding reevaluation this.one('willClearRender', function() { if (oldClass) { classNames.removeObject(oldClass); oldClass = null; } }); }, this); }
[ "function", "(", "classBindings", ")", "{", "var", "classNames", "=", "this", ".", "classNames", ";", "var", "elem", ",", "newClass", ",", "dasherizedClass", ";", "forEach", "(", "classBindings", ",", "function", "(", "binding", ")", "{", "Ember", ".", "assert", "(", "\"classNameBindings must not have spaces in them. Multiple class name bindings can be provided as elements of an array, e.g. ['foo', ':bar']\"", ",", "binding", ".", "indexOf", "(", "' '", ")", "===", "-", "1", ")", ";", "var", "oldClass", ";", "var", "parsedPath", "=", "View", ".", "_parsePropertyPath", "(", "binding", ")", ";", "var", "observer", "=", "function", "(", ")", "{", "newClass", "=", "this", ".", "_classStringForProperty", "(", "binding", ")", ";", "elem", "=", "this", ".", "$", "(", ")", ";", "if", "(", "oldClass", ")", "{", "elem", ".", "removeClass", "(", "oldClass", ")", ";", "classNames", ".", "removeObject", "(", "oldClass", ")", ";", "}", "if", "(", "newClass", ")", "{", "elem", ".", "addClass", "(", "newClass", ")", ";", "oldClass", "=", "newClass", ";", "}", "else", "{", "oldClass", "=", "null", ";", "}", "}", ";", "dasherizedClass", "=", "this", ".", "_classStringForProperty", "(", "binding", ")", ";", "if", "(", "dasherizedClass", ")", "{", "addObject", "(", "classNames", ",", "dasherizedClass", ")", ";", "oldClass", "=", "dasherizedClass", ";", "}", "this", ".", "registerObserver", "(", "this", ",", "parsedPath", ".", "path", ",", "observer", ")", ";", "this", ".", "one", "(", "'willClearRender'", ",", "function", "(", ")", "{", "if", "(", "oldClass", ")", "{", "classNames", ".", "removeObject", "(", "oldClass", ")", ";", "oldClass", "=", "null", ";", "}", "}", ")", ";", "}", ",", "this", ")", ";", "}" ]
Iterates over the view's `classNameBindings` array, inserts the value of the specified property into the `classNames` array, then creates an observer to update the view's element if the bound property ever changes in the future. @method _applyClassNameBindings @private
[ "Iterates", "over", "the", "view", "s", "classNameBindings", "array", "inserts", "the", "value", "of", "the", "specified", "property", "into", "the", "classNames", "array", "then", "creates", "an", "observer", "to", "update", "the", "view", "s", "element", "if", "the", "bound", "property", "ever", "changes", "in", "the", "future", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L42336-L42404
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
function(property) { var parsedPath = View._parsePropertyPath(property); var path = parsedPath.path; var val = get(this, path); if (val === undefined && isGlobalPath(path)) { val = get(Ember.lookup, path); } return View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName); }
javascript
function(property) { var parsedPath = View._parsePropertyPath(property); var path = parsedPath.path; var val = get(this, path); if (val === undefined && isGlobalPath(path)) { val = get(Ember.lookup, path); } return View._classStringForValue(path, val, parsedPath.className, parsedPath.falsyClassName); }
[ "function", "(", "property", ")", "{", "var", "parsedPath", "=", "View", ".", "_parsePropertyPath", "(", "property", ")", ";", "var", "path", "=", "parsedPath", ".", "path", ";", "var", "val", "=", "get", "(", "this", ",", "path", ")", ";", "if", "(", "val", "===", "undefined", "&&", "isGlobalPath", "(", "path", ")", ")", "{", "val", "=", "get", "(", "Ember", ".", "lookup", ",", "path", ")", ";", "}", "return", "View", ".", "_classStringForValue", "(", "path", ",", "val", ",", "parsedPath", ".", "className", ",", "parsedPath", ".", "falsyClassName", ")", ";", "}" ]
Given a property name, returns a dasherized version of that property name if the property evaluates to a non-falsy value. For example, if the view has property `isUrgent` that evaluates to true, passing `isUrgent` to this method will return `"is-urgent"`. @method _classStringForProperty @param property @private
[ "Given", "a", "property", "name", "returns", "a", "dasherized", "version", "of", "that", "property", "name", "if", "the", "property", "evaluates", "to", "a", "non", "-", "falsy", "value", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L42493-L42503
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
interiorNamespace
function interiorNamespace(element){ if ( element && element.namespaceURI === svgNamespace && !svgHTMLIntegrationPoints[element.tagName] ) { return svgNamespace; } else { return null; } }
javascript
function interiorNamespace(element){ if ( element && element.namespaceURI === svgNamespace && !svgHTMLIntegrationPoints[element.tagName] ) { return svgNamespace; } else { return null; } }
[ "function", "interiorNamespace", "(", "element", ")", "{", "if", "(", "element", "&&", "element", ".", "namespaceURI", "===", "svgNamespace", "&&", "!", "svgHTMLIntegrationPoints", "[", "element", ".", "tagName", "]", ")", "{", "return", "svgNamespace", ";", "}", "else", "{", "return", "null", ";", "}", "}" ]
This is not the namespace of the element, but of the elements inside that elements.
[ "This", "is", "not", "the", "namespace", "of", "the", "element", "but", "of", "the", "elements", "inside", "that", "elements", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L43484-L43494
train
appiphony/appiphony-lightning-js
public/lib/emberjs/ember.js
buildSafeDOM
function buildSafeDOM(html, contextualElement, dom) { var childNodes = buildIESafeDOM(html, contextualElement, dom); if (contextualElement.tagName === 'SELECT') { // Walk child nodes for (var i = 0; childNodes[i]; i++) { // Find and process the first option child node if (childNodes[i].tagName === 'OPTION') { if (detectAutoSelectedOption(childNodes[i].parentNode, childNodes[i], html)) { // If the first node is selected but does not have an attribute, // presume it is not really selected. childNodes[i].parentNode.selectedIndex = -1; } break; } } } return childNodes; }
javascript
function buildSafeDOM(html, contextualElement, dom) { var childNodes = buildIESafeDOM(html, contextualElement, dom); if (contextualElement.tagName === 'SELECT') { // Walk child nodes for (var i = 0; childNodes[i]; i++) { // Find and process the first option child node if (childNodes[i].tagName === 'OPTION') { if (detectAutoSelectedOption(childNodes[i].parentNode, childNodes[i], html)) { // If the first node is selected but does not have an attribute, // presume it is not really selected. childNodes[i].parentNode.selectedIndex = -1; } break; } } } return childNodes; }
[ "function", "buildSafeDOM", "(", "html", ",", "contextualElement", ",", "dom", ")", "{", "var", "childNodes", "=", "buildIESafeDOM", "(", "html", ",", "contextualElement", ",", "dom", ")", ";", "if", "(", "contextualElement", ".", "tagName", "===", "'SELECT'", ")", "{", "for", "(", "var", "i", "=", "0", ";", "childNodes", "[", "i", "]", ";", "i", "++", ")", "{", "if", "(", "childNodes", "[", "i", "]", ".", "tagName", "===", "'OPTION'", ")", "{", "if", "(", "detectAutoSelectedOption", "(", "childNodes", "[", "i", "]", ".", "parentNode", ",", "childNodes", "[", "i", "]", ",", "html", ")", ")", "{", "childNodes", "[", "i", "]", ".", "parentNode", ".", "selectedIndex", "=", "-", "1", ";", "}", "break", ";", "}", "}", "}", "return", "childNodes", ";", "}" ]
When parsing innerHTML, the browser may set up DOM with some things not desired. For example, with a select element context and option innerHTML the first option will be marked selected. This method cleans up some of that, resetting those values back to their defaults.
[ "When", "parsing", "innerHTML", "the", "browser", "may", "set", "up", "DOM", "with", "some", "things", "not", "desired", ".", "For", "example", "with", "a", "select", "element", "context", "and", "option", "innerHTML", "the", "first", "option", "will", "be", "marked", "selected", ".", "This", "method", "cleans", "up", "some", "of", "that", "resetting", "those", "values", "back", "to", "their", "defaults", "." ]
704953fdc60b62d3073fc5cace716a201d38b36c
https://github.com/appiphony/appiphony-lightning-js/blob/704953fdc60b62d3073fc5cace716a201d38b36c/public/lib/emberjs/ember.js#L43949-L43968
train
yahoo/kobold
lib/cli.js
filterArguments
function filterArguments(args, params, inject) { var newArgs = ['node', '_mocha'].concat(inject || []), param, i, len, type; for (i = 2, len = args.length; i < len; i++) { if ((i < args.length - 1) && (args[i].length > 2) && (args[i].substr(0, 2) === '--')) { // Get parameter without '--' param = args[i].substr(2); // Is parameter used? if (params.hasOwnProperty(param)) { // Remember what the type was type = typeof params[param]; // Overwrite value with next value in arguments if (type === 'boolean') { params[param] = true; } else { params[param] = args[i + 1]; i++; // Convert back to boolean if needed if (type === 'number') { params[param] = parseFloat(params[param]); } } } else { newArgs.push(args[i]); } } else { newArgs.push(args[i]); } } // Set test-path with last argument if none given if (!params['test-path']) { params['test-path'] = args.pop(); } newArgs.push(path.join(__dirname, '..', 'resource', 'run.js')); return newArgs; }
javascript
function filterArguments(args, params, inject) { var newArgs = ['node', '_mocha'].concat(inject || []), param, i, len, type; for (i = 2, len = args.length; i < len; i++) { if ((i < args.length - 1) && (args[i].length > 2) && (args[i].substr(0, 2) === '--')) { // Get parameter without '--' param = args[i].substr(2); // Is parameter used? if (params.hasOwnProperty(param)) { // Remember what the type was type = typeof params[param]; // Overwrite value with next value in arguments if (type === 'boolean') { params[param] = true; } else { params[param] = args[i + 1]; i++; // Convert back to boolean if needed if (type === 'number') { params[param] = parseFloat(params[param]); } } } else { newArgs.push(args[i]); } } else { newArgs.push(args[i]); } } // Set test-path with last argument if none given if (!params['test-path']) { params['test-path'] = args.pop(); } newArgs.push(path.join(__dirname, '..', 'resource', 'run.js')); return newArgs; }
[ "function", "filterArguments", "(", "args", ",", "params", ",", "inject", ")", "{", "var", "newArgs", "=", "[", "'node'", ",", "'_mocha'", "]", ".", "concat", "(", "inject", "||", "[", "]", ")", ",", "param", ",", "i", ",", "len", ",", "type", ";", "for", "(", "i", "=", "2", ",", "len", "=", "args", ".", "length", ";", "i", "<", "len", ";", "i", "++", ")", "{", "if", "(", "(", "i", "<", "args", ".", "length", "-", "1", ")", "&&", "(", "args", "[", "i", "]", ".", "length", ">", "2", ")", "&&", "(", "args", "[", "i", "]", ".", "substr", "(", "0", ",", "2", ")", "===", "'--'", ")", ")", "{", "param", "=", "args", "[", "i", "]", ".", "substr", "(", "2", ")", ";", "if", "(", "params", ".", "hasOwnProperty", "(", "param", ")", ")", "{", "type", "=", "typeof", "params", "[", "param", "]", ";", "if", "(", "type", "===", "'boolean'", ")", "{", "params", "[", "param", "]", "=", "true", ";", "}", "else", "{", "params", "[", "param", "]", "=", "args", "[", "i", "+", "1", "]", ";", "i", "++", ";", "if", "(", "type", "===", "'number'", ")", "{", "params", "[", "param", "]", "=", "parseFloat", "(", "params", "[", "param", "]", ")", ";", "}", "}", "}", "else", "{", "newArgs", ".", "push", "(", "args", "[", "i", "]", ")", ";", "}", "}", "else", "{", "newArgs", ".", "push", "(", "args", "[", "i", "]", ")", ";", "}", "}", "if", "(", "!", "params", "[", "'test-path'", "]", ")", "{", "params", "[", "'test-path'", "]", "=", "args", ".", "pop", "(", ")", ";", "}", "newArgs", ".", "push", "(", "path", ".", "join", "(", "__dirname", ",", "'..'", ",", "'resource'", ",", "'run.js'", ")", ")", ";", "return", "newArgs", ";", "}" ]
Filters arguments given and sets them to parameters @method filterArguments @param {string[]} args @param {object} params @param {string[]} [inject] @return {string[]} @private
[ "Filters", "arguments", "given", "and", "sets", "them", "to", "parameters" ]
c43adea98046a7cc4101a27f0448675b2f589601
https://github.com/yahoo/kobold/blob/c43adea98046a7cc4101a27f0448675b2f589601/lib/cli.js#L14-L63
train
yahoo/kobold
lib/cli.js
prepareEnvironment
function prepareEnvironment (argv) { var params, args; // Define default values params = { 'approved-folder': 'approved', 'build-folder': 'build', 'highlight-folder': 'highlight', 'config-folder': 'config', 'fail-orphans': false, 'fail-additions': false, 'test-path': null, 'config': null }; // Filter arguments args = filterArguments(argv, params, [ '--slow', '5000', '--no-timeouts' ]); if (!fs.existsSync(params['test-path'])) { throw new Error('Cannot find path to ' + params['test-path']); } else { params['test-path'] = path.resolve(params['test-path']); } // Load global config if (typeof params['config'] === 'string') { params['config'] = require(path.resolve(params['config'])); } else { params['config'] = params['config'] || {}; } // Set global variable for test-runner global.koboldOptions = { "verbose": false, "failForOrphans": params['fail-orphans'], "failOnAdditions": params['fail-additions'], "build": params['build'], "comparison": params['config'], "storage": { "type": 'File', "options": { "path": params['test-path'], "approvedFolderName": params['approved-folder'], "buildFolderName": params['build-folder'], "highlightFolderName": params['highlight-folder'], "configFolderName": params['config-folder'] } } }; return args; }
javascript
function prepareEnvironment (argv) { var params, args; // Define default values params = { 'approved-folder': 'approved', 'build-folder': 'build', 'highlight-folder': 'highlight', 'config-folder': 'config', 'fail-orphans': false, 'fail-additions': false, 'test-path': null, 'config': null }; // Filter arguments args = filterArguments(argv, params, [ '--slow', '5000', '--no-timeouts' ]); if (!fs.existsSync(params['test-path'])) { throw new Error('Cannot find path to ' + params['test-path']); } else { params['test-path'] = path.resolve(params['test-path']); } // Load global config if (typeof params['config'] === 'string') { params['config'] = require(path.resolve(params['config'])); } else { params['config'] = params['config'] || {}; } // Set global variable for test-runner global.koboldOptions = { "verbose": false, "failForOrphans": params['fail-orphans'], "failOnAdditions": params['fail-additions'], "build": params['build'], "comparison": params['config'], "storage": { "type": 'File', "options": { "path": params['test-path'], "approvedFolderName": params['approved-folder'], "buildFolderName": params['build-folder'], "highlightFolderName": params['highlight-folder'], "configFolderName": params['config-folder'] } } }; return args; }
[ "function", "prepareEnvironment", "(", "argv", ")", "{", "var", "params", ",", "args", ";", "params", "=", "{", "'approved-folder'", ":", "'approved'", ",", "'build-folder'", ":", "'build'", ",", "'highlight-folder'", ":", "'highlight'", ",", "'config-folder'", ":", "'config'", ",", "'fail-orphans'", ":", "false", ",", "'fail-additions'", ":", "false", ",", "'test-path'", ":", "null", ",", "'config'", ":", "null", "}", ";", "args", "=", "filterArguments", "(", "argv", ",", "params", ",", "[", "'--slow'", ",", "'5000'", ",", "'--no-timeouts'", "]", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "params", "[", "'test-path'", "]", ")", ")", "{", "throw", "new", "Error", "(", "'Cannot find path to '", "+", "params", "[", "'test-path'", "]", ")", ";", "}", "else", "{", "params", "[", "'test-path'", "]", "=", "path", ".", "resolve", "(", "params", "[", "'test-path'", "]", ")", ";", "}", "if", "(", "typeof", "params", "[", "'config'", "]", "===", "'string'", ")", "{", "params", "[", "'config'", "]", "=", "require", "(", "path", ".", "resolve", "(", "params", "[", "'config'", "]", ")", ")", ";", "}", "else", "{", "params", "[", "'config'", "]", "=", "params", "[", "'config'", "]", "||", "{", "}", ";", "}", "global", ".", "koboldOptions", "=", "{", "\"verbose\"", ":", "false", ",", "\"failForOrphans\"", ":", "params", "[", "'fail-orphans'", "]", ",", "\"failOnAdditions\"", ":", "params", "[", "'fail-additions'", "]", ",", "\"build\"", ":", "params", "[", "'build'", "]", ",", "\"comparison\"", ":", "params", "[", "'config'", "]", ",", "\"storage\"", ":", "{", "\"type\"", ":", "'File'", ",", "\"options\"", ":", "{", "\"path\"", ":", "params", "[", "'test-path'", "]", ",", "\"approvedFolderName\"", ":", "params", "[", "'approved-folder'", "]", ",", "\"buildFolderName\"", ":", "params", "[", "'build-folder'", "]", ",", "\"highlightFolderName\"", ":", "params", "[", "'highlight-folder'", "]", ",", "\"configFolderName\"", ":", "params", "[", "'config-folder'", "]", "}", "}", "}", ";", "return", "args", ";", "}" ]
Prepares the environment for kobold @method prepareEnvironment @param {string[]} argv @return {string[]} @private
[ "Prepares", "the", "environment", "for", "kobold" ]
c43adea98046a7cc4101a27f0448675b2f589601
https://github.com/yahoo/kobold/blob/c43adea98046a7cc4101a27f0448675b2f589601/lib/cli.js#L73-L133
train
redpandatronicsuk/arty-charty
arty-charty/util.js
makeBarsChartPath
function makeBarsChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, paddingLeft, isRange) { let heightScaler = (chartHeight-markerRadius)/maxValue; let xSpacing = width / pointsOnScreen; let barWidth = xSpacing - paddingLeft; let fullWidth = paddingLeft/2 + (paddingLeft+barWidth) * (chart.data.length-1) + barWidth; let pathStr = [] let barCords = []; let x1, y1, y2; chart.data.some((d, idx) => { x1 = paddingLeft/2 + (paddingLeft+barWidth) * idx; if (x1 > fullWidth * t && chart.drawChart) { return true; } if (chart.stretchChart) { x1 = x1 * t; } y1 = (chartHeight+chartHeightOffset) - d.value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1); y2 = isRange ? (chartHeight+chartHeightOffset) - d.valueLow * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1) : (chartHeight+chartHeightOffset); pathStr.push('M'); pathStr.push(x1); pathStr.push(y2); pathStr.push('H'); pathStr.push(x1 + barWidth); pathStr.push('V'); pathStr.push(y1); pathStr.push('H'); pathStr.push(x1); pathStr.push('V'); pathStr.push(y2); barCords.push({x1: x1, x2: x1+barWidth, y1: y1, y2: y2}); }); return { path: pathStr.join(' '), width: fullWidth, maxScroll: fullWidth - width, barCords: barCords }; }
javascript
function makeBarsChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, paddingLeft, isRange) { let heightScaler = (chartHeight-markerRadius)/maxValue; let xSpacing = width / pointsOnScreen; let barWidth = xSpacing - paddingLeft; let fullWidth = paddingLeft/2 + (paddingLeft+barWidth) * (chart.data.length-1) + barWidth; let pathStr = [] let barCords = []; let x1, y1, y2; chart.data.some((d, idx) => { x1 = paddingLeft/2 + (paddingLeft+barWidth) * idx; if (x1 > fullWidth * t && chart.drawChart) { return true; } if (chart.stretchChart) { x1 = x1 * t; } y1 = (chartHeight+chartHeightOffset) - d.value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1); y2 = isRange ? (chartHeight+chartHeightOffset) - d.valueLow * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1) : (chartHeight+chartHeightOffset); pathStr.push('M'); pathStr.push(x1); pathStr.push(y2); pathStr.push('H'); pathStr.push(x1 + barWidth); pathStr.push('V'); pathStr.push(y1); pathStr.push('H'); pathStr.push(x1); pathStr.push('V'); pathStr.push(y2); barCords.push({x1: x1, x2: x1+barWidth, y1: y1, y2: y2}); }); return { path: pathStr.join(' '), width: fullWidth, maxScroll: fullWidth - width, barCords: barCords }; }
[ "function", "makeBarsChartPath", "(", "chart", ",", "width", ",", "t", ",", "maxValue", ",", "chartHeight", ",", "chartHeightOffset", ",", "markerRadius", ",", "pointsOnScreen", ",", "paddingLeft", ",", "isRange", ")", "{", "let", "heightScaler", "=", "(", "chartHeight", "-", "markerRadius", ")", "/", "maxValue", ";", "let", "xSpacing", "=", "width", "/", "pointsOnScreen", ";", "let", "barWidth", "=", "xSpacing", "-", "paddingLeft", ";", "let", "fullWidth", "=", "paddingLeft", "/", "2", "+", "(", "paddingLeft", "+", "barWidth", ")", "*", "(", "chart", ".", "data", ".", "length", "-", "1", ")", "+", "barWidth", ";", "let", "pathStr", "=", "[", "]", "let", "barCords", "=", "[", "]", ";", "let", "x1", ",", "y1", ",", "y2", ";", "chart", ".", "data", ".", "some", "(", "(", "d", ",", "idx", ")", "=>", "{", "x1", "=", "paddingLeft", "/", "2", "+", "(", "paddingLeft", "+", "barWidth", ")", "*", "idx", ";", "if", "(", "x1", ">", "fullWidth", "*", "t", "&&", "chart", ".", "drawChart", ")", "{", "return", "true", ";", "}", "if", "(", "chart", ".", "stretchChart", ")", "{", "x1", "=", "x1", "*", "t", ";", "}", "y1", "=", "(", "chartHeight", "+", "chartHeightOffset", ")", "-", "d", ".", "value", "*", "heightScaler", "*", "(", "chart", ".", "timingFunctions", "?", "chart", ".", "timingFunctions", "[", "idx", "%", "chart", ".", "timingFunctions", ".", "length", "]", "(", "t", ")", ":", "1", ")", ";", "y2", "=", "isRange", "?", "(", "chartHeight", "+", "chartHeightOffset", ")", "-", "d", ".", "valueLow", "*", "heightScaler", "*", "(", "chart", ".", "timingFunctions", "?", "chart", ".", "timingFunctions", "[", "idx", "%", "chart", ".", "timingFunctions", ".", "length", "]", "(", "t", ")", ":", "1", ")", ":", "(", "chartHeight", "+", "chartHeightOffset", ")", ";", "pathStr", ".", "push", "(", "'M'", ")", ";", "pathStr", ".", "push", "(", "x1", ")", ";", "pathStr", ".", "push", "(", "y2", ")", ";", "pathStr", ".", "push", "(", "'H'", ")", ";", "pathStr", ".", "push", "(", "x1", "+", "barWidth", ")", ";", "pathStr", ".", "push", "(", "'V'", ")", ";", "pathStr", ".", "push", "(", "y1", ")", ";", "pathStr", ".", "push", "(", "'H'", ")", ";", "pathStr", ".", "push", "(", "x1", ")", ";", "pathStr", ".", "push", "(", "'V'", ")", ";", "pathStr", ".", "push", "(", "y2", ")", ";", "barCords", ".", "push", "(", "{", "x1", ":", "x1", ",", "x2", ":", "x1", "+", "barWidth", ",", "y1", ":", "y1", ",", "y2", ":", "y2", "}", ")", ";", "}", ")", ";", "return", "{", "path", ":", "pathStr", ".", "join", "(", "' '", ")", ",", "width", ":", "fullWidth", ",", "maxScroll", ":", "fullWidth", "-", "width", ",", "barCords", ":", "barCords", "}", ";", "}" ]
Generate the SVG path for a bar chart. @param {object} chart The chart object @param {number} width Width of the chart in pixels @param {number} t Scale parameter (range: 0-1), used for animating the graph @param {number} maxValue The maximum value of chart data @param {number} chartHeight Height of the chart in pixels @param {number} chartHeightOffset By how much to offset the chart height. Note: The negation of this number is as the marginTop for the component. This is done so when the graph is animated, overflow is not cut off. @param {number} markerRadius Radius of the markers on the line (only needed to calcualte the height scaler and keep it consistent with the line/area chart, refactor for better name!!!) @param {number} pointsOnScreen The number of points to show on the screen without having to scroll. Used to calculate the horizontal spacing between points. (maybe find better name????)
[ "Generate", "the", "SVG", "path", "for", "a", "bar", "chart", "." ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L276-L313
train
redpandatronicsuk/arty-charty
arty-charty/util.js
makeStackedBarsChartPath
function makeStackedBarsChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, paddingLeft, yAxisWidth, isRange) { let heightScaler = (chartHeight-markerRadius)/maxValue; width = width - yAxisWidth; let xSpacing = width / pointsOnScreen; let barWidth = xSpacing - paddingLeft; let fullWidth = paddingLeft/2 + (paddingLeft+barWidth) * (chart.data.length-1) + barWidth; let paths = [] let barCords = []; let x1, y1, y2; chart.data.some((d, idx) => { x1 = paddingLeft/2 + (paddingLeft+barWidth) * idx + yAxisWidth; if (x1 > fullWidth * t && chart.drawChart) { return true; } if (chart.stretchChart) { x1 = x1 * t; } let prevY = 0; d.forEach((stack) => { y1 = (chartHeight+chartHeightOffset) - (stack.value+prevY) * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1); //y2 = isRange ? (chartHeight+chartHeightOffset) - prevY * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1) : (chartHeight+chartHeightOffset); y2 = isRange ? (chartHeight+chartHeightOffset) - prevY * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1) : (chartHeight+chartHeightOffset); prevY += stack.value; paths.push({path: makeBarPath(x1, y1, y2, barWidth), color: stack.color}); barCords.push({x1: x1, x2: x1+barWidth, y1: y1, y2: y2}); }); }); return { //path: pathStr.join(' '), path: paths, width: fullWidth, maxScroll: fullWidth - width, barCords: barCords }; }
javascript
function makeStackedBarsChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, paddingLeft, yAxisWidth, isRange) { let heightScaler = (chartHeight-markerRadius)/maxValue; width = width - yAxisWidth; let xSpacing = width / pointsOnScreen; let barWidth = xSpacing - paddingLeft; let fullWidth = paddingLeft/2 + (paddingLeft+barWidth) * (chart.data.length-1) + barWidth; let paths = [] let barCords = []; let x1, y1, y2; chart.data.some((d, idx) => { x1 = paddingLeft/2 + (paddingLeft+barWidth) * idx + yAxisWidth; if (x1 > fullWidth * t && chart.drawChart) { return true; } if (chart.stretchChart) { x1 = x1 * t; } let prevY = 0; d.forEach((stack) => { y1 = (chartHeight+chartHeightOffset) - (stack.value+prevY) * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1); //y2 = isRange ? (chartHeight+chartHeightOffset) - prevY * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1) : (chartHeight+chartHeightOffset); y2 = isRange ? (chartHeight+chartHeightOffset) - prevY * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1) : (chartHeight+chartHeightOffset); prevY += stack.value; paths.push({path: makeBarPath(x1, y1, y2, barWidth), color: stack.color}); barCords.push({x1: x1, x2: x1+barWidth, y1: y1, y2: y2}); }); }); return { //path: pathStr.join(' '), path: paths, width: fullWidth, maxScroll: fullWidth - width, barCords: barCords }; }
[ "function", "makeStackedBarsChartPath", "(", "chart", ",", "width", ",", "t", ",", "maxValue", ",", "chartHeight", ",", "chartHeightOffset", ",", "markerRadius", ",", "pointsOnScreen", ",", "paddingLeft", ",", "yAxisWidth", ",", "isRange", ")", "{", "let", "heightScaler", "=", "(", "chartHeight", "-", "markerRadius", ")", "/", "maxValue", ";", "width", "=", "width", "-", "yAxisWidth", ";", "let", "xSpacing", "=", "width", "/", "pointsOnScreen", ";", "let", "barWidth", "=", "xSpacing", "-", "paddingLeft", ";", "let", "fullWidth", "=", "paddingLeft", "/", "2", "+", "(", "paddingLeft", "+", "barWidth", ")", "*", "(", "chart", ".", "data", ".", "length", "-", "1", ")", "+", "barWidth", ";", "let", "paths", "=", "[", "]", "let", "barCords", "=", "[", "]", ";", "let", "x1", ",", "y1", ",", "y2", ";", "chart", ".", "data", ".", "some", "(", "(", "d", ",", "idx", ")", "=>", "{", "x1", "=", "paddingLeft", "/", "2", "+", "(", "paddingLeft", "+", "barWidth", ")", "*", "idx", "+", "yAxisWidth", ";", "if", "(", "x1", ">", "fullWidth", "*", "t", "&&", "chart", ".", "drawChart", ")", "{", "return", "true", ";", "}", "if", "(", "chart", ".", "stretchChart", ")", "{", "x1", "=", "x1", "*", "t", ";", "}", "let", "prevY", "=", "0", ";", "d", ".", "forEach", "(", "(", "stack", ")", "=>", "{", "y1", "=", "(", "chartHeight", "+", "chartHeightOffset", ")", "-", "(", "stack", ".", "value", "+", "prevY", ")", "*", "heightScaler", "*", "(", "chart", ".", "timingFunctions", "?", "chart", ".", "timingFunctions", "[", "idx", "%", "chart", ".", "timingFunctions", ".", "length", "]", "(", "t", ")", ":", "1", ")", ";", "y2", "=", "isRange", "?", "(", "chartHeight", "+", "chartHeightOffset", ")", "-", "prevY", "*", "heightScaler", "*", "(", "chart", ".", "timingFunctions", "?", "chart", ".", "timingFunctions", "[", "idx", "%", "chart", ".", "timingFunctions", ".", "length", "]", "(", "t", ")", ":", "1", ")", ":", "(", "chartHeight", "+", "chartHeightOffset", ")", ";", "prevY", "+=", "stack", ".", "value", ";", "paths", ".", "push", "(", "{", "path", ":", "makeBarPath", "(", "x1", ",", "y1", ",", "y2", ",", "barWidth", ")", ",", "color", ":", "stack", ".", "color", "}", ")", ";", "barCords", ".", "push", "(", "{", "x1", ":", "x1", ",", "x2", ":", "x1", "+", "barWidth", ",", "y1", ":", "y1", ",", "y2", ":", "y2", "}", ")", ";", "}", ")", ";", "}", ")", ";", "return", "{", "path", ":", "paths", ",", "width", ":", "fullWidth", ",", "maxScroll", ":", "fullWidth", "-", "width", ",", "barCords", ":", "barCords", "}", ";", "}" ]
Make like candle-stick, where each stck is its own Shape
[ "Make", "like", "candle", "-", "stick", "where", "each", "stck", "is", "its", "own", "Shape" ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L316-L350
train
redpandatronicsuk/arty-charty
arty-charty/util.js
makeAreaChartPath
function makeAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen) { return makeLineOrAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, true, false); }
javascript
function makeAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen) { return makeLineOrAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, true, false); }
[ "function", "makeAreaChartPath", "(", "chart", ",", "width", ",", "t", ",", "maxValue", ",", "chartHeight", ",", "chartHeightOffset", ",", "markerRadius", ",", "pointsOnScreen", ")", "{", "return", "makeLineOrAreaChartPath", "(", "chart", ",", "width", ",", "t", ",", "maxValue", ",", "chartHeight", ",", "chartHeightOffset", ",", "markerRadius", ",", "pointsOnScreen", ",", "true", ",", "false", ")", ";", "}" ]
Wrapper function for makeLineOrAreaChartPath to make a line chart.
[ "Wrapper", "function", "for", "makeLineOrAreaChartPath", "to", "make", "a", "line", "chart", "." ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L479-L481
train
redpandatronicsuk/arty-charty
arty-charty/util.js
makeLineChartPath
function makeLineChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen) { return makeLineOrAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, false, false); }
javascript
function makeLineChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen) { return makeLineOrAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, false, false); }
[ "function", "makeLineChartPath", "(", "chart", ",", "width", ",", "t", ",", "maxValue", ",", "chartHeight", ",", "chartHeightOffset", ",", "markerRadius", ",", "pointsOnScreen", ")", "{", "return", "makeLineOrAreaChartPath", "(", "chart", ",", "width", ",", "t", ",", "maxValue", ",", "chartHeight", ",", "chartHeightOffset", ",", "markerRadius", ",", "pointsOnScreen", ",", "false", ",", "false", ")", ";", "}" ]
Wrapper function for makeLineOrAreaChartPath to make an area chart.
[ "Wrapper", "function", "for", "makeLineOrAreaChartPath", "to", "make", "an", "area", "chart", "." ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L490-L492
train
redpandatronicsuk/arty-charty
arty-charty/util.js
makeLineOrAreaChartPath
function makeLineOrAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, makeArea, isRange) { let heightScaler = (chartHeight-markerRadius)/maxValue; let xSpacing = width / pointsOnScreen; let centeriser = xSpacing / 2 - markerRadius; let fullWidth = xSpacing*(chart.data.length-1) + markerRadius + centeriser; let lineStrArray = makeArea && !isRange ? ['M' + markerRadius, chartHeight+chartHeightOffset] : []; if (isRange) { lineStrArray.push('M'); lineStrArray.push(makeXcord(chart, fullWidth, t, centeriser, markerRadius)); lineStrArray.push((chartHeight+chartHeightOffset) - chart.data[0].value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[0 % chart.timingFunctions.length](t) : 1)); } let xCord; let lowCords = []; chart.data.some((d, idx) => { let spacing = idx*xSpacing + centeriser; if (spacing > fullWidth * t && chart.drawChart) { return true; } xCord = makeXcord(chart, fullWidth, t, spacing, markerRadius); // Move line to to next x-coordinate: lineStrArray.push((idx > 0 || makeArea ? 'L' : 'M') + xCord); // And y-cordinate: let yCord = (chartHeight+chartHeightOffset) - d.value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1); lineStrArray.push(yCord); if (isRange) { let yCordLow = (chartHeight+chartHeightOffset) - d.valueLow * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1); lowCords.unshift({xCord, yCordLow}); } }); if (makeArea) { if (isRange) { lowCords.forEach((d) => { lineStrArray.push('L' + d.xCord); lineStrArray.push(d.yCordLow); }); // lineStrArray.push('L' + makeXcord(chart, fullWidth, t, xSpacing + centeriser, markerRadius)); // lineStrArray.push(d.yCordLow); } else { lineStrArray.push('L' + xCord); lineStrArray.push(chartHeight + chartHeightOffset); } lineStrArray.push('Z'); } return { path: lineStrArray.join(' '), width: xCord + markerRadius, maxScroll: fullWidth - xSpacing + markerRadius }; }
javascript
function makeLineOrAreaChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, makeArea, isRange) { let heightScaler = (chartHeight-markerRadius)/maxValue; let xSpacing = width / pointsOnScreen; let centeriser = xSpacing / 2 - markerRadius; let fullWidth = xSpacing*(chart.data.length-1) + markerRadius + centeriser; let lineStrArray = makeArea && !isRange ? ['M' + markerRadius, chartHeight+chartHeightOffset] : []; if (isRange) { lineStrArray.push('M'); lineStrArray.push(makeXcord(chart, fullWidth, t, centeriser, markerRadius)); lineStrArray.push((chartHeight+chartHeightOffset) - chart.data[0].value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[0 % chart.timingFunctions.length](t) : 1)); } let xCord; let lowCords = []; chart.data.some((d, idx) => { let spacing = idx*xSpacing + centeriser; if (spacing > fullWidth * t && chart.drawChart) { return true; } xCord = makeXcord(chart, fullWidth, t, spacing, markerRadius); // Move line to to next x-coordinate: lineStrArray.push((idx > 0 || makeArea ? 'L' : 'M') + xCord); // And y-cordinate: let yCord = (chartHeight+chartHeightOffset) - d.value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1); lineStrArray.push(yCord); if (isRange) { let yCordLow = (chartHeight+chartHeightOffset) - d.valueLow * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1); lowCords.unshift({xCord, yCordLow}); } }); if (makeArea) { if (isRange) { lowCords.forEach((d) => { lineStrArray.push('L' + d.xCord); lineStrArray.push(d.yCordLow); }); // lineStrArray.push('L' + makeXcord(chart, fullWidth, t, xSpacing + centeriser, markerRadius)); // lineStrArray.push(d.yCordLow); } else { lineStrArray.push('L' + xCord); lineStrArray.push(chartHeight + chartHeightOffset); } lineStrArray.push('Z'); } return { path: lineStrArray.join(' '), width: xCord + markerRadius, maxScroll: fullWidth - xSpacing + markerRadius }; }
[ "function", "makeLineOrAreaChartPath", "(", "chart", ",", "width", ",", "t", ",", "maxValue", ",", "chartHeight", ",", "chartHeightOffset", ",", "markerRadius", ",", "pointsOnScreen", ",", "makeArea", ",", "isRange", ")", "{", "let", "heightScaler", "=", "(", "chartHeight", "-", "markerRadius", ")", "/", "maxValue", ";", "let", "xSpacing", "=", "width", "/", "pointsOnScreen", ";", "let", "centeriser", "=", "xSpacing", "/", "2", "-", "markerRadius", ";", "let", "fullWidth", "=", "xSpacing", "*", "(", "chart", ".", "data", ".", "length", "-", "1", ")", "+", "markerRadius", "+", "centeriser", ";", "let", "lineStrArray", "=", "makeArea", "&&", "!", "isRange", "?", "[", "'M'", "+", "markerRadius", ",", "chartHeight", "+", "chartHeightOffset", "]", ":", "[", "]", ";", "if", "(", "isRange", ")", "{", "lineStrArray", ".", "push", "(", "'M'", ")", ";", "lineStrArray", ".", "push", "(", "makeXcord", "(", "chart", ",", "fullWidth", ",", "t", ",", "centeriser", ",", "markerRadius", ")", ")", ";", "lineStrArray", ".", "push", "(", "(", "chartHeight", "+", "chartHeightOffset", ")", "-", "chart", ".", "data", "[", "0", "]", ".", "value", "*", "heightScaler", "*", "(", "chart", ".", "timingFunctions", "?", "chart", ".", "timingFunctions", "[", "0", "%", "chart", ".", "timingFunctions", ".", "length", "]", "(", "t", ")", ":", "1", ")", ")", ";", "}", "let", "xCord", ";", "let", "lowCords", "=", "[", "]", ";", "chart", ".", "data", ".", "some", "(", "(", "d", ",", "idx", ")", "=>", "{", "let", "spacing", "=", "idx", "*", "xSpacing", "+", "centeriser", ";", "if", "(", "spacing", ">", "fullWidth", "*", "t", "&&", "chart", ".", "drawChart", ")", "{", "return", "true", ";", "}", "xCord", "=", "makeXcord", "(", "chart", ",", "fullWidth", ",", "t", ",", "spacing", ",", "markerRadius", ")", ";", "lineStrArray", ".", "push", "(", "(", "idx", ">", "0", "||", "makeArea", "?", "'L'", ":", "'M'", ")", "+", "xCord", ")", ";", "let", "yCord", "=", "(", "chartHeight", "+", "chartHeightOffset", ")", "-", "d", ".", "value", "*", "heightScaler", "*", "(", "chart", ".", "timingFunctions", "?", "chart", ".", "timingFunctions", "[", "idx", "%", "chart", ".", "timingFunctions", ".", "length", "]", "(", "t", ")", ":", "1", ")", ";", "lineStrArray", ".", "push", "(", "yCord", ")", ";", "if", "(", "isRange", ")", "{", "let", "yCordLow", "=", "(", "chartHeight", "+", "chartHeightOffset", ")", "-", "d", ".", "valueLow", "*", "heightScaler", "*", "(", "chart", ".", "timingFunctions", "?", "chart", ".", "timingFunctions", "[", "idx", "%", "chart", ".", "timingFunctions", ".", "length", "]", "(", "t", ")", ":", "1", ")", ";", "lowCords", ".", "unshift", "(", "{", "xCord", ",", "yCordLow", "}", ")", ";", "}", "}", ")", ";", "if", "(", "makeArea", ")", "{", "if", "(", "isRange", ")", "{", "lowCords", ".", "forEach", "(", "(", "d", ")", "=>", "{", "lineStrArray", ".", "push", "(", "'L'", "+", "d", ".", "xCord", ")", ";", "lineStrArray", ".", "push", "(", "d", ".", "yCordLow", ")", ";", "}", ")", ";", "}", "else", "{", "lineStrArray", ".", "push", "(", "'L'", "+", "xCord", ")", ";", "lineStrArray", ".", "push", "(", "chartHeight", "+", "chartHeightOffset", ")", ";", "}", "lineStrArray", ".", "push", "(", "'Z'", ")", ";", "}", "return", "{", "path", ":", "lineStrArray", ".", "join", "(", "' '", ")", ",", "width", ":", "xCord", "+", "markerRadius", ",", "maxScroll", ":", "fullWidth", "-", "xSpacing", "+", "markerRadius", "}", ";", "}" ]
Generate the SVG path for a line or area chart. @param {object} chart The chart object @param {number} width Width of the chart in pixels @param {number} t Scale parameter (range: 0-1), used for animating the graph @param {number} maxValue The maximum value of chart data @param {number} chartHeight Height of the chart in pixels @param {number} chartHeightOffset By how much to offset the chart height. Note: The negation of this number is as the marginTop for the component. This is done so when the graph is animated, overflow is not cut off. @param {number} markerRadius Radius of the markers on the line (needed here so we can add it to the width of the chart element, maybe change name to something better such as padding!!!!) @param {number} pointsOnScreen The number of points to show on the screen without having to scroll. Used to calculate the horizontal spacing between points. (maybe find better name????) @param {boolean} makeArea Wether to close the line (make it an area chart) or not.
[ "Generate", "the", "SVG", "path", "for", "a", "line", "or", "area", "chart", "." ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L515-L564
train
redpandatronicsuk/arty-charty
arty-charty/util.js
makeSplineChartPath
function makeSplineChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, closePath) { let heightScaler = (chartHeight-markerRadius)/maxValue; let xSpacing = width / pointsOnScreen; let centeriser = xSpacing / 2 - markerRadius; let fullWidth = xSpacing*(chart.data.length-1) + markerRadius + centeriser; let xCord; let xCords = []; let yCords = []; chart.data.forEach((d, idx) => { let spacing = idx*xSpacing + centeriser; if (spacing > fullWidth * t && chart.drawChart) { return true; } xCord = makeXcord(chart, fullWidth, t, spacing, markerRadius); xCords.push(xCord); yCords.push((chartHeight+chartHeightOffset) - d.value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1)); }); let px = computeSplineControlPoints(xCords); let py = computeSplineControlPoints(yCords); let splines = [`M ${xCords[0]} ${yCords[0]}`]; for (i=0;i<xCords.length-1;i++) { splines.push(makeSpline(xCords[i],yCords[i],px.p1[i],py.p1[i],px.p2[i],py.p2[i],xCords[i+1],yCords[i+1])); } if (closePath) { // close for area spline graph splines.push(`V ${chartHeight+chartHeightOffset} H ${xCords[0]} Z`); } return { path: splines.join(','), width: xCords.slice(-1) + markerRadius, maxScroll: fullWidth - xSpacing + markerRadius }; }
javascript
function makeSplineChartPath(chart, width, t, maxValue, chartHeight, chartHeightOffset, markerRadius, pointsOnScreen, closePath) { let heightScaler = (chartHeight-markerRadius)/maxValue; let xSpacing = width / pointsOnScreen; let centeriser = xSpacing / 2 - markerRadius; let fullWidth = xSpacing*(chart.data.length-1) + markerRadius + centeriser; let xCord; let xCords = []; let yCords = []; chart.data.forEach((d, idx) => { let spacing = idx*xSpacing + centeriser; if (spacing > fullWidth * t && chart.drawChart) { return true; } xCord = makeXcord(chart, fullWidth, t, spacing, markerRadius); xCords.push(xCord); yCords.push((chartHeight+chartHeightOffset) - d.value * heightScaler * (chart.timingFunctions ? chart.timingFunctions[idx % chart.timingFunctions.length](t) : 1)); }); let px = computeSplineControlPoints(xCords); let py = computeSplineControlPoints(yCords); let splines = [`M ${xCords[0]} ${yCords[0]}`]; for (i=0;i<xCords.length-1;i++) { splines.push(makeSpline(xCords[i],yCords[i],px.p1[i],py.p1[i],px.p2[i],py.p2[i],xCords[i+1],yCords[i+1])); } if (closePath) { // close for area spline graph splines.push(`V ${chartHeight+chartHeightOffset} H ${xCords[0]} Z`); } return { path: splines.join(','), width: xCords.slice(-1) + markerRadius, maxScroll: fullWidth - xSpacing + markerRadius }; }
[ "function", "makeSplineChartPath", "(", "chart", ",", "width", ",", "t", ",", "maxValue", ",", "chartHeight", ",", "chartHeightOffset", ",", "markerRadius", ",", "pointsOnScreen", ",", "closePath", ")", "{", "let", "heightScaler", "=", "(", "chartHeight", "-", "markerRadius", ")", "/", "maxValue", ";", "let", "xSpacing", "=", "width", "/", "pointsOnScreen", ";", "let", "centeriser", "=", "xSpacing", "/", "2", "-", "markerRadius", ";", "let", "fullWidth", "=", "xSpacing", "*", "(", "chart", ".", "data", ".", "length", "-", "1", ")", "+", "markerRadius", "+", "centeriser", ";", "let", "xCord", ";", "let", "xCords", "=", "[", "]", ";", "let", "yCords", "=", "[", "]", ";", "chart", ".", "data", ".", "forEach", "(", "(", "d", ",", "idx", ")", "=>", "{", "let", "spacing", "=", "idx", "*", "xSpacing", "+", "centeriser", ";", "if", "(", "spacing", ">", "fullWidth", "*", "t", "&&", "chart", ".", "drawChart", ")", "{", "return", "true", ";", "}", "xCord", "=", "makeXcord", "(", "chart", ",", "fullWidth", ",", "t", ",", "spacing", ",", "markerRadius", ")", ";", "xCords", ".", "push", "(", "xCord", ")", ";", "yCords", ".", "push", "(", "(", "chartHeight", "+", "chartHeightOffset", ")", "-", "d", ".", "value", "*", "heightScaler", "*", "(", "chart", ".", "timingFunctions", "?", "chart", ".", "timingFunctions", "[", "idx", "%", "chart", ".", "timingFunctions", ".", "length", "]", "(", "t", ")", ":", "1", ")", ")", ";", "}", ")", ";", "let", "px", "=", "computeSplineControlPoints", "(", "xCords", ")", ";", "let", "py", "=", "computeSplineControlPoints", "(", "yCords", ")", ";", "let", "splines", "=", "[", "`", "${", "xCords", "[", "0", "]", "}", "${", "yCords", "[", "0", "]", "}", "`", "]", ";", "for", "(", "i", "=", "0", ";", "i", "<", "xCords", ".", "length", "-", "1", ";", "i", "++", ")", "{", "splines", ".", "push", "(", "makeSpline", "(", "xCords", "[", "i", "]", ",", "yCords", "[", "i", "]", ",", "px", ".", "p1", "[", "i", "]", ",", "py", ".", "p1", "[", "i", "]", ",", "px", ".", "p2", "[", "i", "]", ",", "py", ".", "p2", "[", "i", "]", ",", "xCords", "[", "i", "+", "1", "]", ",", "yCords", "[", "i", "+", "1", "]", ")", ")", ";", "}", "if", "(", "closePath", ")", "{", "splines", ".", "push", "(", "`", "${", "chartHeight", "+", "chartHeightOffset", "}", "${", "xCords", "[", "0", "]", "}", "`", ")", ";", "}", "return", "{", "path", ":", "splines", ".", "join", "(", "','", ")", ",", "width", ":", "xCords", ".", "slice", "(", "-", "1", ")", "+", "markerRadius", ",", "maxScroll", ":", "fullWidth", "-", "xSpacing", "+", "markerRadius", "}", ";", "}" ]
Generate the SVG path for a spline or spline-area chart. @param {object} chart The chart object @param {number} width Width of the chart in pixels @param {number} t Scale parameter (range: 0-1), used for animating the graph @param {number} maxValue The maximum value of chart data @param {number} chartHeight Height of the chart in pixels @param {number} chartHeightOffset By how much to offset the chart height. Note: The negation of this number is as the marginTop for the component. This is done so when the graph is animated, overflow is not cut off. @param {number} markerRadius Radius of the markers on the line (needed here so we can add it to the width of the chart element, maybe change name to something better such as padding!!!!) @param {number} pointsOnScreen The number of points to show on the screen without having to scroll. Used to calculate the horizontal spacing between points. (maybe find better name????) @param {boolean} closePath Wether to close the spline (make it an area chart) or not.
[ "Generate", "the", "SVG", "path", "for", "a", "spline", "or", "spline", "-", "area", "chart", "." ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L613-L645
train
redpandatronicsuk/arty-charty
arty-charty/util.js
rgbaToHsla
function rgbaToHsla(h, s, l, a) { return [...rgbToHsl(h,s,l), a]; }
javascript
function rgbaToHsla(h, s, l, a) { return [...rgbToHsl(h,s,l), a]; }
[ "function", "rgbaToHsla", "(", "h", ",", "s", ",", "l", ",", "a", ")", "{", "return", "[", "...", "rgbToHsl", "(", "h", ",", "s", ",", "l", ")", ",", "a", "]", ";", "}" ]
Converts a RGBA colour to HSLA.
[ "Converts", "a", "RGBA", "colour", "to", "HSLA", "." ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L739-L741
train
redpandatronicsuk/arty-charty
arty-charty/util.js
inerpolateColorsFixedAlpha
function inerpolateColorsFixedAlpha(col1, col2, amount, alpha) { let col1rgb = parseColor(col1); let col2rgb = parseColor(col2); return RGBobj2string({ r: Math.min(255, col1rgb.r * amount + col2rgb.r * Math.max(0,1-amount)), g: Math.min(255, col1rgb.g * amount + col2rgb.g * Math.max(0,1-amount)), b: Math.min(255, col1rgb.b * amount + col2rgb.b * Math.max(0,1-amount)), a: alpha }); }
javascript
function inerpolateColorsFixedAlpha(col1, col2, amount, alpha) { let col1rgb = parseColor(col1); let col2rgb = parseColor(col2); return RGBobj2string({ r: Math.min(255, col1rgb.r * amount + col2rgb.r * Math.max(0,1-amount)), g: Math.min(255, col1rgb.g * amount + col2rgb.g * Math.max(0,1-amount)), b: Math.min(255, col1rgb.b * amount + col2rgb.b * Math.max(0,1-amount)), a: alpha }); }
[ "function", "inerpolateColorsFixedAlpha", "(", "col1", ",", "col2", ",", "amount", ",", "alpha", ")", "{", "let", "col1rgb", "=", "parseColor", "(", "col1", ")", ";", "let", "col2rgb", "=", "parseColor", "(", "col2", ")", ";", "return", "RGBobj2string", "(", "{", "r", ":", "Math", ".", "min", "(", "255", ",", "col1rgb", ".", "r", "*", "amount", "+", "col2rgb", ".", "r", "*", "Math", ".", "max", "(", "0", ",", "1", "-", "amount", ")", ")", ",", "g", ":", "Math", ".", "min", "(", "255", ",", "col1rgb", ".", "g", "*", "amount", "+", "col2rgb", ".", "g", "*", "Math", ".", "max", "(", "0", ",", "1", "-", "amount", ")", ")", ",", "b", ":", "Math", ".", "min", "(", "255", ",", "col1rgb", ".", "b", "*", "amount", "+", "col2rgb", ".", "b", "*", "Math", ".", "max", "(", "0", ",", "1", "-", "amount", ")", ")", ",", "a", ":", "alpha", "}", ")", ";", "}" ]
Interpolate two colours and set the alpha value.
[ "Interpolate", "two", "colours", "and", "set", "the", "alpha", "value", "." ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L863-L872
train
redpandatronicsuk/arty-charty
arty-charty/util.js
shadeColor
function shadeColor(col, amount) { let col1rgb = parseColor(col); return RGBobj2string({ r: Math.min(255, col1rgb.r * amount + 0 * Math.max(0,1-amount)), g: Math.min(255, col1rgb.g * amount + 0 * Math.max(0,1-amount)), b: Math.min(255, col1rgb.b * amount + 0 * Math.max(0,1-amount)), a: col1rgb.a }); }
javascript
function shadeColor(col, amount) { let col1rgb = parseColor(col); return RGBobj2string({ r: Math.min(255, col1rgb.r * amount + 0 * Math.max(0,1-amount)), g: Math.min(255, col1rgb.g * amount + 0 * Math.max(0,1-amount)), b: Math.min(255, col1rgb.b * amount + 0 * Math.max(0,1-amount)), a: col1rgb.a }); }
[ "function", "shadeColor", "(", "col", ",", "amount", ")", "{", "let", "col1rgb", "=", "parseColor", "(", "col", ")", ";", "return", "RGBobj2string", "(", "{", "r", ":", "Math", ".", "min", "(", "255", ",", "col1rgb", ".", "r", "*", "amount", "+", "0", "*", "Math", ".", "max", "(", "0", ",", "1", "-", "amount", ")", ")", ",", "g", ":", "Math", ".", "min", "(", "255", ",", "col1rgb", ".", "g", "*", "amount", "+", "0", "*", "Math", ".", "max", "(", "0", ",", "1", "-", "amount", ")", ")", ",", "b", ":", "Math", ".", "min", "(", "255", ",", "col1rgb", ".", "b", "*", "amount", "+", "0", "*", "Math", ".", "max", "(", "0", ",", "1", "-", "amount", ")", ")", ",", "a", ":", "col1rgb", ".", "a", "}", ")", ";", "}" ]
Shade the colour by the given amount.
[ "Shade", "the", "colour", "by", "the", "given", "amount", "." ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L877-L885
train
redpandatronicsuk/arty-charty
arty-charty/util.js
lightenColor
function lightenColor(col, amount) { let colRgba = parseColor(col); let colHsla = rgbaToHsla(colRgba.r, colRgba.g, colRgba.b, colRgba.a); colRgba = hslaToRgba(colHsla[0],colHsla[1],Math.min(Math.max(colHsla[2]+amount, 0), 1),colHsla[3]); return RGBobj2string({ r: colRgba[0], g: colRgba[1], b: colRgba[2], a: colRgba[3] }); }
javascript
function lightenColor(col, amount) { let colRgba = parseColor(col); let colHsla = rgbaToHsla(colRgba.r, colRgba.g, colRgba.b, colRgba.a); colRgba = hslaToRgba(colHsla[0],colHsla[1],Math.min(Math.max(colHsla[2]+amount, 0), 1),colHsla[3]); return RGBobj2string({ r: colRgba[0], g: colRgba[1], b: colRgba[2], a: colRgba[3] }); }
[ "function", "lightenColor", "(", "col", ",", "amount", ")", "{", "let", "colRgba", "=", "parseColor", "(", "col", ")", ";", "let", "colHsla", "=", "rgbaToHsla", "(", "colRgba", ".", "r", ",", "colRgba", ".", "g", ",", "colRgba", ".", "b", ",", "colRgba", ".", "a", ")", ";", "colRgba", "=", "hslaToRgba", "(", "colHsla", "[", "0", "]", ",", "colHsla", "[", "1", "]", ",", "Math", ".", "min", "(", "Math", ".", "max", "(", "colHsla", "[", "2", "]", "+", "amount", ",", "0", ")", ",", "1", ")", ",", "colHsla", "[", "3", "]", ")", ";", "return", "RGBobj2string", "(", "{", "r", ":", "colRgba", "[", "0", "]", ",", "g", ":", "colRgba", "[", "1", "]", ",", "b", ":", "colRgba", "[", "2", "]", ",", "a", ":", "colRgba", "[", "3", "]", "}", ")", ";", "}" ]
Increase colour lightness by the given amount.
[ "Increase", "colour", "lightness", "by", "the", "given", "amount", "." ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L903-L913
train
redpandatronicsuk/arty-charty
arty-charty/util.js
hueshiftColor
function hueshiftColor(col, amount) { let colRgba = parseColor(col); let colHsla = rgbaToHsla(colRgba.r, colRgba.g, colRgba.b, colRgba.a); colRgba = hslaToRgba((hsl[0] + amount) % 1, colHsla[1], colHsla[2],colHsla[3]); return RGBobj2string({ r: colRgba[0], g: colRgba[1], b: colRgba[2], a: colRgba[3] }); }
javascript
function hueshiftColor(col, amount) { let colRgba = parseColor(col); let colHsla = rgbaToHsla(colRgba.r, colRgba.g, colRgba.b, colRgba.a); colRgba = hslaToRgba((hsl[0] + amount) % 1, colHsla[1], colHsla[2],colHsla[3]); return RGBobj2string({ r: colRgba[0], g: colRgba[1], b: colRgba[2], a: colRgba[3] }); }
[ "function", "hueshiftColor", "(", "col", ",", "amount", ")", "{", "let", "colRgba", "=", "parseColor", "(", "col", ")", ";", "let", "colHsla", "=", "rgbaToHsla", "(", "colRgba", ".", "r", ",", "colRgba", ".", "g", ",", "colRgba", ".", "b", ",", "colRgba", ".", "a", ")", ";", "colRgba", "=", "hslaToRgba", "(", "(", "hsl", "[", "0", "]", "+", "amount", ")", "%", "1", ",", "colHsla", "[", "1", "]", ",", "colHsla", "[", "2", "]", ",", "colHsla", "[", "3", "]", ")", ";", "return", "RGBobj2string", "(", "{", "r", ":", "colRgba", "[", "0", "]", ",", "g", ":", "colRgba", "[", "1", "]", ",", "b", ":", "colRgba", "[", "2", "]", ",", "a", ":", "colRgba", "[", "3", "]", "}", ")", ";", "}" ]
Hue shift colour by a given amount.
[ "Hue", "shift", "colour", "by", "a", "given", "amount", "." ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L933-L943
train
redpandatronicsuk/arty-charty
arty-charty/util.js
getMaxSumStack
function getMaxSumStack(arr) { //here!!! let maxValue = Number.MIN_VALUE; arr .forEach((d) => { let stackSum = computeArrayValueSum(d); if (stackSum > maxValue) { maxValue = stackSum; } }); return maxValue; }
javascript
function getMaxSumStack(arr) { //here!!! let maxValue = Number.MIN_VALUE; arr .forEach((d) => { let stackSum = computeArrayValueSum(d); if (stackSum > maxValue) { maxValue = stackSum; } }); return maxValue; }
[ "function", "getMaxSumStack", "(", "arr", ")", "{", "let", "maxValue", "=", "Number", ".", "MIN_VALUE", ";", "arr", ".", "forEach", "(", "(", "d", ")", "=>", "{", "let", "stackSum", "=", "computeArrayValueSum", "(", "d", ")", ";", "if", "(", "stackSum", ">", "maxValue", ")", "{", "maxValue", "=", "stackSum", ";", "}", "}", ")", ";", "return", "maxValue", ";", "}" ]
Find maximum stacksum
[ "Find", "maximum", "stacksum" ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L999-L1009
train
redpandatronicsuk/arty-charty
arty-charty/util.js
getMinMaxValuesXY
function getMinMaxValuesXY(arr) { let maxValueX = Number.MIN_VALUE; let maxValueY = Number.MIN_VALUE; let minValueX = Number.MAX_VALUE; let minValueY = Number.MAX_VALUE; arr .forEach((d) => { if (d.x > maxValueX) { maxValueX = d.x; } if (d.x < minValueX) { minValueX = d.x; } if (d.y > maxValueY) { maxValueY = d.y; } if (d.y < minValueY) { minValueY = d.y; } }); return {maxValueX, minValueX, maxValueY, minValueY}; }
javascript
function getMinMaxValuesXY(arr) { let maxValueX = Number.MIN_VALUE; let maxValueY = Number.MIN_VALUE; let minValueX = Number.MAX_VALUE; let minValueY = Number.MAX_VALUE; arr .forEach((d) => { if (d.x > maxValueX) { maxValueX = d.x; } if (d.x < minValueX) { minValueX = d.x; } if (d.y > maxValueY) { maxValueY = d.y; } if (d.y < minValueY) { minValueY = d.y; } }); return {maxValueX, minValueX, maxValueY, minValueY}; }
[ "function", "getMinMaxValuesXY", "(", "arr", ")", "{", "let", "maxValueX", "=", "Number", ".", "MIN_VALUE", ";", "let", "maxValueY", "=", "Number", ".", "MIN_VALUE", ";", "let", "minValueX", "=", "Number", ".", "MAX_VALUE", ";", "let", "minValueY", "=", "Number", ".", "MAX_VALUE", ";", "arr", ".", "forEach", "(", "(", "d", ")", "=>", "{", "if", "(", "d", ".", "x", ">", "maxValueX", ")", "{", "maxValueX", "=", "d", ".", "x", ";", "}", "if", "(", "d", ".", "x", "<", "minValueX", ")", "{", "minValueX", "=", "d", ".", "x", ";", "}", "if", "(", "d", ".", "y", ">", "maxValueY", ")", "{", "maxValueY", "=", "d", ".", "y", ";", "}", "if", "(", "d", ".", "y", "<", "minValueY", ")", "{", "minValueY", "=", "d", ".", "y", ";", "}", "}", ")", ";", "return", "{", "maxValueX", ",", "minValueX", ",", "maxValueY", ",", "minValueY", "}", ";", "}" ]
Find minimum and maximum X and Y values in an array of XY coordinate objects
[ "Find", "minimum", "and", "maximum", "X", "and", "Y", "values", "in", "an", "array", "of", "XY", "coordinate", "objects" ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L1027-L1048
train
redpandatronicsuk/arty-charty
arty-charty/util.js
getMinMaxValuesCandlestick
function getMinMaxValuesCandlestick(arr) { let maxValue = Number.MIN_VALUE; let minValue = Number.MAX_VALUE; arr .forEach((d) => { if (d.high > maxValue) { maxValue = d.high; } if (d.low < minValue) { minValue = d.low; } }); return {maxValue, minValue}; }
javascript
function getMinMaxValuesCandlestick(arr) { let maxValue = Number.MIN_VALUE; let minValue = Number.MAX_VALUE; arr .forEach((d) => { if (d.high > maxValue) { maxValue = d.high; } if (d.low < minValue) { minValue = d.low; } }); return {maxValue, minValue}; }
[ "function", "getMinMaxValuesCandlestick", "(", "arr", ")", "{", "let", "maxValue", "=", "Number", ".", "MIN_VALUE", ";", "let", "minValue", "=", "Number", ".", "MAX_VALUE", ";", "arr", ".", "forEach", "(", "(", "d", ")", "=>", "{", "if", "(", "d", ".", "high", ">", "maxValue", ")", "{", "maxValue", "=", "d", ".", "high", ";", "}", "if", "(", "d", ".", "low", "<", "minValue", ")", "{", "minValue", "=", "d", ".", "low", ";", "}", "}", ")", ";", "return", "{", "maxValue", ",", "minValue", "}", ";", "}" ]
Find minimum and maximum value in an array of candlestick objects
[ "Find", "minimum", "and", "maximum", "value", "in", "an", "array", "of", "candlestick", "objects" ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L1053-L1066
train
redpandatronicsuk/arty-charty
arty-charty/util.js
findRectangleIndexContainingPoint
function findRectangleIndexContainingPoint(rectangles, x, y) { let closestIdx; rectangles.some((d, idx) => { if ((d.x1 <= x && x <= d.x2) && (d.y1 <= y && y <= d.y2)) { closestIdx = idx; return true; } return false; }); return closestIdx; }
javascript
function findRectangleIndexContainingPoint(rectangles, x, y) { let closestIdx; rectangles.some((d, idx) => { if ((d.x1 <= x && x <= d.x2) && (d.y1 <= y && y <= d.y2)) { closestIdx = idx; return true; } return false; }); return closestIdx; }
[ "function", "findRectangleIndexContainingPoint", "(", "rectangles", ",", "x", ",", "y", ")", "{", "let", "closestIdx", ";", "rectangles", ".", "some", "(", "(", "d", ",", "idx", ")", "=>", "{", "if", "(", "(", "d", ".", "x1", "<=", "x", "&&", "x", "<=", "d", ".", "x2", ")", "&&", "(", "d", ".", "y1", "<=", "y", "&&", "y", "<=", "d", ".", "y2", ")", ")", "{", "closestIdx", "=", "idx", ";", "return", "true", ";", "}", "return", "false", ";", "}", ")", ";", "return", "closestIdx", ";", "}" ]
Find the index of the rectangle that contains a given coordinate. @param {array} points - Array of rectangles, each rectangle is of the form {x1: number, x2: number, y1: number, y2: number}, where x1 and x2 are the minimum and maximum x coordinates and y1 and y3 are the minimum and maximum x coordinates. @param {number} x - The x coordinate @param {number} y - The y coordinate
[ "Find", "the", "index", "of", "the", "rectangle", "that", "contains", "a", "given", "coordinate", "." ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L1091-L1101
train
redpandatronicsuk/arty-charty
arty-charty/util.js
findClosestPointIndexWithinRadius
function findClosestPointIndexWithinRadius(points, x, y, radiusThreshold) { let closestIdx; let closestDist = Number.MAX_VALUE; points.forEach((d, idx) => { let distSqrd = Math.pow(d.x - x, 2) + Math.pow(d.y - y, 2); // changeto: (d.x - x)**2 + (d.y - y)**2; if (distSqrd < closestDist && distSqrd < radiusThreshold) { closestIdx = idx; closestDist = distSqrd; } }); return closestIdx; }
javascript
function findClosestPointIndexWithinRadius(points, x, y, radiusThreshold) { let closestIdx; let closestDist = Number.MAX_VALUE; points.forEach((d, idx) => { let distSqrd = Math.pow(d.x - x, 2) + Math.pow(d.y - y, 2); // changeto: (d.x - x)**2 + (d.y - y)**2; if (distSqrd < closestDist && distSqrd < radiusThreshold) { closestIdx = idx; closestDist = distSqrd; } }); return closestIdx; }
[ "function", "findClosestPointIndexWithinRadius", "(", "points", ",", "x", ",", "y", ",", "radiusThreshold", ")", "{", "let", "closestIdx", ";", "let", "closestDist", "=", "Number", ".", "MAX_VALUE", ";", "points", ".", "forEach", "(", "(", "d", ",", "idx", ")", "=>", "{", "let", "distSqrd", "=", "Math", ".", "pow", "(", "d", ".", "x", "-", "x", ",", "2", ")", "+", "Math", ".", "pow", "(", "d", ".", "y", "-", "y", ",", "2", ")", ";", "if", "(", "distSqrd", "<", "closestDist", "&&", "distSqrd", "<", "radiusThreshold", ")", "{", "closestIdx", "=", "idx", ";", "closestDist", "=", "distSqrd", ";", "}", "}", ")", ";", "return", "closestIdx", ";", "}" ]
Find the index of the closest coordinate to a reference coordinate in an array of coordinates. If no point is found within the threshold distance undefined is returned.
[ "Find", "the", "index", "of", "the", "closest", "coordinate", "to", "a", "reference", "coordinate", "in", "an", "array", "of", "coordinates", ".", "If", "no", "point", "is", "found", "within", "the", "threshold", "distance", "undefined", "is", "returned", "." ]
d0b90b42de9f4360343e25e918358e9b331f080d
https://github.com/redpandatronicsuk/arty-charty/blob/d0b90b42de9f4360343e25e918358e9b331f080d/arty-charty/util.js#L1109-L1120
train
Kronos-Integration/kronos-interceptor-object-data-processor-row
lib/util/property-helper.js
function (fieldDefinition) { let type = fieldDefinition.fieldType; if (typeof type === 'object') { type = fieldDefinition.fieldType.type; } return type; }
javascript
function (fieldDefinition) { let type = fieldDefinition.fieldType; if (typeof type === 'object') { type = fieldDefinition.fieldType.type; } return type; }
[ "function", "(", "fieldDefinition", ")", "{", "let", "type", "=", "fieldDefinition", ".", "fieldType", ";", "if", "(", "typeof", "type", "===", "'object'", ")", "{", "type", "=", "fieldDefinition", ".", "fieldType", ".", "type", ";", "}", "return", "type", ";", "}" ]
Returns the severity for a check property. The severity may be defined globaly for the complete field, but also may be defined on a per check basis @param fieldDefinition The field_definition
[ "Returns", "the", "severity", "for", "a", "check", "property", ".", "The", "severity", "may", "be", "defined", "globaly", "for", "the", "complete", "field", "but", "also", "may", "be", "defined", "on", "a", "per", "check", "basis" ]
678a59b84dab4a9082377c90849a0d62d97a1ea4
https://github.com/Kronos-Integration/kronos-interceptor-object-data-processor-row/blob/678a59b84dab4a9082377c90849a0d62d97a1ea4/lib/util/property-helper.js#L87-L93
train
sociomantic-tsunami/lochness
webpack.config.js
buildConfig
function buildConfig( wantedEnv ) { const isValid = wantedEnv && wantedEnv.length > 0 && allowedEnvs.indexOf( wantedEnv ) !== -1; const validEnv = isValid ? wantedEnv : 'dev'; return configs[ validEnv ]; }
javascript
function buildConfig( wantedEnv ) { const isValid = wantedEnv && wantedEnv.length > 0 && allowedEnvs.indexOf( wantedEnv ) !== -1; const validEnv = isValid ? wantedEnv : 'dev'; return configs[ validEnv ]; }
[ "function", "buildConfig", "(", "wantedEnv", ")", "{", "const", "isValid", "=", "wantedEnv", "&&", "wantedEnv", ".", "length", ">", "0", "&&", "allowedEnvs", ".", "indexOf", "(", "wantedEnv", ")", "!==", "-", "1", ";", "const", "validEnv", "=", "isValid", "?", "wantedEnv", ":", "'dev'", ";", "return", "configs", "[", "validEnv", "]", ";", "}" ]
Build the webpack configuration @param {String} wantedEnv The wanted environment @return {Object} Webpack config
[ "Build", "the", "webpack", "configuration" ]
cf71d6608ce2cdc6d745195a90c815304b8f0f6f
https://github.com/sociomantic-tsunami/lochness/blob/cf71d6608ce2cdc6d745195a90c815304b8f0f6f/webpack.config.js#L37-L45
train
yhtml5/yhtml5-cli
packages/yhtml5-cli/lib/generate.js
generate
function generate (projectPatch, source, done) { shell.mkdir('-p', projectPatch) shell.cp('-Rf', source, projectPatch) done() }
javascript
function generate (projectPatch, source, done) { shell.mkdir('-p', projectPatch) shell.cp('-Rf', source, projectPatch) done() }
[ "function", "generate", "(", "projectPatch", ",", "source", ",", "done", ")", "{", "shell", ".", "mkdir", "(", "'-p'", ",", "projectPatch", ")", "shell", ".", "cp", "(", "'-Rf'", ",", "source", ",", "projectPatch", ")", "done", "(", ")", "}" ]
Generate a template given a `src` and `dest`. @param {String} projectPatch @param {String} source @param {Function} done
[ "Generate", "a", "template", "given", "a", "src", "and", "dest", "." ]
521a8ad160058e453dff87c7cc9bfb16215715c6
https://github.com/yhtml5/yhtml5-cli/blob/521a8ad160058e453dff87c7cc9bfb16215715c6/packages/yhtml5-cli/lib/generate.js#L12-L16
train
feedhenry/fh-mbaas-express
lib/common/authenticate.js
getCacheRefreshInterval
function getCacheRefreshInterval() { var value = parseInt(process.env[CACHE_REFRESH_KEY]); // Should we 0 here to invalidate the cache immediately? if (value && !isNaN(value) && value > 0) { return value; } return DEFAULT_CACHE_REFRESH_SECONDS; }
javascript
function getCacheRefreshInterval() { var value = parseInt(process.env[CACHE_REFRESH_KEY]); // Should we 0 here to invalidate the cache immediately? if (value && !isNaN(value) && value > 0) { return value; } return DEFAULT_CACHE_REFRESH_SECONDS; }
[ "function", "getCacheRefreshInterval", "(", ")", "{", "var", "value", "=", "parseInt", "(", "process", ".", "env", "[", "CACHE_REFRESH_KEY", "]", ")", ";", "if", "(", "value", "&&", "!", "isNaN", "(", "value", ")", "&&", "value", ">", "0", ")", "{", "return", "value", ";", "}", "return", "DEFAULT_CACHE_REFRESH_SECONDS", ";", "}" ]
The refresh interval of the authentication cache should be configurable. Since this is running inside a cloud app the best option is th use an environment variable. @returns {*}
[ "The", "refresh", "interval", "of", "the", "authentication", "cache", "should", "be", "configurable", ".", "Since", "this", "is", "running", "inside", "a", "cloud", "app", "the", "best", "option", "is", "th", "use", "an", "environment", "variable", "." ]
381c2a5842b49a4cbc4519d55b9a3c870b364d3c
https://github.com/feedhenry/fh-mbaas-express/blob/381c2a5842b49a4cbc4519d55b9a3c870b364d3c/lib/common/authenticate.js#L357-L366
train
scijs/cwise-parser
index.js
createLocal
function createLocal(id) { var nstr = prefix + id.replace(/\_/g, "__") localVars.push(nstr) return nstr }
javascript
function createLocal(id) { var nstr = prefix + id.replace(/\_/g, "__") localVars.push(nstr) return nstr }
[ "function", "createLocal", "(", "id", ")", "{", "var", "nstr", "=", "prefix", "+", "id", ".", "replace", "(", "/", "\\_", "/", "g", ",", "\"__\"", ")", "localVars", ".", "push", "(", "nstr", ")", "return", "nstr", "}" ]
Retrieves a local variable
[ "Retrieves", "a", "local", "variable" ]
6b9cbce6ebb6b66051226df75627f740b7ecdcc8
https://github.com/scijs/cwise-parser/blob/6b9cbce6ebb6b66051226df75627f740b7ecdcc8/index.js#L72-L76
train
scijs/cwise-parser
index.js
createThisVar
function createThisVar(id) { var nstr = "this_" + id.replace(/\_/g, "__") thisVars.push(nstr) return nstr }
javascript
function createThisVar(id) { var nstr = "this_" + id.replace(/\_/g, "__") thisVars.push(nstr) return nstr }
[ "function", "createThisVar", "(", "id", ")", "{", "var", "nstr", "=", "\"this_\"", "+", "id", ".", "replace", "(", "/", "\\_", "/", "g", ",", "\"__\"", ")", "thisVars", ".", "push", "(", "nstr", ")", "return", "nstr", "}" ]
Creates a this variable
[ "Creates", "a", "this", "variable" ]
6b9cbce6ebb6b66051226df75627f740b7ecdcc8
https://github.com/scijs/cwise-parser/blob/6b9cbce6ebb6b66051226df75627f740b7ecdcc8/index.js#L79-L83
train
scijs/cwise-parser
index.js
rewrite
function rewrite(node, nstr) { var lo = node.range[0], hi = node.range[1] for(var i=lo+1; i<hi; ++i) { exploded[i] = "" } exploded[lo] = nstr }
javascript
function rewrite(node, nstr) { var lo = node.range[0], hi = node.range[1] for(var i=lo+1; i<hi; ++i) { exploded[i] = "" } exploded[lo] = nstr }
[ "function", "rewrite", "(", "node", ",", "nstr", ")", "{", "var", "lo", "=", "node", ".", "range", "[", "0", "]", ",", "hi", "=", "node", ".", "range", "[", "1", "]", "for", "(", "var", "i", "=", "lo", "+", "1", ";", "i", "<", "hi", ";", "++", "i", ")", "{", "exploded", "[", "i", "]", "=", "\"\"", "}", "exploded", "[", "lo", "]", "=", "nstr", "}" ]
Rewrites an ast node
[ "Rewrites", "an", "ast", "node" ]
6b9cbce6ebb6b66051226df75627f740b7ecdcc8
https://github.com/scijs/cwise-parser/blob/6b9cbce6ebb6b66051226df75627f740b7ecdcc8/index.js#L86-L92
train
dowjones/distribucache
lib/CacheClient.js
CacheClient
function CacheClient(store, config) { EventEmitter.call(this); this._store = store; this._config = config || {}; util.propagateEvent(this._store, this, 'error'); this.on('error', unhandledErrorListener); }
javascript
function CacheClient(store, config) { EventEmitter.call(this); this._store = store; this._config = config || {}; util.propagateEvent(this._store, this, 'error'); this.on('error', unhandledErrorListener); }
[ "function", "CacheClient", "(", "store", ",", "config", ")", "{", "EventEmitter", ".", "call", "(", "this", ")", ";", "this", ".", "_store", "=", "store", ";", "this", ".", "_config", "=", "config", "||", "{", "}", ";", "util", ".", "propagateEvent", "(", "this", ".", "_store", ",", "this", ",", "'error'", ")", ";", "this", ".", "on", "(", "'error'", ",", "unhandledErrorListener", ")", ";", "}" ]
Create a new cache client, decorated with the desired features, based on the provided config. @constructor @param {Store} store @param {Object} [config] @param {Boolean} [config.isPreconfigured] defaults to false @param {String} [config.host] defaults to 'localhost' @param {Number} [config.port] defaults to 6379 @param {String} [config.password] @param {String} [config.namespace] @param {Boolean} [config.optimizeForSmallValues] defaults to false @param {Boolean} [config.optimizeForBuffers] defaults to false @param {String} [config.expiresIn] in ms @param {String} [config.staleIn] in ms @param {Function} [config.populate] @param {Number} [config.populateIn] in ms, defaults to 30sec @param {Number} [config.populateInAttempts] defaults to 5 @param {Number} [config.pausePopulateIn] in ms @param {Number} [config.leaseExpiresIn] in ms @param {Number} [config.timeoutPopulateIn] in ms @param {Number} [config.accessedAtThrottle] in ms @param {Number} [config.namespace]
[ "Create", "a", "new", "cache", "client", "decorated", "with", "the", "desired", "features", "based", "on", "the", "provided", "config", "." ]
ad79caee277771a6e49ee4a98c4983480cd89945
https://github.com/dowjones/distribucache/blob/ad79caee277771a6e49ee4a98c4983480cd89945/lib/CacheClient.js#L46-L54
train
macrat/AsyncMark
src/timer.js
timeit
async function timeit(fun, context={}, args=[]) { const start = now(); await fun.call(context, ...args); const end = now(); return end - start; }
javascript
async function timeit(fun, context={}, args=[]) { const start = now(); await fun.call(context, ...args); const end = now(); return end - start; }
[ "async", "function", "timeit", "(", "fun", ",", "context", "=", "{", "}", ",", "args", "=", "[", "]", ")", "{", "const", "start", "=", "now", "(", ")", ";", "await", "fun", ".", "call", "(", "context", ",", "...", "args", ")", ";", "const", "end", "=", "now", "(", ")", ";", "return", "end", "-", "start", ";", "}" ]
Measure tiem to execute a function. wait for done if the target function returns a thenable object. so you can use async function. NOTE: this function will execute target function only once. @param {function(): ?Promise} fun - the target function. @param {Object} [context={}] - the `this` for target function. @param {Object[]} [args=[]] - arguments to passing to target function. @return {Promise<Number>} milliseconds taked executing. @example const msec = await timeit(function() { # do something heavy. }); @example console.log(await timeit(axios.get, args=['http://example.com'])); @since 0.2.4
[ "Measure", "tiem", "to", "execute", "a", "function", "." ]
84ae4130034c47857d0df0e64d43900a18b8b285
https://github.com/macrat/AsyncMark/blob/84ae4130034c47857d0df0e64d43900a18b8b285/src/timer.js#L79-L85
train
SandJS/http
lib/middleware/ai.js
getCache
function getCache() { return new Promise(function(resolve, reject) { // create and fetch the cache key get(getKey(), function(err, data) { if (err) { return reject(err); } resolve(data); }); }); }
javascript
function getCache() { return new Promise(function(resolve, reject) { // create and fetch the cache key get(getKey(), function(err, data) { if (err) { return reject(err); } resolve(data); }); }); }
[ "function", "getCache", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "get", "(", "getKey", "(", ")", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", ";", "}", "resolve", "(", "data", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Fetches an image buffer from the cache @returns {Promise}
[ "Fetches", "an", "image", "buffer", "from", "the", "cache" ]
8f8b4d23eb5f59d802c9537e0ccd67b47fa79d2f
https://github.com/SandJS/http/blob/8f8b4d23eb5f59d802c9537e0ccd67b47fa79d2f/lib/middleware/ai.js#L323-L333
train
SandJS/http
lib/middleware/ai.js
putCache
function putCache() { return new Promise(function(resolve, reject) { // make the cache key let key = getKey(); // adapt the image adapt(function(err, stdout, stderr) { if (err) { return reject(err); } // convert the new image stream to buffer stream2buffer(stdout, function(err, buffer) { if (err) { return reject(err); } if (!buffer || !buffer.length) { return resolve(buffer); } // put the buffer in the cache put(key, buffer, function(err, data) { if (err) { log(`Cache set failure: ${err instanceof Error ? err.message : err}`); } // return the buffer resolve(buffer); }); }); }); }); }
javascript
function putCache() { return new Promise(function(resolve, reject) { // make the cache key let key = getKey(); // adapt the image adapt(function(err, stdout, stderr) { if (err) { return reject(err); } // convert the new image stream to buffer stream2buffer(stdout, function(err, buffer) { if (err) { return reject(err); } if (!buffer || !buffer.length) { return resolve(buffer); } // put the buffer in the cache put(key, buffer, function(err, data) { if (err) { log(`Cache set failure: ${err instanceof Error ? err.message : err}`); } // return the buffer resolve(buffer); }); }); }); }); }
[ "function", "putCache", "(", ")", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "let", "key", "=", "getKey", "(", ")", ";", "adapt", "(", "function", "(", "err", ",", "stdout", ",", "stderr", ")", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", ";", "}", "stream2buffer", "(", "stdout", ",", "function", "(", "err", ",", "buffer", ")", "{", "if", "(", "err", ")", "{", "return", "reject", "(", "err", ")", ";", "}", "if", "(", "!", "buffer", "||", "!", "buffer", ".", "length", ")", "{", "return", "resolve", "(", "buffer", ")", ";", "}", "put", "(", "key", ",", "buffer", ",", "function", "(", "err", ",", "data", ")", "{", "if", "(", "err", ")", "{", "log", "(", "`", "${", "err", "instanceof", "Error", "?", "err", ".", "message", ":", "err", "}", "`", ")", ";", "}", "resolve", "(", "buffer", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Creates an adapted image buffer | puts it in the cache | returns the buffer @returns {Promise}
[ "Creates", "an", "adapted", "image", "buffer", "|", "puts", "it", "in", "the", "cache", "|", "returns", "the", "buffer" ]
8f8b4d23eb5f59d802c9537e0ccd67b47fa79d2f
https://github.com/SandJS/http/blob/8f8b4d23eb5f59d802c9537e0ccd67b47fa79d2f/lib/middleware/ai.js#L340-L373
train
SandJS/http
lib/middleware/ai.js
getKey
function getKey() { let paramString = width + 'x' + height + '-' + path + (is2x ? '-@2x' : '') + (bg ? `_${bg}` : '') + (crop ? '_crop' : '') + (mode ? `_${mode}` : '') + (trim ? '_trim' : ''); return paramString + '-' + crypto.createHash('sha1').update(paramString).digest('hex'); }
javascript
function getKey() { let paramString = width + 'x' + height + '-' + path + (is2x ? '-@2x' : '') + (bg ? `_${bg}` : '') + (crop ? '_crop' : '') + (mode ? `_${mode}` : '') + (trim ? '_trim' : ''); return paramString + '-' + crypto.createHash('sha1').update(paramString).digest('hex'); }
[ "function", "getKey", "(", ")", "{", "let", "paramString", "=", "width", "+", "'x'", "+", "height", "+", "'-'", "+", "path", "+", "(", "is2x", "?", "'-@2x'", ":", "''", ")", "+", "(", "bg", "?", "`", "${", "bg", "}", "`", ":", "''", ")", "+", "(", "crop", "?", "'_crop'", ":", "''", ")", "+", "(", "mode", "?", "`", "${", "mode", "}", "`", ":", "''", ")", "+", "(", "trim", "?", "'_trim'", ":", "''", ")", ";", "return", "paramString", "+", "'-'", "+", "crypto", ".", "createHash", "(", "'sha1'", ")", ".", "update", "(", "paramString", ")", ".", "digest", "(", "'hex'", ")", ";", "}" ]
Builds a cache key for the adapted image @returns {string}
[ "Builds", "a", "cache", "key", "for", "the", "adapted", "image" ]
8f8b4d23eb5f59d802c9537e0ccd67b47fa79d2f
https://github.com/SandJS/http/blob/8f8b4d23eb5f59d802c9537e0ccd67b47fa79d2f/lib/middleware/ai.js#L380-L391
train
Rhinostone/gina
core/controller/controller.js
function(type, resStr, resArr, resObj) { switch(type){ case 'css': var css = resObj; for (var res in resArr) { //means that you will find options. if (typeof(resArr[res]) == "object") { //console.info('found object ', resArr[res]); css.media = (resArr[res].options.media) ? resArr[res].options.media : css.media; css.rel = (resArr[res].options.rel) ? resArr[res].options.rel : css.rel; css.type = (resArr[res].options.type) ? resArr[res].options.type : css.type; if (!css.content[resArr[res]._]) { css.content[resArr[res]._] = '<link href="'+ resArr[res]._ +'" media="'+ css.media +'" rel="'+ css.rel +'" type="'+ css.type +'">'; resStr += '\n\t' + css.content[resArr[res]._] } } else { css.content[resArr[res]] = '<link href="'+ resArr[res] +'" media="screen" rel="'+ css.rel +'" type="'+ css.type +'">'; resStr += '\n\t' + css.content[resArr[res]] } } return { css : css, cssStr : resStr } break; case 'js': var js = resObj; for (var res in resArr) { //means that you will find options if ( typeof(resArr[res]) == "object" ) { js.type = (resArr[res].options.type) ? resArr[res].options.type : js.type; if (!js.content[resArr[res]._]) { js.content[resArr[res]._] = '<script type="'+ js.type +'" src="'+ resArr[res]._ +'"></script>'; resStr += '\n' + js.content[resArr[res]._]; } } else { js.content[resArr[res]] = '<script type="'+ js.type +'" src="'+ resArr[res] +'"></script>'; resStr += '\n' + js.content[resArr[res]] } } return { js : js, jsStr : resStr } break; } }
javascript
function(type, resStr, resArr, resObj) { switch(type){ case 'css': var css = resObj; for (var res in resArr) { //means that you will find options. if (typeof(resArr[res]) == "object") { //console.info('found object ', resArr[res]); css.media = (resArr[res].options.media) ? resArr[res].options.media : css.media; css.rel = (resArr[res].options.rel) ? resArr[res].options.rel : css.rel; css.type = (resArr[res].options.type) ? resArr[res].options.type : css.type; if (!css.content[resArr[res]._]) { css.content[resArr[res]._] = '<link href="'+ resArr[res]._ +'" media="'+ css.media +'" rel="'+ css.rel +'" type="'+ css.type +'">'; resStr += '\n\t' + css.content[resArr[res]._] } } else { css.content[resArr[res]] = '<link href="'+ resArr[res] +'" media="screen" rel="'+ css.rel +'" type="'+ css.type +'">'; resStr += '\n\t' + css.content[resArr[res]] } } return { css : css, cssStr : resStr } break; case 'js': var js = resObj; for (var res in resArr) { //means that you will find options if ( typeof(resArr[res]) == "object" ) { js.type = (resArr[res].options.type) ? resArr[res].options.type : js.type; if (!js.content[resArr[res]._]) { js.content[resArr[res]._] = '<script type="'+ js.type +'" src="'+ resArr[res]._ +'"></script>'; resStr += '\n' + js.content[resArr[res]._]; } } else { js.content[resArr[res]] = '<script type="'+ js.type +'" src="'+ resArr[res] +'"></script>'; resStr += '\n' + js.content[resArr[res]] } } return { js : js, jsStr : resStr } break; } }
[ "function", "(", "type", ",", "resStr", ",", "resArr", ",", "resObj", ")", "{", "switch", "(", "type", ")", "{", "case", "'css'", ":", "var", "css", "=", "resObj", ";", "for", "(", "var", "res", "in", "resArr", ")", "{", "if", "(", "typeof", "(", "resArr", "[", "res", "]", ")", "==", "\"object\"", ")", "{", "css", ".", "media", "=", "(", "resArr", "[", "res", "]", ".", "options", ".", "media", ")", "?", "resArr", "[", "res", "]", ".", "options", ".", "media", ":", "css", ".", "media", ";", "css", ".", "rel", "=", "(", "resArr", "[", "res", "]", ".", "options", ".", "rel", ")", "?", "resArr", "[", "res", "]", ".", "options", ".", "rel", ":", "css", ".", "rel", ";", "css", ".", "type", "=", "(", "resArr", "[", "res", "]", ".", "options", ".", "type", ")", "?", "resArr", "[", "res", "]", ".", "options", ".", "type", ":", "css", ".", "type", ";", "if", "(", "!", "css", ".", "content", "[", "resArr", "[", "res", "]", ".", "_", "]", ")", "{", "css", ".", "content", "[", "resArr", "[", "res", "]", ".", "_", "]", "=", "'<link href=\"'", "+", "resArr", "[", "res", "]", ".", "_", "+", "'\" media=\"'", "+", "css", ".", "media", "+", "'\" rel=\"'", "+", "css", ".", "rel", "+", "'\" type=\"'", "+", "css", ".", "type", "+", "'\">'", ";", "resStr", "+=", "'\\n\\t'", "+", "\\n", "}", "}", "else", "\\t", "}", "css", ".", "content", "[", "resArr", "[", "res", "]", ".", "_", "]", "{", "css", ".", "content", "[", "resArr", "[", "res", "]", "]", "=", "'<link href=\"'", "+", "resArr", "[", "res", "]", "+", "'\" media=\"screen\" rel=\"'", "+", "css", ".", "rel", "+", "'\" type=\"'", "+", "css", ".", "type", "+", "'\">'", ";", "resStr", "+=", "'\\n\\t'", "+", "\\n", "}", "\\t", "}", "}" ]
Get node resources @param {string} type @param {string} resStr @param {array} resArr @param {object} resObj @return {object} content @private
[ "Get", "node", "resources" ]
c6ba13d3255a43734c54880ff12d3a50df53ebea
https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/controller/controller.js#L942-L989
train
Rhinostone/gina
core/controller/controller.js
function (i, res, files, cb) { if (!files.length || files.length == 0) { cb(false) } else { if ( fs.existsSync(files[i].target) ) new _(files[i].target).rmSync(); var sourceStream = fs.createReadStream(files[i].source); var destinationStream = fs.createWriteStream(files[i].target); sourceStream .pipe(destinationStream) .on('error', function () { var err = 'Error on SuperController::copyFile(...): Not found ' + files[i].source + ' or ' + files[i].target; cb(err) }) .on('close', function () { try { fs.unlinkSync(files[i].source); files.splice(i, 1); } catch (err) { cb(err) } movefiles(i, res, files, cb) }) } }
javascript
function (i, res, files, cb) { if (!files.length || files.length == 0) { cb(false) } else { if ( fs.existsSync(files[i].target) ) new _(files[i].target).rmSync(); var sourceStream = fs.createReadStream(files[i].source); var destinationStream = fs.createWriteStream(files[i].target); sourceStream .pipe(destinationStream) .on('error', function () { var err = 'Error on SuperController::copyFile(...): Not found ' + files[i].source + ' or ' + files[i].target; cb(err) }) .on('close', function () { try { fs.unlinkSync(files[i].source); files.splice(i, 1); } catch (err) { cb(err) } movefiles(i, res, files, cb) }) } }
[ "function", "(", "i", ",", "res", ",", "files", ",", "cb", ")", "{", "if", "(", "!", "files", ".", "length", "||", "files", ".", "length", "==", "0", ")", "{", "cb", "(", "false", ")", "}", "else", "{", "if", "(", "fs", ".", "existsSync", "(", "files", "[", "i", "]", ".", "target", ")", ")", "new", "_", "(", "files", "[", "i", "]", ".", "target", ")", ".", "rmSync", "(", ")", ";", "var", "sourceStream", "=", "fs", ".", "createReadStream", "(", "files", "[", "i", "]", ".", "source", ")", ";", "var", "destinationStream", "=", "fs", ".", "createWriteStream", "(", "files", "[", "i", "]", ".", "target", ")", ";", "sourceStream", ".", "pipe", "(", "destinationStream", ")", ".", "on", "(", "'error'", ",", "function", "(", ")", "{", "var", "err", "=", "'Error on SuperController::copyFile(...): Not found '", "+", "files", "[", "i", "]", ".", "source", "+", "' or '", "+", "files", "[", "i", "]", ".", "target", ";", "cb", "(", "err", ")", "}", ")", ".", "on", "(", "'close'", ",", "function", "(", ")", "{", "try", "{", "fs", ".", "unlinkSync", "(", "files", "[", "i", "]", ".", "source", ")", ";", "files", ".", "splice", "(", "i", ",", "1", ")", ";", "}", "catch", "(", "err", ")", "{", "cb", "(", "err", ")", "}", "movefiles", "(", "i", ",", "res", ",", "files", ",", "cb", ")", "}", ")", "}", "}" ]
Move files to assets dir @param {object} res @param {collection} files @callback cb @param {object} [err]
[ "Move", "files", "to", "assets", "dir" ]
c6ba13d3255a43734c54880ff12d3a50df53ebea
https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/controller/controller.js#L1165-L1192
train
Rhinostone/gina
core/controller/controller.js
function(req) { req.getParams = function() { // copy var params = JSON.parse(JSON.stringify(req.params)); switch( req.method.toLowerCase() ) { case 'get': params = merge(params, req.get, true); break; case 'post': params = merge(params, req.post, true); break; case 'put': params = merge(params, req.put, true); break; case 'delete': params = merge(params, req.delete, true); break; } return params } req.getParam = function(name) { // copy var param = null, params = JSON.parse(JSON.stringify(req.params)); switch( req.method.toLowerCase() ) { case 'get': param = req.get[name]; break; case 'post': param = req.post[name]; break; case 'put': param= req.put[name]; break; case 'delete': param = req.delete[name]; break; } return param } }
javascript
function(req) { req.getParams = function() { // copy var params = JSON.parse(JSON.stringify(req.params)); switch( req.method.toLowerCase() ) { case 'get': params = merge(params, req.get, true); break; case 'post': params = merge(params, req.post, true); break; case 'put': params = merge(params, req.put, true); break; case 'delete': params = merge(params, req.delete, true); break; } return params } req.getParam = function(name) { // copy var param = null, params = JSON.parse(JSON.stringify(req.params)); switch( req.method.toLowerCase() ) { case 'get': param = req.get[name]; break; case 'post': param = req.post[name]; break; case 'put': param= req.put[name]; break; case 'delete': param = req.delete[name]; break; } return param } }
[ "function", "(", "req", ")", "{", "req", ".", "getParams", "=", "function", "(", ")", "{", "var", "params", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "req", ".", "params", ")", ")", ";", "switch", "(", "req", ".", "method", ".", "toLowerCase", "(", ")", ")", "{", "case", "'get'", ":", "params", "=", "merge", "(", "params", ",", "req", ".", "get", ",", "true", ")", ";", "break", ";", "case", "'post'", ":", "params", "=", "merge", "(", "params", ",", "req", ".", "post", ",", "true", ")", ";", "break", ";", "case", "'put'", ":", "params", "=", "merge", "(", "params", ",", "req", ".", "put", ",", "true", ")", ";", "break", ";", "case", "'delete'", ":", "params", "=", "merge", "(", "params", ",", "req", ".", "delete", ",", "true", ")", ";", "break", ";", "}", "return", "params", "}", "req", ".", "getParam", "=", "function", "(", "name", ")", "{", "var", "param", "=", "null", ",", "params", "=", "JSON", ".", "parse", "(", "JSON", ".", "stringify", "(", "req", ".", "params", ")", ")", ";", "switch", "(", "req", ".", "method", ".", "toLowerCase", "(", ")", ")", "{", "case", "'get'", ":", "param", "=", "req", ".", "get", "[", "name", "]", ";", "break", ";", "case", "'post'", ":", "param", "=", "req", ".", "post", "[", "name", "]", ";", "break", ";", "case", "'put'", ":", "param", "=", "req", ".", "put", "[", "name", "]", ";", "break", ";", "case", "'delete'", ":", "param", "=", "req", ".", "delete", "[", "name", "]", ";", "break", ";", "}", "return", "param", "}", "}" ]
Get all Params
[ "Get", "all", "Params" ]
c6ba13d3255a43734c54880ff12d3a50df53ebea
https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/controller/controller.js#L1542-L1591
train
Rhinostone/gina
core/controller/controller.js
function (code) { var list = {}, cde = 'short', name = null; if ( typeof(code) != 'undefined' && typeof(userLocales[0][code]) == 'string' ) { cde = code } else if ( typeof(code) != 'undefined' ) ( console.warn('`'+ code +'` not supported : sticking with `short` code') ) for ( var i = 0, len = userLocales.length; i< len; ++i ) { if (userLocales[i][cde]) { name = userLocales[i].full || userLocales[i].officialName.short; if ( name ) list[ userLocales[i][cde] ] = name; } } return list }
javascript
function (code) { var list = {}, cde = 'short', name = null; if ( typeof(code) != 'undefined' && typeof(userLocales[0][code]) == 'string' ) { cde = code } else if ( typeof(code) != 'undefined' ) ( console.warn('`'+ code +'` not supported : sticking with `short` code') ) for ( var i = 0, len = userLocales.length; i< len; ++i ) { if (userLocales[i][cde]) { name = userLocales[i].full || userLocales[i].officialName.short; if ( name ) list[ userLocales[i][cde] ] = name; } } return list }
[ "function", "(", "code", ")", "{", "var", "list", "=", "{", "}", ",", "cde", "=", "'short'", ",", "name", "=", "null", ";", "if", "(", "typeof", "(", "code", ")", "!=", "'undefined'", "&&", "typeof", "(", "userLocales", "[", "0", "]", "[", "code", "]", ")", "==", "'string'", ")", "{", "cde", "=", "code", "}", "else", "if", "(", "typeof", "(", "code", ")", "!=", "'undefined'", ")", "(", "console", ".", "warn", "(", "'`'", "+", "code", "+", "'` not supported : sticking with `short` code'", ")", ")", "for", "(", "var", "i", "=", "0", ",", "len", "=", "userLocales", ".", "length", ";", "i", "<", "len", ";", "++", "i", ")", "{", "if", "(", "userLocales", "[", "i", "]", "[", "cde", "]", ")", "{", "name", "=", "userLocales", "[", "i", "]", ".", "full", "||", "userLocales", "[", "i", "]", ".", "officialName", ".", "short", ";", "if", "(", "name", ")", "list", "[", "userLocales", "[", "i", "]", "[", "cde", "]", "]", "=", "name", ";", "}", "}", "return", "list", "}" ]
Get countries list @param {string} [code] - e.g.: short, long, fifa, m49 @return {object} countries - countries code & value list
[ "Get", "countries", "list" ]
c6ba13d3255a43734c54880ff12d3a50df53ebea
https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/controller/controller.js#L1649-L1670
train
Rhinostone/gina
core/controller/controller.js
function (arr){ var tmp = null, curObj = {}, obj = {}, count = 0, data = {}, last = null; for (var r in arr) { tmp = r.split("."); //Creating structure - Adding sub levels for (var o in tmp) { count++; if (last && typeof(obj[last]) == "undefined") { curObj[last] = {}; if (count >= tmp.length) { // assigning. // !!! if null or undefined, it will be ignored while extending. curObj[last][tmp[o]] = (arr[r]) ? arr[r] : "undefined"; last = null; count = 0; break } else { curObj[last][tmp[o]] = {} } } else if (tmp.length === 1) { //Just one root var curObj[tmp[o]] = (arr[r]) ? arr[r] : "undefined"; obj = curObj; break } obj = curObj; last = tmp[o] } //data = merge(data, obj, true); data = merge(obj, data); obj = {}; curObj = {} } return data }
javascript
function (arr){ var tmp = null, curObj = {}, obj = {}, count = 0, data = {}, last = null; for (var r in arr) { tmp = r.split("."); //Creating structure - Adding sub levels for (var o in tmp) { count++; if (last && typeof(obj[last]) == "undefined") { curObj[last] = {}; if (count >= tmp.length) { // assigning. // !!! if null or undefined, it will be ignored while extending. curObj[last][tmp[o]] = (arr[r]) ? arr[r] : "undefined"; last = null; count = 0; break } else { curObj[last][tmp[o]] = {} } } else if (tmp.length === 1) { //Just one root var curObj[tmp[o]] = (arr[r]) ? arr[r] : "undefined"; obj = curObj; break } obj = curObj; last = tmp[o] } //data = merge(data, obj, true); data = merge(obj, data); obj = {}; curObj = {} } return data }
[ "function", "(", "arr", ")", "{", "var", "tmp", "=", "null", ",", "curObj", "=", "{", "}", ",", "obj", "=", "{", "}", ",", "count", "=", "0", ",", "data", "=", "{", "}", ",", "last", "=", "null", ";", "for", "(", "var", "r", "in", "arr", ")", "{", "tmp", "=", "r", ".", "split", "(", "\".\"", ")", ";", "for", "(", "var", "o", "in", "tmp", ")", "{", "count", "++", ";", "if", "(", "last", "&&", "typeof", "(", "obj", "[", "last", "]", ")", "==", "\"undefined\"", ")", "{", "curObj", "[", "last", "]", "=", "{", "}", ";", "if", "(", "count", ">=", "tmp", ".", "length", ")", "{", "curObj", "[", "last", "]", "[", "tmp", "[", "o", "]", "]", "=", "(", "arr", "[", "r", "]", ")", "?", "arr", "[", "r", "]", ":", "\"undefined\"", ";", "last", "=", "null", ";", "count", "=", "0", ";", "break", "}", "else", "{", "curObj", "[", "last", "]", "[", "tmp", "[", "o", "]", "]", "=", "{", "}", "}", "}", "else", "if", "(", "tmp", ".", "length", "===", "1", ")", "{", "curObj", "[", "tmp", "[", "o", "]", "]", "=", "(", "arr", "[", "r", "]", ")", "?", "arr", "[", "r", "]", ":", "\"undefined\"", ";", "obj", "=", "curObj", ";", "break", "}", "obj", "=", "curObj", ";", "last", "=", "tmp", "[", "o", "]", "}", "data", "=", "merge", "(", "obj", ",", "data", ")", ";", "obj", "=", "{", "}", ";", "curObj", "=", "{", "}", "}", "return", "data", "}" ]
converting references to objects
[ "converting", "references", "to", "objects" ]
c6ba13d3255a43734c54880ff12d3a50df53ebea
https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/controller/controller.js#L1816-L1854
train
invisible-tech/mongoose-extras
customAsserts/documentAssertions.js
assertSameObjectIdArray
function assertSameObjectIdArray(actual, expected, msg) { assert(Array.isArray(actual), 'assertSameObjectIdArray: First argument is not an Array.') assert(Array.isArray(expected), 'assertSameObjectIdArray: Second argument is not an Array.') assert(size(actual) > 0 || size(expected) > 0, 'assertSameObjectIdArray: Received two empty Arrays.') assert.strictEqual(size(actual), size(expected), 'assertSameObjectIdArray: arrays different sizes') const parseIds = flow(map(stringifyObjectId), sortBy(identity)) try { parseIds(actual) } catch (err) { throw Error(`assertSameObjectIdArray 1st argument: ${err.message}`) } try { parseIds(expected) } catch (err) { throw Error(`assertSameObjectIdArray 2nd argument: ${err.message}`) } assert.deepStrictEqual(parseIds(actual), parseIds(expected), msg) }
javascript
function assertSameObjectIdArray(actual, expected, msg) { assert(Array.isArray(actual), 'assertSameObjectIdArray: First argument is not an Array.') assert(Array.isArray(expected), 'assertSameObjectIdArray: Second argument is not an Array.') assert(size(actual) > 0 || size(expected) > 0, 'assertSameObjectIdArray: Received two empty Arrays.') assert.strictEqual(size(actual), size(expected), 'assertSameObjectIdArray: arrays different sizes') const parseIds = flow(map(stringifyObjectId), sortBy(identity)) try { parseIds(actual) } catch (err) { throw Error(`assertSameObjectIdArray 1st argument: ${err.message}`) } try { parseIds(expected) } catch (err) { throw Error(`assertSameObjectIdArray 2nd argument: ${err.message}`) } assert.deepStrictEqual(parseIds(actual), parseIds(expected), msg) }
[ "function", "assertSameObjectIdArray", "(", "actual", ",", "expected", ",", "msg", ")", "{", "assert", "(", "Array", ".", "isArray", "(", "actual", ")", ",", "'assertSameObjectIdArray: First argument is not an Array.'", ")", "assert", "(", "Array", ".", "isArray", "(", "expected", ")", ",", "'assertSameObjectIdArray: Second argument is not an Array.'", ")", "assert", "(", "size", "(", "actual", ")", ">", "0", "||", "size", "(", "expected", ")", ">", "0", ",", "'assertSameObjectIdArray: Received two empty Arrays.'", ")", "assert", ".", "strictEqual", "(", "size", "(", "actual", ")", ",", "size", "(", "expected", ")", ",", "'assertSameObjectIdArray: arrays different sizes'", ")", "const", "parseIds", "=", "flow", "(", "map", "(", "stringifyObjectId", ")", ",", "sortBy", "(", "identity", ")", ")", "try", "{", "parseIds", "(", "actual", ")", "}", "catch", "(", "err", ")", "{", "throw", "Error", "(", "`", "${", "err", ".", "message", "}", "`", ")", "}", "try", "{", "parseIds", "(", "expected", ")", "}", "catch", "(", "err", ")", "{", "throw", "Error", "(", "`", "${", "err", ".", "message", "}", "`", ")", "}", "assert", ".", "deepStrictEqual", "(", "parseIds", "(", "actual", ")", ",", "parseIds", "(", "expected", ")", ",", "msg", ")", "}" ]
Throws if the given actual and expected arrays of ObjectIds don't match. @method assertSameDocumentIdArray @param {ObjectId[]} actual - Array of ObjectId @param {ObjectId[]} expected - Array of ObjectId @param {String} msg - Optional custom error message @return {undefined} - Throws if assertions fail
[ "Throws", "if", "the", "given", "actual", "and", "expected", "arrays", "of", "ObjectIds", "don", "t", "match", "." ]
9b572554a292ead1644b0afa3fc5a5b382d5dec9
https://github.com/invisible-tech/mongoose-extras/blob/9b572554a292ead1644b0afa3fc5a5b382d5dec9/customAsserts/documentAssertions.js#L73-L82
train
Rhinostone/gina
script/pre_install.js
PreInstall
function PreInstall() { var self = this; var init = function() { self.isWin32 = ( os.platform() == 'win32' ) ? true : false; self.path = __dirname.substring(0, (__dirname.length - 'script'.length)); console.debug('paths -> '+ self.path); if ( hasNodeModulesSync() ) { // cleaining old var target = new _(self.path + '/node_modules'); console.debug('replacing: ', target.toString() ); var err = target.rmSync(); if (err instanceof Error) { throw err; process.exit(1) } fs.mkdirSync(_(self.path) + '/node_modules'); } } var hasNodeModulesSync = function() { return fs.existsSync( _(self.path + '/node_modules') ) } // compare with post_install.js if you want to use this //var filename = _(self.path + '/SUCCESS'); //var installed = fs.existsSync( filename ); //if (installed && /node_modules\/gina/.test( new _(process.cwd()).toUnixStyle() ) ) { // process.exit(0) //} else { // fs.writeFileSync(filename, true ); //} // ... init() }
javascript
function PreInstall() { var self = this; var init = function() { self.isWin32 = ( os.platform() == 'win32' ) ? true : false; self.path = __dirname.substring(0, (__dirname.length - 'script'.length)); console.debug('paths -> '+ self.path); if ( hasNodeModulesSync() ) { // cleaining old var target = new _(self.path + '/node_modules'); console.debug('replacing: ', target.toString() ); var err = target.rmSync(); if (err instanceof Error) { throw err; process.exit(1) } fs.mkdirSync(_(self.path) + '/node_modules'); } } var hasNodeModulesSync = function() { return fs.existsSync( _(self.path + '/node_modules') ) } // compare with post_install.js if you want to use this //var filename = _(self.path + '/SUCCESS'); //var installed = fs.existsSync( filename ); //if (installed && /node_modules\/gina/.test( new _(process.cwd()).toUnixStyle() ) ) { // process.exit(0) //} else { // fs.writeFileSync(filename, true ); //} // ... init() }
[ "function", "PreInstall", "(", ")", "{", "var", "self", "=", "this", ";", "var", "init", "=", "function", "(", ")", "{", "self", ".", "isWin32", "=", "(", "os", ".", "platform", "(", ")", "==", "'win32'", ")", "?", "true", ":", "false", ";", "self", ".", "path", "=", "__dirname", ".", "substring", "(", "0", ",", "(", "__dirname", ".", "length", "-", "'script'", ".", "length", ")", ")", ";", "console", ".", "debug", "(", "'paths -> '", "+", "self", ".", "path", ")", ";", "if", "(", "hasNodeModulesSync", "(", ")", ")", "{", "var", "target", "=", "new", "_", "(", "self", ".", "path", "+", "'/node_modules'", ")", ";", "console", ".", "debug", "(", "'replacing: '", ",", "target", ".", "toString", "(", ")", ")", ";", "var", "err", "=", "target", ".", "rmSync", "(", ")", ";", "if", "(", "err", "instanceof", "Error", ")", "{", "throw", "err", ";", "process", ".", "exit", "(", "1", ")", "}", "fs", ".", "mkdirSync", "(", "_", "(", "self", ".", "path", ")", "+", "'/node_modules'", ")", ";", "}", "}", "var", "hasNodeModulesSync", "=", "function", "(", ")", "{", "return", "fs", ".", "existsSync", "(", "_", "(", "self", ".", "path", "+", "'/node_modules'", ")", ")", "}", "init", "(", ")", "}" ]
Pre install constructor @constructor
[ "Pre", "install", "constructor" ]
c6ba13d3255a43734c54880ff12d3a50df53ebea
https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/script/pre_install.js#L24-L61
train
Rhinostone/gina
core/plugins/lib/validator/src/main.js
function($form) { var $form = $form, _id = null; if ( typeof($form) == 'undefined' ) { if ( typeof(this.target) != 'undefined' ) { _id = this.target.getAttribute('id'); } else { _id = this.getAttribute('id'); } $form = instance.$forms[_id] } else if ( typeof($form) == 'string' ) { _id = $form; _id = _id.replace(/\#/, ''); if ( typeof(instance.$forms[_id]) == 'undefined') { throw new Error('[ FormValidator::resetErrorsDisplay([formId]) ] `'+$form+'` not found') } $form = instance.$forms[_id] } //reseting error display handleErrorsDisplay($form['target'], []); return $form }
javascript
function($form) { var $form = $form, _id = null; if ( typeof($form) == 'undefined' ) { if ( typeof(this.target) != 'undefined' ) { _id = this.target.getAttribute('id'); } else { _id = this.getAttribute('id'); } $form = instance.$forms[_id] } else if ( typeof($form) == 'string' ) { _id = $form; _id = _id.replace(/\#/, ''); if ( typeof(instance.$forms[_id]) == 'undefined') { throw new Error('[ FormValidator::resetErrorsDisplay([formId]) ] `'+$form+'` not found') } $form = instance.$forms[_id] } //reseting error display handleErrorsDisplay($form['target'], []); return $form }
[ "function", "(", "$form", ")", "{", "var", "$form", "=", "$form", ",", "_id", "=", "null", ";", "if", "(", "typeof", "(", "$form", ")", "==", "'undefined'", ")", "{", "if", "(", "typeof", "(", "this", ".", "target", ")", "!=", "'undefined'", ")", "{", "_id", "=", "this", ".", "target", ".", "getAttribute", "(", "'id'", ")", ";", "}", "else", "{", "_id", "=", "this", ".", "getAttribute", "(", "'id'", ")", ";", "}", "$form", "=", "instance", ".", "$forms", "[", "_id", "]", "}", "else", "if", "(", "typeof", "(", "$form", ")", "==", "'string'", ")", "{", "_id", "=", "$form", ";", "_id", "=", "_id", ".", "replace", "(", "/", "\\#", "/", ",", "''", ")", ";", "if", "(", "typeof", "(", "instance", ".", "$forms", "[", "_id", "]", ")", "==", "'undefined'", ")", "{", "throw", "new", "Error", "(", "'[ FormValidator::resetErrorsDisplay([formId]) ] `'", "+", "$form", "+", "'` not found'", ")", "}", "$form", "=", "instance", ".", "$forms", "[", "_id", "]", "}", "handleErrorsDisplay", "(", "$form", "[", "'target'", "]", ",", "[", "]", ")", ";", "return", "$form", "}" ]
Reset errors display @param {object|string} [$form|formId]
[ "Reset", "errors", "display" ]
c6ba13d3255a43734c54880ff12d3a50df53ebea
https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/plugins/lib/validator/src/main.js#L392-L416
train
Rhinostone/gina
core/plugins/lib/validator/src/main.js
function(rules, tmp) { var _r = null; for (var r in rules) { if ( typeof(rules[r]) == 'object' && typeof(instance.rules[tmp + r]) == 'undefined' ) { _r = r; if (/\[|\]/.test(r) ) { // must be a real path _r = r.replace(/\[/g, '.').replace(/\]/g, ''); } instance.rules[tmp + _r] = rules[r]; //delete instance.rules[r]; parseRules(rules[r], tmp + _r +'.'); } } }
javascript
function(rules, tmp) { var _r = null; for (var r in rules) { if ( typeof(rules[r]) == 'object' && typeof(instance.rules[tmp + r]) == 'undefined' ) { _r = r; if (/\[|\]/.test(r) ) { // must be a real path _r = r.replace(/\[/g, '.').replace(/\]/g, ''); } instance.rules[tmp + _r] = rules[r]; //delete instance.rules[r]; parseRules(rules[r], tmp + _r +'.'); } } }
[ "function", "(", "rules", ",", "tmp", ")", "{", "var", "_r", "=", "null", ";", "for", "(", "var", "r", "in", "rules", ")", "{", "if", "(", "typeof", "(", "rules", "[", "r", "]", ")", "==", "'object'", "&&", "typeof", "(", "instance", ".", "rules", "[", "tmp", "+", "r", "]", ")", "==", "'undefined'", ")", "{", "_r", "=", "r", ";", "if", "(", "/", "\\[|\\]", "/", ".", "test", "(", "r", ")", ")", "{", "_r", "=", "r", ".", "replace", "(", "/", "\\[", "/", "g", ",", "'.'", ")", ".", "replace", "(", "/", "\\]", "/", "g", ",", "''", ")", ";", "}", "instance", ".", "rules", "[", "tmp", "+", "_r", "]", "=", "rules", "[", "r", "]", ";", "parseRules", "(", "rules", "[", "r", "]", ",", "tmp", "+", "_r", "+", "'.'", ")", ";", "}", "}", "}" ]
parseRules - Preparing rules paths @param {object} rules @param {string} tmp - path
[ "parseRules", "-", "Preparing", "rules", "paths" ]
c6ba13d3255a43734c54880ff12d3a50df53ebea
https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/plugins/lib/validator/src/main.js#L1103-L1119
train
Kronos-Integration/kronos-interceptor-object-data-processor-row
lib/converter/data-field-splitter.js
createSplitterForField
function createSplitterForField(multiFieldDefinitionPart, fieldName) { if (multiFieldDefinitionPart === undefined) { throw ("'multiFieldDefinitionPart' must not be undefined"); } if (fieldName === undefined) { throw ("'fieldName' must not be undefined"); } const delimiter = multiFieldDefinitionPart.delimiter; let escapeChar = multiFieldDefinitionPart.escapeChar; let removeWhiteSpace = true; let uniqueFields = true; let sortFields = true; let removeEmpty = true; // set default values if (multiFieldDefinitionPart.removeWhiteSpace !== undefined) { // remove leading and trailing whitespaces removeWhiteSpace = multiFieldDefinitionPart.removeWhiteSpace; } if (multiFieldDefinitionPart.uniqueFields !== undefined) { // remove duplicates from the list uniqueFields = multiFieldDefinitionPart.uniqueFields; } if (multiFieldDefinitionPart.sortFields !== undefined) { // sort the fields sortFields = multiFieldDefinitionPart.sortFields; } if (multiFieldDefinitionPart.removeEmpty !== undefined) { // Empty fields will be deleted removeEmpty = multiFieldDefinitionPart.removeEmpty; } return function (content) { if (content.hasOwnProperty(fieldName)) { // the field exists in the content record let fieldValue = content[fieldName]; if (fieldValue) { // ------------------------------------------------ // escape delimiter // ------------------------------------------------ if (escapeChar) { escapeChar = escapeChar.replace(/\\/, "\\\\"); escapeChar = escapeChar.replace(/\//, "\\/"); // The escaped delimiter will be replaced by the string '<--DIVIDER-->' let re = new RegExp(escapeChar + delimiter, 'g'); fieldValue = fieldValue.replace(re, TMP_DEVIDER); } // ------------------------------------------------ // split the string // ------------------------------------------------ let values = fieldValue.split(delimiter); if (escapeChar) { // remove the escape char let re = new RegExp(TMP_DEVIDER, 'g'); for (let i = 0; i < values.length; i++) { values[i] = values[i].replace(re, delimiter); } } // ------------------------------------------------ // remove the leading and trailing whiteSpaces // ------------------------------------------------ if (removeWhiteSpace) { for (let i = 0; i < values.length; i++) { values[i] = values[i].trim(); } } // ------------------------------------------------ // remove empty fields // ------------------------------------------------ if (removeEmpty) { let i = 0; let j = 0; for (i = 0; i < values.length; i++) { if (values[i]) { values[j] = values[i]; j++; } } values.splice(j, i); } // ------------------------------------------------ // sort fields // ------------------------------------------------ if (sortFields) { values.sort(); } // ------------------------------------------------ // remove duplicates // ------------------------------------------------ if (uniqueFields) { values = values.filter(function (elem, pos) { return values.indexOf(elem) == pos; }); } // ------------------------------------------------ // store the splited fields back to the content // ------------------------------------------------ content[fieldName] = values; } } return null; }; }
javascript
function createSplitterForField(multiFieldDefinitionPart, fieldName) { if (multiFieldDefinitionPart === undefined) { throw ("'multiFieldDefinitionPart' must not be undefined"); } if (fieldName === undefined) { throw ("'fieldName' must not be undefined"); } const delimiter = multiFieldDefinitionPart.delimiter; let escapeChar = multiFieldDefinitionPart.escapeChar; let removeWhiteSpace = true; let uniqueFields = true; let sortFields = true; let removeEmpty = true; // set default values if (multiFieldDefinitionPart.removeWhiteSpace !== undefined) { // remove leading and trailing whitespaces removeWhiteSpace = multiFieldDefinitionPart.removeWhiteSpace; } if (multiFieldDefinitionPart.uniqueFields !== undefined) { // remove duplicates from the list uniqueFields = multiFieldDefinitionPart.uniqueFields; } if (multiFieldDefinitionPart.sortFields !== undefined) { // sort the fields sortFields = multiFieldDefinitionPart.sortFields; } if (multiFieldDefinitionPart.removeEmpty !== undefined) { // Empty fields will be deleted removeEmpty = multiFieldDefinitionPart.removeEmpty; } return function (content) { if (content.hasOwnProperty(fieldName)) { // the field exists in the content record let fieldValue = content[fieldName]; if (fieldValue) { // ------------------------------------------------ // escape delimiter // ------------------------------------------------ if (escapeChar) { escapeChar = escapeChar.replace(/\\/, "\\\\"); escapeChar = escapeChar.replace(/\//, "\\/"); // The escaped delimiter will be replaced by the string '<--DIVIDER-->' let re = new RegExp(escapeChar + delimiter, 'g'); fieldValue = fieldValue.replace(re, TMP_DEVIDER); } // ------------------------------------------------ // split the string // ------------------------------------------------ let values = fieldValue.split(delimiter); if (escapeChar) { // remove the escape char let re = new RegExp(TMP_DEVIDER, 'g'); for (let i = 0; i < values.length; i++) { values[i] = values[i].replace(re, delimiter); } } // ------------------------------------------------ // remove the leading and trailing whiteSpaces // ------------------------------------------------ if (removeWhiteSpace) { for (let i = 0; i < values.length; i++) { values[i] = values[i].trim(); } } // ------------------------------------------------ // remove empty fields // ------------------------------------------------ if (removeEmpty) { let i = 0; let j = 0; for (i = 0; i < values.length; i++) { if (values[i]) { values[j] = values[i]; j++; } } values.splice(j, i); } // ------------------------------------------------ // sort fields // ------------------------------------------------ if (sortFields) { values.sort(); } // ------------------------------------------------ // remove duplicates // ------------------------------------------------ if (uniqueFields) { values = values.filter(function (elem, pos) { return values.indexOf(elem) == pos; }); } // ------------------------------------------------ // store the splited fields back to the content // ------------------------------------------------ content[fieldName] = values; } } return null; }; }
[ "function", "createSplitterForField", "(", "multiFieldDefinitionPart", ",", "fieldName", ")", "{", "if", "(", "multiFieldDefinitionPart", "===", "undefined", ")", "{", "throw", "(", "\"'multiFieldDefinitionPart' must not be undefined\"", ")", ";", "}", "if", "(", "fieldName", "===", "undefined", ")", "{", "throw", "(", "\"'fieldName' must not be undefined\"", ")", ";", "}", "const", "delimiter", "=", "multiFieldDefinitionPart", ".", "delimiter", ";", "let", "escapeChar", "=", "multiFieldDefinitionPart", ".", "escapeChar", ";", "let", "removeWhiteSpace", "=", "true", ";", "let", "uniqueFields", "=", "true", ";", "let", "sortFields", "=", "true", ";", "let", "removeEmpty", "=", "true", ";", "if", "(", "multiFieldDefinitionPart", ".", "removeWhiteSpace", "!==", "undefined", ")", "{", "removeWhiteSpace", "=", "multiFieldDefinitionPart", ".", "removeWhiteSpace", ";", "}", "if", "(", "multiFieldDefinitionPart", ".", "uniqueFields", "!==", "undefined", ")", "{", "uniqueFields", "=", "multiFieldDefinitionPart", ".", "uniqueFields", ";", "}", "if", "(", "multiFieldDefinitionPart", ".", "sortFields", "!==", "undefined", ")", "{", "sortFields", "=", "multiFieldDefinitionPart", ".", "sortFields", ";", "}", "if", "(", "multiFieldDefinitionPart", ".", "removeEmpty", "!==", "undefined", ")", "{", "removeEmpty", "=", "multiFieldDefinitionPart", ".", "removeEmpty", ";", "}", "return", "function", "(", "content", ")", "{", "if", "(", "content", ".", "hasOwnProperty", "(", "fieldName", ")", ")", "{", "let", "fieldValue", "=", "content", "[", "fieldName", "]", ";", "if", "(", "fieldValue", ")", "{", "if", "(", "escapeChar", ")", "{", "escapeChar", "=", "escapeChar", ".", "replace", "(", "/", "\\\\", "/", ",", "\"\\\\\\\\\"", ")", ";", "\\\\", "\\\\", "escapeChar", "=", "escapeChar", ".", "replace", "(", "/", "\\/", "/", ",", "\"\\\\/\"", ")", ";", "}", "\\\\", "let", "re", "=", "new", "RegExp", "(", "escapeChar", "+", "delimiter", ",", "'g'", ")", ";", "fieldValue", "=", "fieldValue", ".", "replace", "(", "re", ",", "TMP_DEVIDER", ")", ";", "let", "values", "=", "fieldValue", ".", "split", "(", "delimiter", ")", ";", "if", "(", "escapeChar", ")", "{", "let", "re", "=", "new", "RegExp", "(", "TMP_DEVIDER", ",", "'g'", ")", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "values", ".", "length", ";", "i", "++", ")", "{", "values", "[", "i", "]", "=", "values", "[", "i", "]", ".", "replace", "(", "re", ",", "delimiter", ")", ";", "}", "}", "if", "(", "removeWhiteSpace", ")", "{", "for", "(", "let", "i", "=", "0", ";", "i", "<", "values", ".", "length", ";", "i", "++", ")", "{", "values", "[", "i", "]", "=", "values", "[", "i", "]", ".", "trim", "(", ")", ";", "}", "}", "if", "(", "removeEmpty", ")", "{", "let", "i", "=", "0", ";", "let", "j", "=", "0", ";", "for", "(", "i", "=", "0", ";", "i", "<", "values", ".", "length", ";", "i", "++", ")", "{", "if", "(", "values", "[", "i", "]", ")", "{", "values", "[", "j", "]", "=", "values", "[", "i", "]", ";", "j", "++", ";", "}", "}", "values", ".", "splice", "(", "j", ",", "i", ")", ";", "}", "}", "}", "if", "(", "sortFields", ")", "{", "values", ".", "sort", "(", ")", ";", "}", "}", ";", "}" ]
Create the field spliter for a given field definition The field must be a multiField. @param multiFieldDefinitionPart The multiField part of aa field definition for one field. @param fieldName The name of the current multiField
[ "Create", "the", "field", "spliter", "for", "a", "given", "field", "definition", "The", "field", "must", "be", "a", "multiField", "." ]
678a59b84dab4a9082377c90849a0d62d97a1ea4
https://github.com/Kronos-Integration/kronos-interceptor-object-data-processor-row/blob/678a59b84dab4a9082377c90849a0d62d97a1ea4/lib/converter/data-field-splitter.js#L28-L146
train
AlCalzone/shared-utils
build/sorted-list/index.js
findPrevNode
function findPrevNode(firstNode, item, comparer) { let ret; let prevNode = firstNode; // while item > prevNode.value while (prevNode != undefined && comparer(prevNode.value, item) > 0) { ret = prevNode; prevNode = prevNode.next; } return ret; }
javascript
function findPrevNode(firstNode, item, comparer) { let ret; let prevNode = firstNode; // while item > prevNode.value while (prevNode != undefined && comparer(prevNode.value, item) > 0) { ret = prevNode; prevNode = prevNode.next; } return ret; }
[ "function", "findPrevNode", "(", "firstNode", ",", "item", ",", "comparer", ")", "{", "let", "ret", ";", "let", "prevNode", "=", "firstNode", ";", "while", "(", "prevNode", "!=", "undefined", "&&", "comparer", "(", "prevNode", ".", "value", ",", "item", ")", ">", "0", ")", "{", "ret", "=", "prevNode", ";", "prevNode", "=", "prevNode", ".", "next", ";", "}", "return", "ret", ";", "}" ]
Seeks the list from the beginning and finds the position to add the new item
[ "Seeks", "the", "list", "from", "the", "beginning", "and", "finds", "the", "position", "to", "add", "the", "new", "item" ]
9048e1f8793909fae7acb503984a4d8aadad4f3b
https://github.com/AlCalzone/shared-utils/blob/9048e1f8793909fae7acb503984a4d8aadad4f3b/build/sorted-list/index.js#L8-L17
train
AlCalzone/shared-utils
build/sorted-list/index.js
findNode
function findNode(firstNode, predicate) { let curNode = firstNode; while (curNode != null) { if (predicate(curNode.value)) return curNode; curNode = curNode.next; } }
javascript
function findNode(firstNode, predicate) { let curNode = firstNode; while (curNode != null) { if (predicate(curNode.value)) return curNode; curNode = curNode.next; } }
[ "function", "findNode", "(", "firstNode", ",", "predicate", ")", "{", "let", "curNode", "=", "firstNode", ";", "while", "(", "curNode", "!=", "null", ")", "{", "if", "(", "predicate", "(", "curNode", ".", "value", ")", ")", "return", "curNode", ";", "curNode", "=", "curNode", ".", "next", ";", "}", "}" ]
Seeks the list from the beginning and returns the first item matching the given predicate
[ "Seeks", "the", "list", "from", "the", "beginning", "and", "returns", "the", "first", "item", "matching", "the", "given", "predicate" ]
9048e1f8793909fae7acb503984a4d8aadad4f3b
https://github.com/AlCalzone/shared-utils/blob/9048e1f8793909fae7acb503984a4d8aadad4f3b/build/sorted-list/index.js#L21-L28
train
Kronos-Integration/kronos-interceptor-object-data-processor-row
lib/recordCheck/data-check-string-email.js
createCheckEmail
function createCheckEmail(fieldDefinition, fieldName) { const severity = propertyHelper.getSeverity(fieldDefinition); // return getIteratorFunction: function (fieldName, defaultValue, checkProperties, checkFunction, getErrorFunction, // getValueIfErrorFunction, getValueIfOkFunction) { let errorInfo = { severity: severity, errorCode: 'NOT_EMAIL' }; return functionHelper.getParserCheck(errorInfo, getEmailIfValid, fieldName, undefined); }
javascript
function createCheckEmail(fieldDefinition, fieldName) { const severity = propertyHelper.getSeverity(fieldDefinition); // return getIteratorFunction: function (fieldName, defaultValue, checkProperties, checkFunction, getErrorFunction, // getValueIfErrorFunction, getValueIfOkFunction) { let errorInfo = { severity: severity, errorCode: 'NOT_EMAIL' }; return functionHelper.getParserCheck(errorInfo, getEmailIfValid, fieldName, undefined); }
[ "function", "createCheckEmail", "(", "fieldDefinition", ",", "fieldName", ")", "{", "const", "severity", "=", "propertyHelper", ".", "getSeverity", "(", "fieldDefinition", ")", ";", "let", "errorInfo", "=", "{", "severity", ":", "severity", ",", "errorCode", ":", "'NOT_EMAIL'", "}", ";", "return", "functionHelper", ".", "getParserCheck", "(", "errorInfo", ",", "getEmailIfValid", ",", "fieldName", ",", "undefined", ")", ";", "}" ]
Checks if a given string looks like a valid email. @param fieldDefinition The field_definition for this field. @param fieldName The name of the current field @return The check
[ "Checks", "if", "a", "given", "string", "looks", "like", "a", "valid", "email", "." ]
678a59b84dab4a9082377c90849a0d62d97a1ea4
https://github.com/Kronos-Integration/kronos-interceptor-object-data-processor-row/blob/678a59b84dab4a9082377c90849a0d62d97a1ea4/lib/recordCheck/data-check-string-email.js#L45-L58
train
Kronos-Integration/kronos-interceptor-object-data-processor-row
lib/recordCheck/data-check-string-email.js
createCheckDefaultValue
function createCheckDefaultValue(fieldDefinition, fieldName) { const defaultValue = fieldDefinition.defaultValue; // ----------------------------------------------------------------------- // Set default value // ----------------------------------------------------------------------- return function (content) { const valueToCheck = content[fieldName]; // If the value is defined, we need to check it if (valueToCheck === undefined || valueToCheck === null) { if (defaultValue !== undefined) { content[fieldName] = defaultValue; } } else { if (Array.isArray(valueToCheck)) { valueToCheck.forEach(function (item, idx, arr) { if (item === undefined || item === null) { arr[idx] = defaultValue; } }); } } }; }
javascript
function createCheckDefaultValue(fieldDefinition, fieldName) { const defaultValue = fieldDefinition.defaultValue; // ----------------------------------------------------------------------- // Set default value // ----------------------------------------------------------------------- return function (content) { const valueToCheck = content[fieldName]; // If the value is defined, we need to check it if (valueToCheck === undefined || valueToCheck === null) { if (defaultValue !== undefined) { content[fieldName] = defaultValue; } } else { if (Array.isArray(valueToCheck)) { valueToCheck.forEach(function (item, idx, arr) { if (item === undefined || item === null) { arr[idx] = defaultValue; } }); } } }; }
[ "function", "createCheckDefaultValue", "(", "fieldDefinition", ",", "fieldName", ")", "{", "const", "defaultValue", "=", "fieldDefinition", ".", "defaultValue", ";", "return", "function", "(", "content", ")", "{", "const", "valueToCheck", "=", "content", "[", "fieldName", "]", ";", "if", "(", "valueToCheck", "===", "undefined", "||", "valueToCheck", "===", "null", ")", "{", "if", "(", "defaultValue", "!==", "undefined", ")", "{", "content", "[", "fieldName", "]", "=", "defaultValue", ";", "}", "}", "else", "{", "if", "(", "Array", ".", "isArray", "(", "valueToCheck", ")", ")", "{", "valueToCheck", ".", "forEach", "(", "function", "(", "item", ",", "idx", ",", "arr", ")", "{", "if", "(", "item", "===", "undefined", "||", "item", "===", "null", ")", "{", "arr", "[", "idx", "]", "=", "defaultValue", ";", "}", "}", ")", ";", "}", "}", "}", ";", "}" ]
Set the default value if no value is there @param fieldDefinition The field_definition for this field. @param fieldName The name of the current field @return checks A list of checks to be perfomred
[ "Set", "the", "default", "value", "if", "no", "value", "is", "there" ]
678a59b84dab4a9082377c90849a0d62d97a1ea4
https://github.com/Kronos-Integration/kronos-interceptor-object-data-processor-row/blob/678a59b84dab4a9082377c90849a0d62d97a1ea4/lib/recordCheck/data-check-string-email.js#L66-L90
train
Rhinostone/gina
core/utils/helpers/dateFormat.js
function (format) { var name = "default"; for (var f in self.masks) { if ( self.masks[f] === format ) return f } return name }
javascript
function (format) { var name = "default"; for (var f in self.masks) { if ( self.masks[f] === format ) return f } return name }
[ "function", "(", "format", ")", "{", "var", "name", "=", "\"default\"", ";", "for", "(", "var", "f", "in", "self", ".", "masks", ")", "{", "if", "(", "self", ".", "masks", "[", "f", "]", "===", "format", ")", "return", "f", "}", "return", "name", "}" ]
Get mask name from a given format @param {string} format @return {string} maskName
[ "Get", "mask", "name", "from", "a", "given", "format" ]
c6ba13d3255a43734c54880ff12d3a50df53ebea
https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/helpers/dateFormat.js#L143-L153
train
Rhinostone/gina
core/utils/helpers/dateFormat.js
function(date, dateTo) { if ( dateTo instanceof Date) { // The number of milliseconds in one day var oneDay = 1000 * 60 * 60 * 24 // Convert both dates to milliseconds var date1Ms = date.getTime() var date2Ms = dateTo.getTime() // Calculate the difference in milliseconds var count = Math.abs(date1Ms - date2Ms) // Convert back to days and return return Math.round(count/oneDay); } else { throw new Error('dateTo is not instance of Date() !') } }
javascript
function(date, dateTo) { if ( dateTo instanceof Date) { // The number of milliseconds in one day var oneDay = 1000 * 60 * 60 * 24 // Convert both dates to milliseconds var date1Ms = date.getTime() var date2Ms = dateTo.getTime() // Calculate the difference in milliseconds var count = Math.abs(date1Ms - date2Ms) // Convert back to days and return return Math.round(count/oneDay); } else { throw new Error('dateTo is not instance of Date() !') } }
[ "function", "(", "date", ",", "dateTo", ")", "{", "if", "(", "dateTo", "instanceof", "Date", ")", "{", "var", "oneDay", "=", "1000", "*", "60", "*", "60", "*", "24", "var", "date1Ms", "=", "date", ".", "getTime", "(", ")", "var", "date2Ms", "=", "dateTo", ".", "getTime", "(", ")", "var", "count", "=", "Math", ".", "abs", "(", "date1Ms", "-", "date2Ms", ")", "return", "Math", ".", "round", "(", "count", "/", "oneDay", ")", ";", "}", "else", "{", "throw", "new", "Error", "(", "'dateTo is not instance of Date() !'", ")", "}", "}" ]
Count days from the current date to another TODO - add a closure to `ignoreWeekend()` based on Utils::Validator TODO - add a closure to `ignoreFromList(array)` based on Utils::Validator @param {object} dateTo @return {number} count
[ "Count", "days", "from", "the", "current", "date", "to", "another" ]
c6ba13d3255a43734c54880ff12d3a50df53ebea
https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/helpers/dateFormat.js#L165-L183
train
Rhinostone/gina
core/utils/helpers/dateFormat.js
function(date, dateTo, mask) { if ( dateTo instanceof Date) { var count = countDaysTo(date, dateTo) , month = date.getMonth() , year = date.getFullYear() , day = date.getDate() + 1 , dateObj = new Date(year, month, day) , days = [] , i = 0; for (; i < count; ++i) { if ( typeof(mask) != 'undefined' ) { days.push(new Date(dateObj).format(mask)); } else { days.push(new Date(dateObj)); } dateObj.setDate(dateObj.getDate() + 1); } return days || []; } else { throw new Error('dateTo is not instance of Date() !') } }
javascript
function(date, dateTo, mask) { if ( dateTo instanceof Date) { var count = countDaysTo(date, dateTo) , month = date.getMonth() , year = date.getFullYear() , day = date.getDate() + 1 , dateObj = new Date(year, month, day) , days = [] , i = 0; for (; i < count; ++i) { if ( typeof(mask) != 'undefined' ) { days.push(new Date(dateObj).format(mask)); } else { days.push(new Date(dateObj)); } dateObj.setDate(dateObj.getDate() + 1); } return days || []; } else { throw new Error('dateTo is not instance of Date() !') } }
[ "function", "(", "date", ",", "dateTo", ",", "mask", ")", "{", "if", "(", "dateTo", "instanceof", "Date", ")", "{", "var", "count", "=", "countDaysTo", "(", "date", ",", "dateTo", ")", ",", "month", "=", "date", ".", "getMonth", "(", ")", ",", "year", "=", "date", ".", "getFullYear", "(", ")", ",", "day", "=", "date", ".", "getDate", "(", ")", "+", "1", ",", "dateObj", "=", "new", "Date", "(", "year", ",", "month", ",", "day", ")", ",", "days", "=", "[", "]", ",", "i", "=", "0", ";", "for", "(", ";", "i", "<", "count", ";", "++", "i", ")", "{", "if", "(", "typeof", "(", "mask", ")", "!=", "'undefined'", ")", "{", "days", ".", "push", "(", "new", "Date", "(", "dateObj", ")", ".", "format", "(", "mask", ")", ")", ";", "}", "else", "{", "days", ".", "push", "(", "new", "Date", "(", "dateObj", ")", ")", ";", "}", "dateObj", ".", "setDate", "(", "dateObj", ".", "getDate", "(", ")", "+", "1", ")", ";", "}", "return", "days", "||", "[", "]", ";", "}", "else", "{", "throw", "new", "Error", "(", "'dateTo is not instance of Date() !'", ")", "}", "}" ]
Will give an array of dates between the current date to a targeted date TODO - add a closure to `ignoreWeekend()` based on Utils::Validator TODO - add a closure to `ignoreFromList(array)` based on Utils::Validator @param {object} dateTo @param {string} [ mask ] @return {array} dates
[ "Will", "give", "an", "array", "of", "dates", "between", "the", "current", "date", "to", "a", "targeted", "date" ]
c6ba13d3255a43734c54880ff12d3a50df53ebea
https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/helpers/dateFormat.js#L196-L221
train
dowjones/distribucache
lib/decorators/BaseDecorator.js
BaseDecorator
function BaseDecorator(cache, config, configSchema) { this._cache = cache; if (config) { this._configSchema = configSchema; this._config = this._humanTimeIntervalToMs(config); this._config = this._validateConfig(configSchema, this._config); } // substitute cb, for cases // when you don't need a callback, but // don't want to loose the error. this._emitError = function (err) { if (err) this.emit('error', err); }.bind(this); }
javascript
function BaseDecorator(cache, config, configSchema) { this._cache = cache; if (config) { this._configSchema = configSchema; this._config = this._humanTimeIntervalToMs(config); this._config = this._validateConfig(configSchema, this._config); } // substitute cb, for cases // when you don't need a callback, but // don't want to loose the error. this._emitError = function (err) { if (err) this.emit('error', err); }.bind(this); }
[ "function", "BaseDecorator", "(", "cache", ",", "config", ",", "configSchema", ")", "{", "this", ".", "_cache", "=", "cache", ";", "if", "(", "config", ")", "{", "this", ".", "_configSchema", "=", "configSchema", ";", "this", ".", "_config", "=", "this", ".", "_humanTimeIntervalToMs", "(", "config", ")", ";", "this", ".", "_config", "=", "this", ".", "_validateConfig", "(", "configSchema", ",", "this", ".", "_config", ")", ";", "}", "this", ".", "_emitError", "=", "function", "(", "err", ")", "{", "if", "(", "err", ")", "this", ".", "emit", "(", "'error'", ",", "err", ")", ";", "}", ".", "bind", "(", "this", ")", ";", "}" ]
The root of the Decorator tree @constructor
[ "The", "root", "of", "the", "Decorator", "tree" ]
ad79caee277771a6e49ee4a98c4983480cd89945
https://github.com/dowjones/distribucache/blob/ad79caee277771a6e49ee4a98c4983480cd89945/lib/decorators/BaseDecorator.js#L12-L27
train
Rhinostone/gina
core/utils/lib/merge/src/main.js
function (obj) { if ( !obj || {}.toString.call(obj) !== '[object Object]' || obj.nodeType || obj.setInterval ) { return false } var hasOwn = {}.hasOwnProperty; var hasOwnConstructor = hasOwn.call(obj, 'constructor'); // added test for node > v6 var hasMethodPrototyped = ( typeof(obj.constructor) != 'undefined' ) ? hasOwn.call(obj.constructor.prototype, 'isPrototypeOf') : false; if ( obj.constructor && !hasOwnConstructor && !hasMethodPrototyped ) { return false } //Own properties are enumerated firstly, so to speed up, //if last one is own, then all properties are own. var key; return key === undefined || hasOwn.call(obj, key) }
javascript
function (obj) { if ( !obj || {}.toString.call(obj) !== '[object Object]' || obj.nodeType || obj.setInterval ) { return false } var hasOwn = {}.hasOwnProperty; var hasOwnConstructor = hasOwn.call(obj, 'constructor'); // added test for node > v6 var hasMethodPrototyped = ( typeof(obj.constructor) != 'undefined' ) ? hasOwn.call(obj.constructor.prototype, 'isPrototypeOf') : false; if ( obj.constructor && !hasOwnConstructor && !hasMethodPrototyped ) { return false } //Own properties are enumerated firstly, so to speed up, //if last one is own, then all properties are own. var key; return key === undefined || hasOwn.call(obj, key) }
[ "function", "(", "obj", ")", "{", "if", "(", "!", "obj", "||", "{", "}", ".", "toString", ".", "call", "(", "obj", ")", "!==", "'[object Object]'", "||", "obj", ".", "nodeType", "||", "obj", ".", "setInterval", ")", "{", "return", "false", "}", "var", "hasOwn", "=", "{", "}", ".", "hasOwnProperty", ";", "var", "hasOwnConstructor", "=", "hasOwn", ".", "call", "(", "obj", ",", "'constructor'", ")", ";", "var", "hasMethodPrototyped", "=", "(", "typeof", "(", "obj", ".", "constructor", ")", "!=", "'undefined'", ")", "?", "hasOwn", ".", "call", "(", "obj", ".", "constructor", ".", "prototype", ",", "'isPrototypeOf'", ")", ":", "false", ";", "if", "(", "obj", ".", "constructor", "&&", "!", "hasOwnConstructor", "&&", "!", "hasMethodPrototyped", ")", "{", "return", "false", "}", "var", "key", ";", "return", "key", "===", "undefined", "||", "hasOwn", ".", "call", "(", "obj", ",", "key", ")", "}" ]
Check if object before merging.
[ "Check", "if", "object", "before", "merging", "." ]
c6ba13d3255a43734c54880ff12d3a50df53ebea
https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/utils/lib/merge/src/main.js#L307-L333
train
kevinoid/promise-nodeify
index.js
doCallback
function doCallback(callback, reason, value) { // Note: Could delay callback call until later, as When.js does, but this // loses the stack (particularly for bluebird long traces) and causes // unnecessary delay in the non-exception (common) case. try { // Match argument length to resolve/reject in case callback cares. // Note: bluebird has argument length 1 if value === undefined due to // https://github.com/petkaantonov/bluebird/issues/170 // If you are reading this and want similar behavior, I'll consider it. if (reason) { callback(reason); } else { callback(null, value); } } catch (err) { later(() => { throw err; }); } }
javascript
function doCallback(callback, reason, value) { // Note: Could delay callback call until later, as When.js does, but this // loses the stack (particularly for bluebird long traces) and causes // unnecessary delay in the non-exception (common) case. try { // Match argument length to resolve/reject in case callback cares. // Note: bluebird has argument length 1 if value === undefined due to // https://github.com/petkaantonov/bluebird/issues/170 // If you are reading this and want similar behavior, I'll consider it. if (reason) { callback(reason); } else { callback(null, value); } } catch (err) { later(() => { throw err; }); } }
[ "function", "doCallback", "(", "callback", ",", "reason", ",", "value", ")", "{", "try", "{", "if", "(", "reason", ")", "{", "callback", "(", "reason", ")", ";", "}", "else", "{", "callback", "(", "null", ",", "value", ")", ";", "}", "}", "catch", "(", "err", ")", "{", "later", "(", "(", ")", "=>", "{", "throw", "err", ";", "}", ")", ";", "}", "}" ]
Invokes callback and ensures any exceptions thrown are uncaught. @private
[ "Invokes", "callback", "and", "ensures", "any", "exceptions", "thrown", "are", "uncaught", "." ]
1542cb7824c1b5e0e19e925dfb9650bfe8c7cdbd
https://github.com/kevinoid/promise-nodeify/blob/1542cb7824c1b5e0e19e925dfb9650bfe8c7cdbd/index.js#L20-L37
train
kevinoid/promise-nodeify
index.js
promiseNodeify
function promiseNodeify(promise, callback) { if (typeof callback !== 'function') { return promise; } function onRejected(reason) { // callback is unlikely to recognize or expect a falsey error. // (we also rely on truthyness for arguments.length in doCallback) // Convert it to something truthy let truthyReason = reason; if (!truthyReason) { // Note: unthenify converts falsey rejections to TypeError: // https://github.com/blakeembrey/unthenify/blob/v1.0.0/src/index.ts#L32 // We use bluebird convention for Error, message, and .cause property truthyReason = new Error(String(reason)); truthyReason.cause = reason; } doCallback(callback, truthyReason); } function onResolved(value) { doCallback(callback, null, value); } promise.then(onResolved, onRejected); return undefined; }
javascript
function promiseNodeify(promise, callback) { if (typeof callback !== 'function') { return promise; } function onRejected(reason) { // callback is unlikely to recognize or expect a falsey error. // (we also rely on truthyness for arguments.length in doCallback) // Convert it to something truthy let truthyReason = reason; if (!truthyReason) { // Note: unthenify converts falsey rejections to TypeError: // https://github.com/blakeembrey/unthenify/blob/v1.0.0/src/index.ts#L32 // We use bluebird convention for Error, message, and .cause property truthyReason = new Error(String(reason)); truthyReason.cause = reason; } doCallback(callback, truthyReason); } function onResolved(value) { doCallback(callback, null, value); } promise.then(onResolved, onRejected); return undefined; }
[ "function", "promiseNodeify", "(", "promise", ",", "callback", ")", "{", "if", "(", "typeof", "callback", "!==", "'function'", ")", "{", "return", "promise", ";", "}", "function", "onRejected", "(", "reason", ")", "{", "let", "truthyReason", "=", "reason", ";", "if", "(", "!", "truthyReason", ")", "{", "truthyReason", "=", "new", "Error", "(", "String", "(", "reason", ")", ")", ";", "truthyReason", ".", "cause", "=", "reason", ";", "}", "doCallback", "(", "callback", ",", "truthyReason", ")", ";", "}", "function", "onResolved", "(", "value", ")", "{", "doCallback", "(", "callback", ",", "null", ",", "value", ")", ";", "}", "promise", ".", "then", "(", "onResolved", ",", "onRejected", ")", ";", "return", "undefined", ";", "}" ]
Calls a node-style callback when a Promise is resolved or rejected. This function provides the behavior of {@link https://github.com/then/nodeify then <code>nodeify</code>}, {@link https://github.com/cujojs/when/blob/master/docs/api.md#nodebindcallback when.js <code>node.bindCallback</code>}, or {@link http://bluebirdjs.com/docs/api/ascallback.html bluebird <code>Promise.prototype.nodeify</code> (now <code>Promise.prototype.asCallback</code>)} (without options). @ template ValueType @param {!Promise<ValueType>} promise Promise to monitor. @param {?function(*, ValueType=)=} callback Node-style callback to be called when <code>promise</code> is resolved or rejected. If <code>promise</code> is rejected with a falsey value the first argument will be an instance of <code>Error</code> with a <code>.cause</code> property with the rejected value. @return {Promise<ValueType>|undefined} <code>undefined</code> if <code>callback</code> is a function, otherwise a <code>Promise</code> which behaves like <code>promise</code> (currently is <code>promise</code>, but is not guaranteed to remain so). @alias module:promise-nodeify
[ "Calls", "a", "node", "-", "style", "callback", "when", "a", "Promise", "is", "resolved", "or", "rejected", "." ]
1542cb7824c1b5e0e19e925dfb9650bfe8c7cdbd
https://github.com/kevinoid/promise-nodeify/blob/1542cb7824c1b5e0e19e925dfb9650bfe8c7cdbd/index.js#L63-L90
train
Gi60s/binary-case
index.js
getBinaryCase
function getBinaryCase (str, val) { let res = ''; for (let i = 0; i < str.length; i++) { const code = str.charCodeAt(i); if (code >= 65 && code <= 90) { res += val & 1 ? String.fromCharCode(code + 32) : String.fromCharCode(code); val >>>= 1; } else if (code >= 97 && code <= 122) { res += val & 1 ? String.fromCharCode(code - 32) : String.fromCharCode(code); val >>>= 1; } else { res += String.fromCharCode(code); } if (val === 0) { return res + str.substr(i + 1); } } return res; }
javascript
function getBinaryCase (str, val) { let res = ''; for (let i = 0; i < str.length; i++) { const code = str.charCodeAt(i); if (code >= 65 && code <= 90) { res += val & 1 ? String.fromCharCode(code + 32) : String.fromCharCode(code); val >>>= 1; } else if (code >= 97 && code <= 122) { res += val & 1 ? String.fromCharCode(code - 32) : String.fromCharCode(code); val >>>= 1; } else { res += String.fromCharCode(code); } if (val === 0) { return res + str.substr(i + 1); } } return res; }
[ "function", "getBinaryCase", "(", "str", ",", "val", ")", "{", "let", "res", "=", "''", ";", "for", "(", "let", "i", "=", "0", ";", "i", "<", "str", ".", "length", ";", "i", "++", ")", "{", "const", "code", "=", "str", ".", "charCodeAt", "(", "i", ")", ";", "if", "(", "code", ">=", "65", "&&", "code", "<=", "90", ")", "{", "res", "+=", "val", "&", "1", "?", "String", ".", "fromCharCode", "(", "code", "+", "32", ")", ":", "String", ".", "fromCharCode", "(", "code", ")", ";", "val", ">>>=", "1", ";", "}", "else", "if", "(", "code", ">=", "97", "&&", "code", "<=", "122", ")", "{", "res", "+=", "val", "&", "1", "?", "String", ".", "fromCharCode", "(", "code", "-", "32", ")", ":", "String", ".", "fromCharCode", "(", "code", ")", ";", "val", ">>>=", "1", ";", "}", "else", "{", "res", "+=", "String", ".", "fromCharCode", "(", "code", ")", ";", "}", "if", "(", "val", "===", "0", ")", "{", "return", "res", "+", "str", ".", "substr", "(", "i", "+", "1", ")", ";", "}", "}", "return", "res", ";", "}" ]
A performance improved method for acquiring the binary case, provided by Blake Embrey with very minor modification by James Speirs. @author Blake Embrey | https://github.com/blakeembrey @author James Speirs | https://github.com/gi60s @param {string} str @param {number} val @returns {string}
[ "A", "performance", "improved", "method", "for", "acquiring", "the", "binary", "case", "provided", "by", "Blake", "Embrey", "with", "very", "minor", "modification", "by", "James", "Speirs", "." ]
a53af5c542b936d6c1329895dd9b93556024d132
https://github.com/Gi60s/binary-case/blob/a53af5c542b936d6c1329895dd9b93556024d132/index.js#L86-L108
train
feedhenry/fh-mbaas-express
lib/mbaas.js
resolvePermission
function resolvePermission(params) { var dbPermissions = mBaaS.permission_map.db; if (params.act && dbPermissions && dbPermissions[params.act]) { params.requestedPermission = dbPermissions[params.act].requires; } }
javascript
function resolvePermission(params) { var dbPermissions = mBaaS.permission_map.db; if (params.act && dbPermissions && dbPermissions[params.act]) { params.requestedPermission = dbPermissions[params.act].requires; } }
[ "function", "resolvePermission", "(", "params", ")", "{", "var", "dbPermissions", "=", "mBaaS", ".", "permission_map", ".", "db", ";", "if", "(", "params", ".", "act", "&&", "dbPermissions", "&&", "dbPermissions", "[", "params", ".", "act", "]", ")", "{", "params", ".", "requestedPermission", "=", "dbPermissions", "[", "params", ".", "act", "]", ".", "requires", ";", "}", "}" ]
DB actions are bound to specific permissions. For example the `list` action requires only read permissions while `update` requires write. Those permissions are configured in the `permission-map` of fh-db. If the given action has a permission set we will add that to the params, otherwise we ignore it. @param params Request parameter object
[ "DB", "actions", "are", "bound", "to", "specific", "permissions", ".", "For", "example", "the", "list", "action", "requires", "only", "read", "permissions", "while", "update", "requires", "write", ".", "Those", "permissions", "are", "configured", "in", "the", "permission", "-", "map", "of", "fh", "-", "db", ".", "If", "the", "given", "action", "has", "a", "permission", "set", "we", "will", "add", "that", "to", "the", "params", "otherwise", "we", "ignore", "it", "." ]
381c2a5842b49a4cbc4519d55b9a3c870b364d3c
https://github.com/feedhenry/fh-mbaas-express/blob/381c2a5842b49a4cbc4519d55b9a3c870b364d3c/lib/mbaas.js#L39-L44
train
passabilities/backrest
lib/routing/buildRoutes.js
getFilterMethods
function getFilterMethods(type, controller, action) { // Get all filters for the action. let filters = getFilters(type, controller, action) // Get filter method names to be skipped. type = `skip${type[0].toUpperCase() + type.slice(1)}` let skipFilterMethods = _.map(getFilters(type, controller, action), 'action') // Remove filters that should be skipped. filters = _.filter(filters, f => { for(let method of skipFilterMethods) if(method === f.action) return false return true }) // Return final list of filter methods. return _.map(filters, f => { let { action } = f action = typeof action === 'string' ? controller[action] : action return action.bind(controller) }) }
javascript
function getFilterMethods(type, controller, action) { // Get all filters for the action. let filters = getFilters(type, controller, action) // Get filter method names to be skipped. type = `skip${type[0].toUpperCase() + type.slice(1)}` let skipFilterMethods = _.map(getFilters(type, controller, action), 'action') // Remove filters that should be skipped. filters = _.filter(filters, f => { for(let method of skipFilterMethods) if(method === f.action) return false return true }) // Return final list of filter methods. return _.map(filters, f => { let { action } = f action = typeof action === 'string' ? controller[action] : action return action.bind(controller) }) }
[ "function", "getFilterMethods", "(", "type", ",", "controller", ",", "action", ")", "{", "let", "filters", "=", "getFilters", "(", "type", ",", "controller", ",", "action", ")", "type", "=", "`", "${", "type", "[", "0", "]", ".", "toUpperCase", "(", ")", "+", "type", ".", "slice", "(", "1", ")", "}", "`", "let", "skipFilterMethods", "=", "_", ".", "map", "(", "getFilters", "(", "type", ",", "controller", ",", "action", ")", ",", "'action'", ")", "filters", "=", "_", ".", "filter", "(", "filters", ",", "f", "=>", "{", "for", "(", "let", "method", "of", "skipFilterMethods", ")", "if", "(", "method", "===", "f", ".", "action", ")", "return", "false", "return", "true", "}", ")", "return", "_", ".", "map", "(", "filters", ",", "f", "=>", "{", "let", "{", "action", "}", "=", "f", "action", "=", "typeof", "action", "===", "'string'", "?", "controller", "[", "action", "]", ":", "action", "return", "action", ".", "bind", "(", "controller", ")", "}", ")", "}" ]
Get list of filter methods to be applied to a specific action.
[ "Get", "list", "of", "filter", "methods", "to", "be", "applied", "to", "a", "specific", "action", "." ]
d44d417f199c4199a0f440b5c56ced19248de27a
https://github.com/passabilities/backrest/blob/d44d417f199c4199a0f440b5c56ced19248de27a/lib/routing/buildRoutes.js#L153-L174
train
passabilities/backrest
lib/routing/buildRoutes.js
getFilters
function getFilters(type, controller, action) { // User can set 'only' and 'except' rules on filters to be used on one // or many action methods. let useOptions = { only: true, except: false } // Only return action filter methods that apply. return _.filter(controller[`__${type}Filters`], filter => { // An action must be defined in each filter. if(!('action' in filter) || !filter.action) throw new Error(`No action defined in filter for [${controller.constructor.name}.${type}: ${JSON.stringify(filter)}].`) // Filter cannot contain both options. let containsBoth = _.every(_.keys(useOptions), o => o in filter) if(containsBoth) throw new Error(`${type[0].toUpperCase() + type.slice(1)} filter cannot have both \'only\' and \'except\' keys.`) let option = _.first(_.intersection(_.keys(useOptions), _.keys(filter))) // If no option is defined, use for all actions. if(!option) return true let useActions, use = useOptions[option] useActions = typeof (useActions = filter[option]) === 'string' ? [useActions] : useActions // Determine if filter can be used for this action. for(let ua of useActions) if(ua === action) return use return !use }) }
javascript
function getFilters(type, controller, action) { // User can set 'only' and 'except' rules on filters to be used on one // or many action methods. let useOptions = { only: true, except: false } // Only return action filter methods that apply. return _.filter(controller[`__${type}Filters`], filter => { // An action must be defined in each filter. if(!('action' in filter) || !filter.action) throw new Error(`No action defined in filter for [${controller.constructor.name}.${type}: ${JSON.stringify(filter)}].`) // Filter cannot contain both options. let containsBoth = _.every(_.keys(useOptions), o => o in filter) if(containsBoth) throw new Error(`${type[0].toUpperCase() + type.slice(1)} filter cannot have both \'only\' and \'except\' keys.`) let option = _.first(_.intersection(_.keys(useOptions), _.keys(filter))) // If no option is defined, use for all actions. if(!option) return true let useActions, use = useOptions[option] useActions = typeof (useActions = filter[option]) === 'string' ? [useActions] : useActions // Determine if filter can be used for this action. for(let ua of useActions) if(ua === action) return use return !use }) }
[ "function", "getFilters", "(", "type", ",", "controller", ",", "action", ")", "{", "let", "useOptions", "=", "{", "only", ":", "true", ",", "except", ":", "false", "}", "return", "_", ".", "filter", "(", "controller", "[", "`", "${", "type", "}", "`", "]", ",", "filter", "=>", "{", "if", "(", "!", "(", "'action'", "in", "filter", ")", "||", "!", "filter", ".", "action", ")", "throw", "new", "Error", "(", "`", "${", "controller", ".", "constructor", ".", "name", "}", "${", "type", "}", "${", "JSON", ".", "stringify", "(", "filter", ")", "}", "`", ")", "let", "containsBoth", "=", "_", ".", "every", "(", "_", ".", "keys", "(", "useOptions", ")", ",", "o", "=>", "o", "in", "filter", ")", "if", "(", "containsBoth", ")", "throw", "new", "Error", "(", "`", "${", "type", "[", "0", "]", ".", "toUpperCase", "(", ")", "+", "type", ".", "slice", "(", "1", ")", "}", "\\'", "\\'", "\\'", "\\'", "`", ")", "let", "option", "=", "_", ".", "first", "(", "_", ".", "intersection", "(", "_", ".", "keys", "(", "useOptions", ")", ",", "_", ".", "keys", "(", "filter", ")", ")", ")", "if", "(", "!", "option", ")", "return", "true", "let", "useActions", ",", "use", "=", "useOptions", "[", "option", "]", "useActions", "=", "typeof", "(", "useActions", "=", "filter", "[", "option", "]", ")", "===", "'string'", "?", "[", "useActions", "]", ":", "useActions", "for", "(", "let", "ua", "of", "useActions", ")", "if", "(", "ua", "===", "action", ")", "return", "use", "return", "!", "use", "}", ")", "}" ]
Get list of filters based on the type name to be applied to a specific action.
[ "Get", "list", "of", "filters", "based", "on", "the", "type", "name", "to", "be", "applied", "to", "a", "specific", "action", "." ]
d44d417f199c4199a0f440b5c56ced19248de27a
https://github.com/passabilities/backrest/blob/d44d417f199c4199a0f440b5c56ced19248de27a/lib/routing/buildRoutes.js#L177-L207
train
tunnckoCoreLabs/charlike
src/index.js
charlike
async function charlike(settings = {}) { const proj = settings.project; if (!proj || (proj && typeof proj !== 'object')) { throw new TypeError('expect `settings.project` to be an object'); } const options = await makeDefaults(settings); const { project, templates } = options; const cfgDir = path.join(os.homedir(), '.config', 'charlike'); const tplDir = path.join(cfgDir, 'templates'); const templatesDir = templates ? path.resolve(templates) : null; if (templatesDir && fs.existsSync(templatesDir)) { project.templates = templatesDir; } else if (fs.existsSync(cfgDir) && fs.existsSync(tplDir)) { project.templates = tplDir; } else { project.templates = path.join(path.dirname(__dirname), 'templates'); } if (!fs.existsSync(project.templates)) { throw new Error(`source templates folder not exist: ${project.templates}`); } const locals = objectAssign({}, options.locals, { project }); const stream = fastGlob.stream('**/*', { cwd: project.templates, ignore: arrayify(null), }); return new Promise((resolve, reject) => { stream.on('error', reject); stream.on('end', () => { // Note: Seems to be called before really write to the optionsination directory. // Stream are still fucking shit even in Node v10. // Feels like nothing happend since v0.10. // For proof, `process.exit` from inside the `.then` in the CLI, // it will end/close the program before even create the options folder. // One more proof: put one console.log in stream.on('data') // and you will see that it still outputs even after calling the resolve() resolve({ locals, project, dest: options.dest, options }); }); stream.on('data', async (filepath) => { try { const tplFilepath = path.join(project.templates, filepath); const { body } = await jstransformer.renderFileAsync( tplFilepath, { engine: options.engine }, locals, ); const newFilepath = path .join(options.dest, filepath) .replace('_circleci', '.circleci'); const basename = path .basename(newFilepath) .replace(/^__/, '') .replace(/^\$/, '') .replace(/^_/, '.'); const fp = path.join(path.dirname(newFilepath), basename); const fpDirname = path.dirname(fp); if (!fs.existsSync(fpDirname)) { await util.promisify(fs.mkdir)(fpDirname); } await util.promisify(fs.writeFile)(fp, body); } catch (err) { reject(err); } }); }); }
javascript
async function charlike(settings = {}) { const proj = settings.project; if (!proj || (proj && typeof proj !== 'object')) { throw new TypeError('expect `settings.project` to be an object'); } const options = await makeDefaults(settings); const { project, templates } = options; const cfgDir = path.join(os.homedir(), '.config', 'charlike'); const tplDir = path.join(cfgDir, 'templates'); const templatesDir = templates ? path.resolve(templates) : null; if (templatesDir && fs.existsSync(templatesDir)) { project.templates = templatesDir; } else if (fs.existsSync(cfgDir) && fs.existsSync(tplDir)) { project.templates = tplDir; } else { project.templates = path.join(path.dirname(__dirname), 'templates'); } if (!fs.existsSync(project.templates)) { throw new Error(`source templates folder not exist: ${project.templates}`); } const locals = objectAssign({}, options.locals, { project }); const stream = fastGlob.stream('**/*', { cwd: project.templates, ignore: arrayify(null), }); return new Promise((resolve, reject) => { stream.on('error', reject); stream.on('end', () => { // Note: Seems to be called before really write to the optionsination directory. // Stream are still fucking shit even in Node v10. // Feels like nothing happend since v0.10. // For proof, `process.exit` from inside the `.then` in the CLI, // it will end/close the program before even create the options folder. // One more proof: put one console.log in stream.on('data') // and you will see that it still outputs even after calling the resolve() resolve({ locals, project, dest: options.dest, options }); }); stream.on('data', async (filepath) => { try { const tplFilepath = path.join(project.templates, filepath); const { body } = await jstransformer.renderFileAsync( tplFilepath, { engine: options.engine }, locals, ); const newFilepath = path .join(options.dest, filepath) .replace('_circleci', '.circleci'); const basename = path .basename(newFilepath) .replace(/^__/, '') .replace(/^\$/, '') .replace(/^_/, '.'); const fp = path.join(path.dirname(newFilepath), basename); const fpDirname = path.dirname(fp); if (!fs.existsSync(fpDirname)) { await util.promisify(fs.mkdir)(fpDirname); } await util.promisify(fs.writeFile)(fp, body); } catch (err) { reject(err); } }); }); }
[ "async", "function", "charlike", "(", "settings", "=", "{", "}", ")", "{", "const", "proj", "=", "settings", ".", "project", ";", "if", "(", "!", "proj", "||", "(", "proj", "&&", "typeof", "proj", "!==", "'object'", ")", ")", "{", "throw", "new", "TypeError", "(", "'expect `settings.project` to be an object'", ")", ";", "}", "const", "options", "=", "await", "makeDefaults", "(", "settings", ")", ";", "const", "{", "project", ",", "templates", "}", "=", "options", ";", "const", "cfgDir", "=", "path", ".", "join", "(", "os", ".", "homedir", "(", ")", ",", "'.config'", ",", "'charlike'", ")", ";", "const", "tplDir", "=", "path", ".", "join", "(", "cfgDir", ",", "'templates'", ")", ";", "const", "templatesDir", "=", "templates", "?", "path", ".", "resolve", "(", "templates", ")", ":", "null", ";", "if", "(", "templatesDir", "&&", "fs", ".", "existsSync", "(", "templatesDir", ")", ")", "{", "project", ".", "templates", "=", "templatesDir", ";", "}", "else", "if", "(", "fs", ".", "existsSync", "(", "cfgDir", ")", "&&", "fs", ".", "existsSync", "(", "tplDir", ")", ")", "{", "project", ".", "templates", "=", "tplDir", ";", "}", "else", "{", "project", ".", "templates", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "__dirname", ")", ",", "'templates'", ")", ";", "}", "if", "(", "!", "fs", ".", "existsSync", "(", "project", ".", "templates", ")", ")", "{", "throw", "new", "Error", "(", "`", "${", "project", ".", "templates", "}", "`", ")", ";", "}", "const", "locals", "=", "objectAssign", "(", "{", "}", ",", "options", ".", "locals", ",", "{", "project", "}", ")", ";", "const", "stream", "=", "fastGlob", ".", "stream", "(", "'**/*'", ",", "{", "cwd", ":", "project", ".", "templates", ",", "ignore", ":", "arrayify", "(", "null", ")", ",", "}", ")", ";", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "stream", ".", "on", "(", "'error'", ",", "reject", ")", ";", "stream", ".", "on", "(", "'end'", ",", "(", ")", "=>", "{", "resolve", "(", "{", "locals", ",", "project", ",", "dest", ":", "options", ".", "dest", ",", "options", "}", ")", ";", "}", ")", ";", "stream", ".", "on", "(", "'data'", ",", "async", "(", "filepath", ")", "=>", "{", "try", "{", "const", "tplFilepath", "=", "path", ".", "join", "(", "project", ".", "templates", ",", "filepath", ")", ";", "const", "{", "body", "}", "=", "await", "jstransformer", ".", "renderFileAsync", "(", "tplFilepath", ",", "{", "engine", ":", "options", ".", "engine", "}", ",", "locals", ",", ")", ";", "const", "newFilepath", "=", "path", ".", "join", "(", "options", ".", "dest", ",", "filepath", ")", ".", "replace", "(", "'_circleci'", ",", "'.circleci'", ")", ";", "const", "basename", "=", "path", ".", "basename", "(", "newFilepath", ")", ".", "replace", "(", "/", "^__", "/", ",", "''", ")", ".", "replace", "(", "/", "^\\$", "/", ",", "''", ")", ".", "replace", "(", "/", "^_", "/", ",", "'.'", ")", ";", "const", "fp", "=", "path", ".", "join", "(", "path", ".", "dirname", "(", "newFilepath", ")", ",", "basename", ")", ";", "const", "fpDirname", "=", "path", ".", "dirname", "(", "fp", ")", ";", "if", "(", "!", "fs", ".", "existsSync", "(", "fpDirname", ")", ")", "{", "await", "util", ".", "promisify", "(", "fs", ".", "mkdir", ")", "(", "fpDirname", ")", ";", "}", "await", "util", ".", "promisify", "(", "fs", ".", "writeFile", ")", "(", "fp", ",", "body", ")", ";", "}", "catch", "(", "err", ")", "{", "reject", "(", "err", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Generates a complete project using a set of templates. You can define what _"templates"_ files to be used by passing `settings.templates`, by default it uses [./templates](./templates) folder from this repository root. You can define project metadata in `settings.project` object, which should contain `name`, `description` properties and also can contain `repo` and `dest`. By default the destination folder is dynamically built from `settings.cwd` and `settings.project.name`, but this behavior can be changed. If `settings.project.repo` is passed, then it will be used instead of the `settings.project.name`. To control the context of the templates, pass `settings.locals`. The default set of locals includes `version` string and `project`, `author` and `license` objects. @example import charlike from 'charlike'; const settings = { project: { name: 'foobar', description: 'Awesome project' }, cwd: '/home/charlike/code', templates: '/home/charlike/config/.jsproject', locals: { foo: 'bar', // some helper toUpperCase: (val) => val.toUpperCase(), }, }; // the `dest` will be `/home/charlike/code/foobar` charlike(settings) .then(({ dest }) => console.log(`Project generated to ${dest}`)) .catch((err) => console.error(`Error occures: ${err.message}; Sorry!`)); @name charlike @param {object} settings the only required is `project` which should be an object @param {object} settings.cwd working directory to create project to, defaults to `process.cwd()` @param {object} settings.project should contain `name`, `description`, `repo` and `dest` @param {object} settings.locals to pass more context to template files @param {string} settings.engine for different template engine to be used in template files, default is `lodash` @return {Promise<object>} if successful, will resolve to object like `{ locals, project, dest, options }` @public
[ "Generates", "a", "complete", "project", "using", "a", "set", "of", "templates", "." ]
a1278ff083b76f9e14f14ca25e6b5a467c9e20fa
https://github.com/tunnckoCoreLabs/charlike/blob/a1278ff083b76f9e14f14ca25e6b5a467c9e20fa/src/index.js#L62-L139
train
Rhinostone/gina
core/router.js
function(request, params, route) { var uRe = params.url.split(/\//) , uRo = route.split(/\//) , maxLen = uRo.length , score = 0 , r = {} , i = 0; //attaching routing description for this request request.routing = params; // can be retried in controller with: req.routing if (uRe.length === uRo.length) { for (; i<maxLen; ++i) { if (uRe[i] === uRo[i]) { ++score } else if (score == i && hasParams(uRo[i]) && fitsWithRequirements(request, uRo[i], uRe[i], params)) { ++score } } } r.past = (score === maxLen) ? true : false; r.request = request; return r }
javascript
function(request, params, route) { var uRe = params.url.split(/\//) , uRo = route.split(/\//) , maxLen = uRo.length , score = 0 , r = {} , i = 0; //attaching routing description for this request request.routing = params; // can be retried in controller with: req.routing if (uRe.length === uRo.length) { for (; i<maxLen; ++i) { if (uRe[i] === uRo[i]) { ++score } else if (score == i && hasParams(uRo[i]) && fitsWithRequirements(request, uRo[i], uRe[i], params)) { ++score } } } r.past = (score === maxLen) ? true : false; r.request = request; return r }
[ "function", "(", "request", ",", "params", ",", "route", ")", "{", "var", "uRe", "=", "params", ".", "url", ".", "split", "(", "/", "\\/", "/", ")", ",", "uRo", "=", "route", ".", "split", "(", "/", "\\/", "/", ")", ",", "maxLen", "=", "uRo", ".", "length", ",", "score", "=", "0", ",", "r", "=", "{", "}", ",", "i", "=", "0", ";", "request", ".", "routing", "=", "params", ";", "if", "(", "uRe", ".", "length", "===", "uRo", ".", "length", ")", "{", "for", "(", ";", "i", "<", "maxLen", ";", "++", "i", ")", "{", "if", "(", "uRe", "[", "i", "]", "===", "uRo", "[", "i", "]", ")", "{", "++", "score", "}", "else", "if", "(", "score", "==", "i", "&&", "hasParams", "(", "uRo", "[", "i", "]", ")", "&&", "fitsWithRequirements", "(", "request", ",", "uRo", "[", "i", "]", ",", "uRe", "[", "i", "]", ",", "params", ")", ")", "{", "++", "score", "}", "}", "}", "r", ".", "past", "=", "(", "score", "===", "maxLen", ")", "?", "true", ":", "false", ";", "r", ".", "request", "=", "request", ";", "return", "r", "}" ]
Parse routing for mathcing url @param {object} request @param {object} params @param {string} route @return
[ "Parse", "routing", "for", "mathcing", "url" ]
c6ba13d3255a43734c54880ff12d3a50df53ebea
https://github.com/Rhinostone/gina/blob/c6ba13d3255a43734c54880ff12d3a50df53ebea/core/router.js#L113-L138
train
cshum/ginga
index.js
wrapFn
function wrapFn (gen) { if (!is.function(gen)) throw new Error('Middleware must be a function') if (!is.generator(gen)) return gen // wrap generator with raco var fn = raco.wrap(gen) return function (ctx, next) { fn.call(this, ctx, next) } }
javascript
function wrapFn (gen) { if (!is.function(gen)) throw new Error('Middleware must be a function') if (!is.generator(gen)) return gen // wrap generator with raco var fn = raco.wrap(gen) return function (ctx, next) { fn.call(this, ctx, next) } }
[ "function", "wrapFn", "(", "gen", ")", "{", "if", "(", "!", "is", ".", "function", "(", "gen", ")", ")", "throw", "new", "Error", "(", "'Middleware must be a function'", ")", "if", "(", "!", "is", ".", "generator", "(", "gen", ")", ")", "return", "gen", "var", "fn", "=", "raco", ".", "wrap", "(", "gen", ")", "return", "function", "(", "ctx", ",", "next", ")", "{", "fn", ".", "call", "(", "this", ",", "ctx", ",", "next", ")", "}", "}" ]
wrap ginga middleware function
[ "wrap", "ginga", "middleware", "function" ]
6169297b1864d3779f4f09884fd9979a59052fb5
https://github.com/cshum/ginga/blob/6169297b1864d3779f4f09884fd9979a59052fb5/index.js#L8-L17
train
cshum/ginga
index.js
use
function use () { // init hooks if (!this.hasOwnProperty('_hooks')) { this._hooks = {} } var args = Array.prototype.slice.call(arguments) var i, j, l, m var name = null if (is.array(args[0])) { // use(['a','b','c'], ...) var arr = args.shift() for (i = 0, l = arr.length; i < l; i++) { use.apply(this, [arr[i]].concat(args)) } return this } else if (is.object(args[0]) && args[0]._hooks) { // use(ginga) var key // concat hooks for (key in args[0]._hooks) { use.call(this, key, args[0]._hooks[key]) } return this } // method name if (is.string(args[0])) name = args.shift() if (!name) throw new Error('Method name is not defined.') if (!this._hooks[name]) this._hooks[name] = [] for (i = 0, l = args.length; i < l; i++) { if (is.function(args[i])) { this._hooks[name].push(wrapFn(args[i])) } else if (is.array(args[i])) { // use('a', [fn1, fn2, fn3]) for (j = 0, m = args[i].length; j < m; j++) { use.call(this, name, args[i][j]) } return this } else { throw new Error('Middleware must be a function') } } return this }
javascript
function use () { // init hooks if (!this.hasOwnProperty('_hooks')) { this._hooks = {} } var args = Array.prototype.slice.call(arguments) var i, j, l, m var name = null if (is.array(args[0])) { // use(['a','b','c'], ...) var arr = args.shift() for (i = 0, l = arr.length; i < l; i++) { use.apply(this, [arr[i]].concat(args)) } return this } else if (is.object(args[0]) && args[0]._hooks) { // use(ginga) var key // concat hooks for (key in args[0]._hooks) { use.call(this, key, args[0]._hooks[key]) } return this } // method name if (is.string(args[0])) name = args.shift() if (!name) throw new Error('Method name is not defined.') if (!this._hooks[name]) this._hooks[name] = [] for (i = 0, l = args.length; i < l; i++) { if (is.function(args[i])) { this._hooks[name].push(wrapFn(args[i])) } else if (is.array(args[i])) { // use('a', [fn1, fn2, fn3]) for (j = 0, m = args[i].length; j < m; j++) { use.call(this, name, args[i][j]) } return this } else { throw new Error('Middleware must be a function') } } return this }
[ "function", "use", "(", ")", "{", "if", "(", "!", "this", ".", "hasOwnProperty", "(", "'_hooks'", ")", ")", "{", "this", ".", "_hooks", "=", "{", "}", "}", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", "var", "i", ",", "j", ",", "l", ",", "m", "var", "name", "=", "null", "if", "(", "is", ".", "array", "(", "args", "[", "0", "]", ")", ")", "{", "var", "arr", "=", "args", ".", "shift", "(", ")", "for", "(", "i", "=", "0", ",", "l", "=", "arr", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "use", ".", "apply", "(", "this", ",", "[", "arr", "[", "i", "]", "]", ".", "concat", "(", "args", ")", ")", "}", "return", "this", "}", "else", "if", "(", "is", ".", "object", "(", "args", "[", "0", "]", ")", "&&", "args", "[", "0", "]", ".", "_hooks", ")", "{", "var", "key", "for", "(", "key", "in", "args", "[", "0", "]", ".", "_hooks", ")", "{", "use", ".", "call", "(", "this", ",", "key", ",", "args", "[", "0", "]", ".", "_hooks", "[", "key", "]", ")", "}", "return", "this", "}", "if", "(", "is", ".", "string", "(", "args", "[", "0", "]", ")", ")", "name", "=", "args", ".", "shift", "(", ")", "if", "(", "!", "name", ")", "throw", "new", "Error", "(", "'Method name is not defined.'", ")", "if", "(", "!", "this", ".", "_hooks", "[", "name", "]", ")", "this", ".", "_hooks", "[", "name", "]", "=", "[", "]", "for", "(", "i", "=", "0", ",", "l", "=", "args", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "if", "(", "is", ".", "function", "(", "args", "[", "i", "]", ")", ")", "{", "this", ".", "_hooks", "[", "name", "]", ".", "push", "(", "wrapFn", "(", "args", "[", "i", "]", ")", ")", "}", "else", "if", "(", "is", ".", "array", "(", "args", "[", "i", "]", ")", ")", "{", "for", "(", "j", "=", "0", ",", "m", "=", "args", "[", "i", "]", ".", "length", ";", "j", "<", "m", ";", "j", "++", ")", "{", "use", ".", "call", "(", "this", ",", "name", ",", "args", "[", "i", "]", "[", "j", "]", ")", "}", "return", "this", "}", "else", "{", "throw", "new", "Error", "(", "'Middleware must be a function'", ")", "}", "}", "return", "this", "}" ]
ginga use method
[ "ginga", "use", "method" ]
6169297b1864d3779f4f09884fd9979a59052fb5
https://github.com/cshum/ginga/blob/6169297b1864d3779f4f09884fd9979a59052fb5/index.js#L20-L66
train
cshum/ginga
index.js
define
function define () { var args = Array.prototype.slice.call(arguments) var i, l var name = args.shift() if (is.array(name)) { name = args.shift() for (i = 0, l = name.length; i < l; i++) { define.apply(this, [name[i]].concat(args)) } return this } if (!is.string(name)) throw new Error('Method name is not defined') var invoke = is.function(args[args.length - 1]) ? wrapFn(args.pop()) : null var pre = args.map(wrapFn) // define scope method this[name] = function () { var args = Array.prototype.slice.call(arguments) var self = this var callback if (is.function(args[args.length - 1])) callback = args.pop() // init pipeline var pipe = [] var obj = this // prototype chain while (obj) { if (obj.hasOwnProperty('_hooks') && obj._hooks[name]) { pipe.unshift(obj._hooks[name]) } obj = Object.getPrototypeOf(obj) } // pre middlewares pipe.unshift(pre) // invoke middleware if (invoke) pipe.push(invoke) pipe = flatten(pipe) // context object and next triggerer var ctx = new EventEmitter() ctx.method = name ctx.args = args var index = 0 var size = pipe.length function next (err, res) { if (err || index === size) { var args = Array.prototype.slice.call(arguments) // callback when err or end of pipeline if (callback) callback.apply(self, args) args.unshift('end') ctx.emit.apply(ctx, args) } else if (index < size) { var fn = pipe[index] index++ var val = fn.call(self, ctx, next) if (is.promise(val)) { val.then(function (res) { next(null, res) }, function (err) { next(err || new Error()) }) } else if (fn.length < 2) { // args without next() & not promise, sync func next(null, val) } } } if (callback) { next() } else { // use promise if no callback return new Promise(function (resolve, reject) { callback = function (err, result) { if (err) return reject(err) resolve(result) } next() }) } } return this }
javascript
function define () { var args = Array.prototype.slice.call(arguments) var i, l var name = args.shift() if (is.array(name)) { name = args.shift() for (i = 0, l = name.length; i < l; i++) { define.apply(this, [name[i]].concat(args)) } return this } if (!is.string(name)) throw new Error('Method name is not defined') var invoke = is.function(args[args.length - 1]) ? wrapFn(args.pop()) : null var pre = args.map(wrapFn) // define scope method this[name] = function () { var args = Array.prototype.slice.call(arguments) var self = this var callback if (is.function(args[args.length - 1])) callback = args.pop() // init pipeline var pipe = [] var obj = this // prototype chain while (obj) { if (obj.hasOwnProperty('_hooks') && obj._hooks[name]) { pipe.unshift(obj._hooks[name]) } obj = Object.getPrototypeOf(obj) } // pre middlewares pipe.unshift(pre) // invoke middleware if (invoke) pipe.push(invoke) pipe = flatten(pipe) // context object and next triggerer var ctx = new EventEmitter() ctx.method = name ctx.args = args var index = 0 var size = pipe.length function next (err, res) { if (err || index === size) { var args = Array.prototype.slice.call(arguments) // callback when err or end of pipeline if (callback) callback.apply(self, args) args.unshift('end') ctx.emit.apply(ctx, args) } else if (index < size) { var fn = pipe[index] index++ var val = fn.call(self, ctx, next) if (is.promise(val)) { val.then(function (res) { next(null, res) }, function (err) { next(err || new Error()) }) } else if (fn.length < 2) { // args without next() & not promise, sync func next(null, val) } } } if (callback) { next() } else { // use promise if no callback return new Promise(function (resolve, reject) { callback = function (err, result) { if (err) return reject(err) resolve(result) } next() }) } } return this }
[ "function", "define", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", "var", "i", ",", "l", "var", "name", "=", "args", ".", "shift", "(", ")", "if", "(", "is", ".", "array", "(", "name", ")", ")", "{", "name", "=", "args", ".", "shift", "(", ")", "for", "(", "i", "=", "0", ",", "l", "=", "name", ".", "length", ";", "i", "<", "l", ";", "i", "++", ")", "{", "define", ".", "apply", "(", "this", ",", "[", "name", "[", "i", "]", "]", ".", "concat", "(", "args", ")", ")", "}", "return", "this", "}", "if", "(", "!", "is", ".", "string", "(", "name", ")", ")", "throw", "new", "Error", "(", "'Method name is not defined'", ")", "var", "invoke", "=", "is", ".", "function", "(", "args", "[", "args", ".", "length", "-", "1", "]", ")", "?", "wrapFn", "(", "args", ".", "pop", "(", ")", ")", ":", "null", "var", "pre", "=", "args", ".", "map", "(", "wrapFn", ")", "this", "[", "name", "]", "=", "function", "(", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", "var", "self", "=", "this", "var", "callback", "if", "(", "is", ".", "function", "(", "args", "[", "args", ".", "length", "-", "1", "]", ")", ")", "callback", "=", "args", ".", "pop", "(", ")", "var", "pipe", "=", "[", "]", "var", "obj", "=", "this", "while", "(", "obj", ")", "{", "if", "(", "obj", ".", "hasOwnProperty", "(", "'_hooks'", ")", "&&", "obj", ".", "_hooks", "[", "name", "]", ")", "{", "pipe", ".", "unshift", "(", "obj", ".", "_hooks", "[", "name", "]", ")", "}", "obj", "=", "Object", ".", "getPrototypeOf", "(", "obj", ")", "}", "pipe", ".", "unshift", "(", "pre", ")", "if", "(", "invoke", ")", "pipe", ".", "push", "(", "invoke", ")", "pipe", "=", "flatten", "(", "pipe", ")", "var", "ctx", "=", "new", "EventEmitter", "(", ")", "ctx", ".", "method", "=", "name", "ctx", ".", "args", "=", "args", "var", "index", "=", "0", "var", "size", "=", "pipe", ".", "length", "function", "next", "(", "err", ",", "res", ")", "{", "if", "(", "err", "||", "index", "===", "size", ")", "{", "var", "args", "=", "Array", ".", "prototype", ".", "slice", ".", "call", "(", "arguments", ")", "if", "(", "callback", ")", "callback", ".", "apply", "(", "self", ",", "args", ")", "args", ".", "unshift", "(", "'end'", ")", "ctx", ".", "emit", ".", "apply", "(", "ctx", ",", "args", ")", "}", "else", "if", "(", "index", "<", "size", ")", "{", "var", "fn", "=", "pipe", "[", "index", "]", "index", "++", "var", "val", "=", "fn", ".", "call", "(", "self", ",", "ctx", ",", "next", ")", "if", "(", "is", ".", "promise", "(", "val", ")", ")", "{", "val", ".", "then", "(", "function", "(", "res", ")", "{", "next", "(", "null", ",", "res", ")", "}", ",", "function", "(", "err", ")", "{", "next", "(", "err", "||", "new", "Error", "(", ")", ")", "}", ")", "}", "else", "if", "(", "fn", ".", "length", "<", "2", ")", "{", "next", "(", "null", ",", "val", ")", "}", "}", "}", "if", "(", "callback", ")", "{", "next", "(", ")", "}", "else", "{", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "callback", "=", "function", "(", "err", ",", "result", ")", "{", "if", "(", "err", ")", "return", "reject", "(", "err", ")", "resolve", "(", "result", ")", "}", "next", "(", ")", "}", ")", "}", "}", "return", "this", "}" ]
ginga define method
[ "ginga", "define", "method" ]
6169297b1864d3779f4f09884fd9979a59052fb5
https://github.com/cshum/ginga/blob/6169297b1864d3779f4f09884fd9979a59052fb5/index.js#L69-L159
train
Jack12816/greppy
lib/app/worker.js
function(callback) { self.configureDatabases(function(err) { if (err) { process.exit(111); return; } self.configureApplicationStack( app, server, callback ); }); }
javascript
function(callback) { self.configureDatabases(function(err) { if (err) { process.exit(111); return; } self.configureApplicationStack( app, server, callback ); }); }
[ "function", "(", "callback", ")", "{", "self", ".", "configureDatabases", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "process", ".", "exit", "(", "111", ")", ";", "return", ";", "}", "self", ".", "configureApplicationStack", "(", "app", ",", "server", ",", "callback", ")", ";", "}", ")", ";", "}" ]
Configure database connections
[ "Configure", "database", "connections" ]
ede2157b90c207896781cc41fb9ea115e83951dd
https://github.com/Jack12816/greppy/blob/ede2157b90c207896781cc41fb9ea115e83951dd/lib/app/worker.js#L454-L466
train
Kronos-Integration/kronos-interceptor-object-data-processor-row
lib/recordCheck/data-check-common.js
function (fieldDefinition, fieldName) { const severity = propertyHelper.getSeverity(fieldDefinition, undefined, 'mandatory'); const isMandatoy = propertyHelper.getProperty(fieldDefinition, undefined, 'mandatory'); // const severity = fieldDefinition.severity; // const isMandatoy = fieldDefinition.mandatory; if (isMandatoy === true) { /** * Just check if for mandatory fields the value is given * @param content the content hash to be validated. */ return function (content) { // get the value from the content hash const valueToCheck = content[fieldName]; // If the value is defined, we need to check it if (valueToCheck === undefined || valueToCheck === null) { return { errorCode: 'MANDATORY_VALUE_MISSING', severity: severity, fieldName: fieldName }; } }; } }
javascript
function (fieldDefinition, fieldName) { const severity = propertyHelper.getSeverity(fieldDefinition, undefined, 'mandatory'); const isMandatoy = propertyHelper.getProperty(fieldDefinition, undefined, 'mandatory'); // const severity = fieldDefinition.severity; // const isMandatoy = fieldDefinition.mandatory; if (isMandatoy === true) { /** * Just check if for mandatory fields the value is given * @param content the content hash to be validated. */ return function (content) { // get the value from the content hash const valueToCheck = content[fieldName]; // If the value is defined, we need to check it if (valueToCheck === undefined || valueToCheck === null) { return { errorCode: 'MANDATORY_VALUE_MISSING', severity: severity, fieldName: fieldName }; } }; } }
[ "function", "(", "fieldDefinition", ",", "fieldName", ")", "{", "const", "severity", "=", "propertyHelper", ".", "getSeverity", "(", "fieldDefinition", ",", "undefined", ",", "'mandatory'", ")", ";", "const", "isMandatoy", "=", "propertyHelper", ".", "getProperty", "(", "fieldDefinition", ",", "undefined", ",", "'mandatory'", ")", ";", "if", "(", "isMandatoy", "===", "true", ")", "{", "return", "function", "(", "content", ")", "{", "const", "valueToCheck", "=", "content", "[", "fieldName", "]", ";", "if", "(", "valueToCheck", "===", "undefined", "||", "valueToCheck", "===", "null", ")", "{", "return", "{", "errorCode", ":", "'MANDATORY_VALUE_MISSING'", ",", "severity", ":", "severity", ",", "fieldName", ":", "fieldName", "}", ";", "}", "}", ";", "}", "}" ]
Creates the checks which are common to each file type @param fieldDefinition The field_definition for this field. @param fieldName The name of the current field
[ "Creates", "the", "checks", "which", "are", "common", "to", "each", "file", "type" ]
678a59b84dab4a9082377c90849a0d62d97a1ea4
https://github.com/Kronos-Integration/kronos-interceptor-object-data-processor-row/blob/678a59b84dab4a9082377c90849a0d62d97a1ea4/lib/recordCheck/data-check-common.js#L14-L41
train
vimlet/vimlet-commons
docs/release/framework/vcomet/vcomet.js
function (evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. if ( evt.type === "load" || readyRegExp.test((evt.currentTarget || evt.srcElement).readyState) ) { //Reset interactive script so a script node is not held onto for //to long. interactiveScript = null; //Pull out the name of the module and the context. var data = getScriptData(evt); context.completeLoad(data.id); } }
javascript
function (evt) { //Using currentTarget instead of target for Firefox 2.0's sake. Not //all old browsers will be supported, but this one was easy enough //to support and still makes sense. if ( evt.type === "load" || readyRegExp.test((evt.currentTarget || evt.srcElement).readyState) ) { //Reset interactive script so a script node is not held onto for //to long. interactiveScript = null; //Pull out the name of the module and the context. var data = getScriptData(evt); context.completeLoad(data.id); } }
[ "function", "(", "evt", ")", "{", "if", "(", "evt", ".", "type", "===", "\"load\"", "||", "readyRegExp", ".", "test", "(", "(", "evt", ".", "currentTarget", "||", "evt", ".", "srcElement", ")", ".", "readyState", ")", ")", "{", "interactiveScript", "=", "null", ";", "var", "data", "=", "getScriptData", "(", "evt", ")", ";", "context", ".", "completeLoad", "(", "data", ".", "id", ")", ";", "}", "}" ]
callback for script loads, used to check status of loading. @param {Event} evt the event from the browser for the script that was loaded.
[ "callback", "for", "script", "loads", "used", "to", "check", "status", "of", "loading", "." ]
c2d06dd64637e6729872ef82b40e99b7155b0dea
https://github.com/vimlet/vimlet-commons/blob/c2d06dd64637e6729872ef82b40e99b7155b0dea/docs/release/framework/vcomet/vcomet.js#L2073-L2089
train
vimlet/vimlet-commons
docs/release/framework/vcomet/vcomet.js
function (attrName, oldVal, newVal) { var property = vcomet.util.hyphenToCamelCase(attrName); // The onAttributeChanged callback is triggered whether its observed or as a reflection of a property if (el.__observeAttributes[attrName] || el.__reflectProperties[property]) { vcomet.triggerAllCallbackEvents(el, config, "onAttributeChanged", [attrName, oldVal, newVal]); } // The onPropertyChanged callback is triggered when the attribute has changed and its reflect by a property if (el.__reflectProperties[property]) { el["__" + property] = newVal; vcomet.triggerAllCallbackEvents(el, config, "onPropertyChanged", [property, oldVal, newVal]); } }
javascript
function (attrName, oldVal, newVal) { var property = vcomet.util.hyphenToCamelCase(attrName); // The onAttributeChanged callback is triggered whether its observed or as a reflection of a property if (el.__observeAttributes[attrName] || el.__reflectProperties[property]) { vcomet.triggerAllCallbackEvents(el, config, "onAttributeChanged", [attrName, oldVal, newVal]); } // The onPropertyChanged callback is triggered when the attribute has changed and its reflect by a property if (el.__reflectProperties[property]) { el["__" + property] = newVal; vcomet.triggerAllCallbackEvents(el, config, "onPropertyChanged", [property, oldVal, newVal]); } }
[ "function", "(", "attrName", ",", "oldVal", ",", "newVal", ")", "{", "var", "property", "=", "vcomet", ".", "util", ".", "hyphenToCamelCase", "(", "attrName", ")", ";", "if", "(", "el", ".", "__observeAttributes", "[", "attrName", "]", "||", "el", ".", "__reflectProperties", "[", "property", "]", ")", "{", "vcomet", ".", "triggerAllCallbackEvents", "(", "el", ",", "config", ",", "\"onAttributeChanged\"", ",", "[", "attrName", ",", "oldVal", ",", "newVal", "]", ")", ";", "}", "if", "(", "el", ".", "__reflectProperties", "[", "property", "]", ")", "{", "el", "[", "\"__\"", "+", "property", "]", "=", "newVal", ";", "vcomet", ".", "triggerAllCallbackEvents", "(", "el", ",", "config", ",", "\"onPropertyChanged\"", ",", "[", "property", ",", "oldVal", ",", "newVal", "]", ")", ";", "}", "}" ]
Callback to be triggered when the user calls to setAttribute
[ "Callback", "to", "be", "triggered", "when", "the", "user", "calls", "to", "setAttribute" ]
c2d06dd64637e6729872ef82b40e99b7155b0dea
https://github.com/vimlet/vimlet-commons/blob/c2d06dd64637e6729872ef82b40e99b7155b0dea/docs/release/framework/vcomet/vcomet.js#L4582-L4597
train
datacentricdesign/dcd-model
services/ThingService.js
createAccessPolicy
function createAccessPolicy(thingId) { const thingPolicy = { id: thingId + "-" + thingId + "-cru-policy", effect: "allow", actions: ["dcd:actions:create", "dcd:actions:read", "dcd:actions:update"], subjects: ["dcd:things:" + thingId], resources: [ "dcd:things:" + thingId, "dcd:things:" + thingId + ":properties", "dcd:things:" + thingId + ":properties:<.*>" ] }; logger.debug("Thing policy: " + JSON.stringify(thingPolicy)); return policies.create(thingPolicy); }
javascript
function createAccessPolicy(thingId) { const thingPolicy = { id: thingId + "-" + thingId + "-cru-policy", effect: "allow", actions: ["dcd:actions:create", "dcd:actions:read", "dcd:actions:update"], subjects: ["dcd:things:" + thingId], resources: [ "dcd:things:" + thingId, "dcd:things:" + thingId + ":properties", "dcd:things:" + thingId + ":properties:<.*>" ] }; logger.debug("Thing policy: " + JSON.stringify(thingPolicy)); return policies.create(thingPolicy); }
[ "function", "createAccessPolicy", "(", "thingId", ")", "{", "const", "thingPolicy", "=", "{", "id", ":", "thingId", "+", "\"-\"", "+", "thingId", "+", "\"-cru-policy\"", ",", "effect", ":", "\"allow\"", ",", "actions", ":", "[", "\"dcd:actions:create\"", ",", "\"dcd:actions:read\"", ",", "\"dcd:actions:update\"", "]", ",", "subjects", ":", "[", "\"dcd:things:\"", "+", "thingId", "]", ",", "resources", ":", "[", "\"dcd:things:\"", "+", "thingId", ",", "\"dcd:things:\"", "+", "thingId", "+", "\":properties\"", ",", "\"dcd:things:\"", "+", "thingId", "+", "\":properties:<.*>\"", "]", "}", ";", "logger", ".", "debug", "(", "\"Thing policy: \"", "+", "JSON", ".", "stringify", "(", "thingPolicy", ")", ")", ";", "return", "policies", ".", "create", "(", "thingPolicy", ")", ";", "}" ]
Generate an access policy for a thing. @param thingId @returns {Promise<>}
[ "Generate", "an", "access", "policy", "for", "a", "thing", "." ]
162b724bc965439fcd894cf23101b2f00dd02924
https://github.com/datacentricdesign/dcd-model/blob/162b724bc965439fcd894cf23101b2f00dd02924/services/ThingService.js#L161-L175
train
datacentricdesign/dcd-model
services/ThingService.js
createOwnerAccessPolicy
function createOwnerAccessPolicy(thingId, subject) { const thingOwnerPolicy = { id: thingId + "-" + subject + "-clrud-policy", effect: "allow", actions: [ "dcd:actions:create", "dcd:actions:list", "dcd:actions:read", "dcd:actions:update", "dcd:actions:delete" ], subjects: [subject], resources: [ "dcd:things:" + thingId, "dcd:things:" + thingId + ":properties", "dcd:things:" + thingId + ":properties:<.*>" ] }; return policies.create(thingOwnerPolicy); }
javascript
function createOwnerAccessPolicy(thingId, subject) { const thingOwnerPolicy = { id: thingId + "-" + subject + "-clrud-policy", effect: "allow", actions: [ "dcd:actions:create", "dcd:actions:list", "dcd:actions:read", "dcd:actions:update", "dcd:actions:delete" ], subjects: [subject], resources: [ "dcd:things:" + thingId, "dcd:things:" + thingId + ":properties", "dcd:things:" + thingId + ":properties:<.*>" ] }; return policies.create(thingOwnerPolicy); }
[ "function", "createOwnerAccessPolicy", "(", "thingId", ",", "subject", ")", "{", "const", "thingOwnerPolicy", "=", "{", "id", ":", "thingId", "+", "\"-\"", "+", "subject", "+", "\"-clrud-policy\"", ",", "effect", ":", "\"allow\"", ",", "actions", ":", "[", "\"dcd:actions:create\"", ",", "\"dcd:actions:list\"", ",", "\"dcd:actions:read\"", ",", "\"dcd:actions:update\"", ",", "\"dcd:actions:delete\"", "]", ",", "subjects", ":", "[", "subject", "]", ",", "resources", ":", "[", "\"dcd:things:\"", "+", "thingId", ",", "\"dcd:things:\"", "+", "thingId", "+", "\":properties\"", ",", "\"dcd:things:\"", "+", "thingId", "+", "\":properties:<.*>\"", "]", "}", ";", "return", "policies", ".", "create", "(", "thingOwnerPolicy", ")", ";", "}" ]
Generate an access policy for the owner of a thing. @param thingId @param subject @returns {Promise<>}
[ "Generate", "an", "access", "policy", "for", "the", "owner", "of", "a", "thing", "." ]
162b724bc965439fcd894cf23101b2f00dd02924
https://github.com/datacentricdesign/dcd-model/blob/162b724bc965439fcd894cf23101b2f00dd02924/services/ThingService.js#L183-L202
train
dowjones/distribucache
lib/decorators/PopulateInDecorator.js
PopulateInDecorator
function PopulateInDecorator(cache, config) { BaseDecorator.call(this, cache, config, joi.object().keys({ populateIn: joi.number().integer().min(500).required(), populateInAttempts: joi.number().integer().default(5), pausePopulateIn: joi.number().integer().required(), accessedAtThrottle: joi.number().integer().default(1000) })); this._store = this._getStore(); this._timer = this._store.createTimer(); this._timer.on('error', this._emitError); this._timer.on('timeout', this._onTimeout.bind(this)); this.on('set:after', this.setTimeout.bind(this)); this.on('get:after', throttle(this.setAccessedAt.bind(this), this._config.accessedAtThrottle)); }
javascript
function PopulateInDecorator(cache, config) { BaseDecorator.call(this, cache, config, joi.object().keys({ populateIn: joi.number().integer().min(500).required(), populateInAttempts: joi.number().integer().default(5), pausePopulateIn: joi.number().integer().required(), accessedAtThrottle: joi.number().integer().default(1000) })); this._store = this._getStore(); this._timer = this._store.createTimer(); this._timer.on('error', this._emitError); this._timer.on('timeout', this._onTimeout.bind(this)); this.on('set:after', this.setTimeout.bind(this)); this.on('get:after', throttle(this.setAccessedAt.bind(this), this._config.accessedAtThrottle)); }
[ "function", "PopulateInDecorator", "(", "cache", ",", "config", ")", "{", "BaseDecorator", ".", "call", "(", "this", ",", "cache", ",", "config", ",", "joi", ".", "object", "(", ")", ".", "keys", "(", "{", "populateIn", ":", "joi", ".", "number", "(", ")", ".", "integer", "(", ")", ".", "min", "(", "500", ")", ".", "required", "(", ")", ",", "populateInAttempts", ":", "joi", ".", "number", "(", ")", ".", "integer", "(", ")", ".", "default", "(", "5", ")", ",", "pausePopulateIn", ":", "joi", ".", "number", "(", ")", ".", "integer", "(", ")", ".", "required", "(", ")", ",", "accessedAtThrottle", ":", "joi", ".", "number", "(", ")", ".", "integer", "(", ")", ".", "default", "(", "1000", ")", "}", ")", ")", ";", "this", ".", "_store", "=", "this", ".", "_getStore", "(", ")", ";", "this", ".", "_timer", "=", "this", ".", "_store", ".", "createTimer", "(", ")", ";", "this", ".", "_timer", ".", "on", "(", "'error'", ",", "this", ".", "_emitError", ")", ";", "this", ".", "_timer", ".", "on", "(", "'timeout'", ",", "this", ".", "_onTimeout", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "on", "(", "'set:after'", ",", "this", ".", "setTimeout", ".", "bind", "(", "this", ")", ")", ";", "this", ".", "on", "(", "'get:after'", ",", "throttle", "(", "this", ".", "setAccessedAt", ".", "bind", "(", "this", ")", ",", "this", ".", "_config", ".", "accessedAtThrottle", ")", ")", ";", "}" ]
Auto-populating Redis-backed cache @constructor @param {Cache} cache @param {Object} [config] @param {String} [config.populateIn] @param {String} [config.populateInAttempts] @param {String} [config.pausePopulateIn] @param {String} [config.accessedAtThrottle]
[ "Auto", "-", "populating", "Redis", "-", "backed", "cache" ]
ad79caee277771a6e49ee4a98c4983480cd89945
https://github.com/dowjones/distribucache/blob/ad79caee277771a6e49ee4a98c4983480cd89945/lib/decorators/PopulateInDecorator.js#L22-L38
train
kalamuna/metalsmith-concat-convention
index.js
concatenateFile
function concatenateFile(file, done) { // Append the concat file itself to the end of the concatenation. files[file].files.push(file) // Make sure the output is defined. if (!Object.prototype.hasOwnProperty.call(files[file], 'output')) { // Output the file to the destination, without the ".concat". const dir = path.dirname(file) const filename = path.basename(file, opts.extname) const final = path.join(dir, filename) files[file].output = final } // Tell Metalsmith Concat plugin to concatinate the files. metalsmithConcat(files[file])(files, metalsmith, done) }
javascript
function concatenateFile(file, done) { // Append the concat file itself to the end of the concatenation. files[file].files.push(file) // Make sure the output is defined. if (!Object.prototype.hasOwnProperty.call(files[file], 'output')) { // Output the file to the destination, without the ".concat". const dir = path.dirname(file) const filename = path.basename(file, opts.extname) const final = path.join(dir, filename) files[file].output = final } // Tell Metalsmith Concat plugin to concatinate the files. metalsmithConcat(files[file])(files, metalsmith, done) }
[ "function", "concatenateFile", "(", "file", ",", "done", ")", "{", "files", "[", "file", "]", ".", "files", ".", "push", "(", "file", ")", "if", "(", "!", "Object", ".", "prototype", ".", "hasOwnProperty", ".", "call", "(", "files", "[", "file", "]", ",", "'output'", ")", ")", "{", "const", "dir", "=", "path", ".", "dirname", "(", "file", ")", "const", "filename", "=", "path", ".", "basename", "(", "file", ",", "opts", ".", "extname", ")", "const", "final", "=", "path", ".", "join", "(", "dir", ",", "filename", ")", "files", "[", "file", "]", ".", "output", "=", "final", "}", "metalsmithConcat", "(", "files", "[", "file", "]", ")", "(", "files", ",", "metalsmith", ",", "done", ")", "}" ]
Tell Metalsmith Concatenate to process on the given file config.
[ "Tell", "Metalsmith", "Concatenate", "to", "process", "on", "the", "given", "file", "config", "." ]
631950f41b06423494ebf657635856ada5460615
https://github.com/kalamuna/metalsmith-concat-convention/blob/631950f41b06423494ebf657635856ada5460615/index.js#L29-L44
train