repo
stringlengths
5
67
path
stringlengths
4
116
func_name
stringlengths
0
58
original_string
stringlengths
52
373k
language
stringclasses
1 value
code
stringlengths
52
373k
code_tokens
list
docstring
stringlengths
4
11.8k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
86
226
partition
stringclasses
1 value
ChauffeurPrive/stakhanov
lib/lib.js
promisifyWithTimeout
function promisifyWithTimeout(yieldable, name, timeout) { return new Promise((resolve, reject) => { const timeoutId = setTimeout(() => reject(new Error(`Yieldable timeout in ${name}`)), timeout); co(yieldable) .then((...args) => { clearTimeout(timeoutId); resolve(...args); }) .catch((...args) => { clearTimeout(timeoutId); reject(...args); }); }); }
javascript
function promisifyWithTimeout(yieldable, name, timeout) { return new Promise((resolve, reject) => { const timeoutId = setTimeout(() => reject(new Error(`Yieldable timeout in ${name}`)), timeout); co(yieldable) .then((...args) => { clearTimeout(timeoutId); resolve(...args); }) .catch((...args) => { clearTimeout(timeoutId); reject(...args); }); }); }
[ "function", "promisifyWithTimeout", "(", "yieldable", ",", "name", ",", "timeout", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "const", "timeoutId", "=", "setTimeout", "(", "(", ")", "=>", "reject", "(", "new", "Error", "(", "`", "${", "name", "}", "`", ")", ")", ",", "timeout", ")", ";", "co", "(", "yieldable", ")", ".", "then", "(", "(", "...", "args", ")", "=>", "{", "clearTimeout", "(", "timeoutId", ")", ";", "resolve", "(", "...", "args", ")", ";", "}", ")", ".", "catch", "(", "(", "...", "args", ")", "=>", "{", "clearTimeout", "(", "timeoutId", ")", ";", "reject", "(", "...", "args", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Make a promise outside of a yieldable. To avoid unhandled callbacks resulting in unacked messages piling up in amqp, the returned promise will fail after a specified timeout. @param {Promise|Generator|Function} yieldable a yieldable (generator or promise) @param {String} name Name for error handling @param {Number} timeout Time after which the promise fails @returns {Promise} the promise
[ "Make", "a", "promise", "outside", "of", "a", "yieldable", ".", "To", "avoid", "unhandled", "callbacks", "resulting", "in", "unacked", "messages", "piling", "up", "in", "amqp", "the", "returned", "promise", "will", "fail", "after", "a", "specified", "timeout", "." ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/lib.js#L14-L27
train
ChauffeurPrive/stakhanov
lib/createWorkers.js
_wait
function _wait(eventName, timeout = 1000) { return new Promise((resolve, reject) => { let timeoutId = null; timeoutId = setTimeout(() => { timeoutId = null; reject(new Error(`event ${eventName} didn't occur after ${timeout}ms`)); }, timeout); emitter.once(eventName, () => { if (timeoutId !== null) { clearTimeout(timeoutId); resolve(); } }); }); }
javascript
function _wait(eventName, timeout = 1000) { return new Promise((resolve, reject) => { let timeoutId = null; timeoutId = setTimeout(() => { timeoutId = null; reject(new Error(`event ${eventName} didn't occur after ${timeout}ms`)); }, timeout); emitter.once(eventName, () => { if (timeoutId !== null) { clearTimeout(timeoutId); resolve(); } }); }); }
[ "function", "_wait", "(", "eventName", ",", "timeout", "=", "1000", ")", "{", "return", "new", "Promise", "(", "(", "resolve", ",", "reject", ")", "=>", "{", "let", "timeoutId", "=", "null", ";", "timeoutId", "=", "setTimeout", "(", "(", ")", "=>", "{", "timeoutId", "=", "null", ";", "reject", "(", "new", "Error", "(", "`", "${", "eventName", "}", "${", "timeout", "}", "`", ")", ")", ";", "}", ",", "timeout", ")", ";", "emitter", ".", "once", "(", "eventName", ",", "(", ")", "=>", "{", "if", "(", "timeoutId", "!==", "null", ")", "{", "clearTimeout", "(", "timeoutId", ")", ";", "resolve", "(", ")", ";", "}", "}", ")", ";", "}", ")", ";", "}" ]
Wait for an event for a given amount of time. @param {string} eventName The name of the event to wait for. @param {number} timeout The maximum number of milliseconds to wait for, defaults to 1000. @return {Promise} A promise which is resolved when the event emitted, or rejected if the timeout occurs first. @private
[ "Wait", "for", "an", "event", "for", "a", "given", "amount", "of", "time", "." ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L84-L100
train
ChauffeurPrive/stakhanov
lib/createWorkers.js
_closeOnSignal
function _closeOnSignal(signal) { process.on(signal, onSignal); /** * @returns {void} */ function onSignal() { logger.info({ workerName: configuration.workerName, signal }, '[worker#listen] Received exit signal, stopping workers...'); workers.close(true); } }
javascript
function _closeOnSignal(signal) { process.on(signal, onSignal); /** * @returns {void} */ function onSignal() { logger.info({ workerName: configuration.workerName, signal }, '[worker#listen] Received exit signal, stopping workers...'); workers.close(true); } }
[ "function", "_closeOnSignal", "(", "signal", ")", "{", "process", ".", "on", "(", "signal", ",", "onSignal", ")", ";", "function", "onSignal", "(", ")", "{", "logger", ".", "info", "(", "{", "workerName", ":", "configuration", ".", "workerName", ",", "signal", "}", ",", "'[worker#listen] Received exit signal, stopping workers...'", ")", ";", "workers", ".", "close", "(", "true", ")", ";", "}", "}" ]
Listen to exit signal such as SIGINT and close the workers @param {String} signal name (e.g. SIGINT) @returns {void} @private
[ "Listen", "to", "exit", "signal", "such", "as", "SIGINT", "and", "close", "the", "workers" ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L149-L160
train
ChauffeurPrive/stakhanov
lib/createWorkers.js
_getMessageConsumer
function _getMessageConsumer(channel, handle, validate, routingKey) { return function* _consumeMessage(message) { try { logger.debug({ message, routingKey }, '[worker#listen] received message'); const content = _parseMessage(message); if (!content) return channel.ack(message); const validatedContent = _validateMessage(validate, content); if (_.isError(validatedContent)) return channel.ack(message); const handleSuccess = yield _handleMessage( handle, validatedContent || content, message.fields ); if (!handleSuccess) return channel.nack(message); return channel.ack(message); } catch (err) { logger.error({ err, routingKey }, '[worker#listen] failed to ack/nack'); return null; } }; }
javascript
function _getMessageConsumer(channel, handle, validate, routingKey) { return function* _consumeMessage(message) { try { logger.debug({ message, routingKey }, '[worker#listen] received message'); const content = _parseMessage(message); if (!content) return channel.ack(message); const validatedContent = _validateMessage(validate, content); if (_.isError(validatedContent)) return channel.ack(message); const handleSuccess = yield _handleMessage( handle, validatedContent || content, message.fields ); if (!handleSuccess) return channel.nack(message); return channel.ack(message); } catch (err) { logger.error({ err, routingKey }, '[worker#listen] failed to ack/nack'); return null; } }; }
[ "function", "_getMessageConsumer", "(", "channel", ",", "handle", ",", "validate", ",", "routingKey", ")", "{", "return", "function", "*", "_consumeMessage", "(", "message", ")", "{", "try", "{", "logger", ".", "debug", "(", "{", "message", ",", "routingKey", "}", ",", "'[worker#listen] received message'", ")", ";", "const", "content", "=", "_parseMessage", "(", "message", ")", ";", "if", "(", "!", "content", ")", "return", "channel", ".", "ack", "(", "message", ")", ";", "const", "validatedContent", "=", "_validateMessage", "(", "validate", ",", "content", ")", ";", "if", "(", "_", ".", "isError", "(", "validatedContent", ")", ")", "return", "channel", ".", "ack", "(", "message", ")", ";", "const", "handleSuccess", "=", "yield", "_handleMessage", "(", "handle", ",", "validatedContent", "||", "content", ",", "message", ".", "fields", ")", ";", "if", "(", "!", "handleSuccess", ")", "return", "channel", ".", "nack", "(", "message", ")", ";", "return", "channel", ".", "ack", "(", "message", ")", ";", "}", "catch", "(", "err", ")", "{", "logger", ".", "error", "(", "{", "err", ",", "routingKey", "}", ",", "'[worker#listen] failed to ack/nack'", ")", ";", "return", "null", ";", "}", "}", ";", "}" ]
Create an AMQP message consumer with the given handler @param {Object} channel The AMQP channel. @param {function} handle the message handler @param {function} validate the message validator @returns {function} The generator function that consumes an AMQP message @param {String} routingKey routing key to bind on @private
[ "Create", "an", "AMQP", "message", "consumer", "with", "the", "given", "handler" ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L227-L250
train
ChauffeurPrive/stakhanov
lib/createWorkers.js
_parseMessage
function _parseMessage(message) { try { const contentString = message && message.content && message.content.toString(); return JSON.parse(contentString); } catch (err) { _emit(TASK_FAILED); logger.warn( { err, message, options: configWithoutFuncs }, '[worker#listen] Content is not a valid JSON' ); return null; } }
javascript
function _parseMessage(message) { try { const contentString = message && message.content && message.content.toString(); return JSON.parse(contentString); } catch (err) { _emit(TASK_FAILED); logger.warn( { err, message, options: configWithoutFuncs }, '[worker#listen] Content is not a valid JSON' ); return null; } }
[ "function", "_parseMessage", "(", "message", ")", "{", "try", "{", "const", "contentString", "=", "message", "&&", "message", ".", "content", "&&", "message", ".", "content", ".", "toString", "(", ")", ";", "return", "JSON", ".", "parse", "(", "contentString", ")", ";", "}", "catch", "(", "err", ")", "{", "_emit", "(", "TASK_FAILED", ")", ";", "logger", ".", "warn", "(", "{", "err", ",", "message", ",", "options", ":", "configWithoutFuncs", "}", ",", "'[worker#listen] Content is not a valid JSON'", ")", ";", "return", "null", ";", "}", "}" ]
Parse a message and return content @param {Object} message the message from the queue @returns {String|null} message content or null if parsing failed @private
[ "Parse", "a", "message", "and", "return", "content" ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L259-L271
train
ChauffeurPrive/stakhanov
lib/createWorkers.js
_validateMessage
function _validateMessage(validate, message) { const { workerName } = configuration; try { return validate(message); } catch (err) { _emit(TASK_FAILED); logger.warn( { err, message, options: configWithoutFuncs, workerName }, '[worker#listen] Message validation failed' ); return err; } }
javascript
function _validateMessage(validate, message) { const { workerName } = configuration; try { return validate(message); } catch (err) { _emit(TASK_FAILED); logger.warn( { err, message, options: configWithoutFuncs, workerName }, '[worker#listen] Message validation failed' ); return err; } }
[ "function", "_validateMessage", "(", "validate", ",", "message", ")", "{", "const", "{", "workerName", "}", "=", "configuration", ";", "try", "{", "return", "validate", "(", "message", ")", ";", "}", "catch", "(", "err", ")", "{", "_emit", "(", "TASK_FAILED", ")", ";", "logger", ".", "warn", "(", "{", "err", ",", "message", ",", "options", ":", "configWithoutFuncs", ",", "workerName", "}", ",", "'[worker#listen] Message validation failed'", ")", ";", "return", "err", ";", "}", "}" ]
Validate a message against custom validator if any @param {function} validate the message validator @param {String} message content of the message @returns {Object|null} The validated object, or null if validation failed @private
[ "Validate", "a", "message", "against", "custom", "validator", "if", "any" ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L281-L293
train
ChauffeurPrive/stakhanov
lib/createWorkers.js
_subscribeToConnectionEvents
function _subscribeToConnectionEvents(connection, workerName) { connection.on('close', errCode => { logger.info({ workerName, errCode }, '[AMQP] Connection closing, exiting'); // The workerConnection isn't working anymore... workerConnection = null; workers.close(); }); connection.on('error', err => { logger.error({ err, workerName }, '[AMQP] Connection closing because of an error'); }); connection.on('blocked', reason => { logger.warn({ reason, workerName }, '[AMQP] Connection blocked'); }); }
javascript
function _subscribeToConnectionEvents(connection, workerName) { connection.on('close', errCode => { logger.info({ workerName, errCode }, '[AMQP] Connection closing, exiting'); // The workerConnection isn't working anymore... workerConnection = null; workers.close(); }); connection.on('error', err => { logger.error({ err, workerName }, '[AMQP] Connection closing because of an error'); }); connection.on('blocked', reason => { logger.warn({ reason, workerName }, '[AMQP] Connection blocked'); }); }
[ "function", "_subscribeToConnectionEvents", "(", "connection", ",", "workerName", ")", "{", "connection", ".", "on", "(", "'close'", ",", "errCode", "=>", "{", "logger", ".", "info", "(", "{", "workerName", ",", "errCode", "}", ",", "'[AMQP] Connection closing, exiting'", ")", ";", "workerConnection", "=", "null", ";", "workers", ".", "close", "(", ")", ";", "}", ")", ";", "connection", ".", "on", "(", "'error'", ",", "err", "=>", "{", "logger", ".", "error", "(", "{", "err", ",", "workerName", "}", ",", "'[AMQP] Connection closing because of an error'", ")", ";", "}", ")", ";", "connection", ".", "on", "(", "'blocked'", ",", "reason", "=>", "{", "logger", ".", "warn", "(", "{", "reason", ",", "workerName", "}", ",", "'[AMQP] Connection blocked'", ")", ";", "}", ")", ";", "}" ]
Bind a logger to noticeable connection events @param {Object} connection the connection objext @param {String} workerName worker name @returns {*} - @private
[ "Bind", "a", "logger", "to", "noticeable", "connection", "events" ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L335-L348
train
ChauffeurPrive/stakhanov
lib/createWorkers.js
_subscribeToChannelEvents
function _subscribeToChannelEvents(channel, { exchangeName, queueName, channelPrefetch, workerName }) { channel.on('error', err => { logger.error( { err, exchangeName, queueName, channelPrefetch, workerName }, '[AMQP] channel error' ); }); channel.on('close', () => { logger.info( { exchangeName, queueName, channelPrefetch, workerName }, '[AMQP] channel closed' ); // Remove this channel because is closed workerChannels.delete(channel); workers.close(); }); }
javascript
function _subscribeToChannelEvents(channel, { exchangeName, queueName, channelPrefetch, workerName }) { channel.on('error', err => { logger.error( { err, exchangeName, queueName, channelPrefetch, workerName }, '[AMQP] channel error' ); }); channel.on('close', () => { logger.info( { exchangeName, queueName, channelPrefetch, workerName }, '[AMQP] channel closed' ); // Remove this channel because is closed workerChannels.delete(channel); workers.close(); }); }
[ "function", "_subscribeToChannelEvents", "(", "channel", ",", "{", "exchangeName", ",", "queueName", ",", "channelPrefetch", ",", "workerName", "}", ")", "{", "channel", ".", "on", "(", "'error'", ",", "err", "=>", "{", "logger", ".", "error", "(", "{", "err", ",", "exchangeName", ",", "queueName", ",", "channelPrefetch", ",", "workerName", "}", ",", "'[AMQP] channel error'", ")", ";", "}", ")", ";", "channel", ".", "on", "(", "'close'", ",", "(", ")", "=>", "{", "logger", ".", "info", "(", "{", "exchangeName", ",", "queueName", ",", "channelPrefetch", ",", "workerName", "}", ",", "'[AMQP] channel closed'", ")", ";", "workerChannels", ".", "delete", "(", "channel", ")", ";", "workers", ".", "close", "(", ")", ";", "}", ")", ";", "}" ]
Bind a logger to noticeable channel events @param {Object} channel the channel object @param {String} exchangeName the exchange name to use @param {String} queueName the queue name to target @param {Number} channelPrefetch number of message to prefetch from channel @param {String} workerName the name of the worker (for logs) @returns {*} - @private
[ "Bind", "a", "logger", "to", "noticeable", "channel", "events" ]
c6a09a2bbb4afdeebe06ab942b2595f689ba77b8
https://github.com/ChauffeurPrive/stakhanov/blob/c6a09a2bbb4afdeebe06ab942b2595f689ba77b8/lib/createWorkers.js#L389-L406
train
adrai/node-cqrs-eventdenormalizer
lib/replayHandler.js
function (callback) { var self = this; async.parallel([ function (callback) { async.each(self.dispatcher.tree.getCollections(), function (col, callback) { if (col.noReplay) { return callback(null); } col.repository.clear(callback); }, callback); }, function (callback) { self.store.clear(callback); } ], callback); }
javascript
function (callback) { var self = this; async.parallel([ function (callback) { async.each(self.dispatcher.tree.getCollections(), function (col, callback) { if (col.noReplay) { return callback(null); } col.repository.clear(callback); }, callback); }, function (callback) { self.store.clear(callback); } ], callback); }
[ "function", "(", "callback", ")", "{", "var", "self", "=", "this", ";", "async", ".", "parallel", "(", "[", "function", "(", "callback", ")", "{", "async", ".", "each", "(", "self", ".", "dispatcher", ".", "tree", ".", "getCollections", "(", ")", ",", "function", "(", "col", ",", "callback", ")", "{", "if", "(", "col", ".", "noReplay", ")", "{", "return", "callback", "(", "null", ")", ";", "}", "col", ".", "repository", ".", "clear", "(", "callback", ")", ";", "}", ",", "callback", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "self", ".", "store", ".", "clear", "(", "callback", ")", ";", "}", "]", ",", "callback", ")", ";", "}" ]
Clears all collections and the revisionGuardStore. @param {Function} callback The function, that will be called when this action is completed. `function(err){}`
[ "Clears", "all", "collections", "and", "the", "revisionGuardStore", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/replayHandler.js#L48-L63
train
adrai/node-cqrs-eventdenormalizer
lib/replayHandler.js
function (revisionMap, callback) { var self = this; var ids = _.keys(revisionMap); async.each(ids, function (id, callback) { self.store.get(id, function (err, rev) { if (err) { return callback(err); } self.store.set(id, revisionMap[id] + 1, rev, callback); }); }, callback); }
javascript
function (revisionMap, callback) { var self = this; var ids = _.keys(revisionMap); async.each(ids, function (id, callback) { self.store.get(id, function (err, rev) { if (err) { return callback(err); } self.store.set(id, revisionMap[id] + 1, rev, callback); }); }, callback); }
[ "function", "(", "revisionMap", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "var", "ids", "=", "_", ".", "keys", "(", "revisionMap", ")", ";", "async", ".", "each", "(", "ids", ",", "function", "(", "id", ",", "callback", ")", "{", "self", ".", "store", ".", "get", "(", "id", ",", "function", "(", "err", ",", "rev", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "self", ".", "store", ".", "set", "(", "id", ",", "revisionMap", "[", "id", "]", "+", "1", ",", "rev", ",", "callback", ")", ";", "}", ")", ";", "}", ",", "callback", ")", ";", "}" ]
Updates the revision in the store. @param {Object} revisionMap The revision map. @param {Function} callback The function, that will be called when this action is completed. `function(err){}`
[ "Updates", "the", "revision", "in", "the", "store", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/replayHandler.js#L95-L106
train
adrai/node-cqrs-eventdenormalizer
lib/replayHandler.js
function (evts, callback) { this.replayStreamed(function (replay, done) { evts.forEach(function (evt) { replay(evt); }); done(callback); }); }
javascript
function (evts, callback) { this.replayStreamed(function (replay, done) { evts.forEach(function (evt) { replay(evt); }); done(callback); }); }
[ "function", "(", "evts", ",", "callback", ")", "{", "this", ".", "replayStreamed", "(", "function", "(", "replay", ",", "done", ")", "{", "evts", ".", "forEach", "(", "function", "(", "evt", ")", "{", "replay", "(", "evt", ")", ";", "}", ")", ";", "done", "(", "callback", ")", ";", "}", ")", ";", "}" ]
Replays all passed events. @param {Array} evts The passed array of events. @param {Function} callback The function, that will be called when this action is completed. `function(err){}`
[ "Replays", "all", "passed", "events", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/replayHandler.js#L114-L121
train
stimulant/ampm
model/persistence.js
function() { if (!this._startupSchedule || !this._shutdownSchedule) { return true; } var lastStartup = later.schedule(this._startupSchedule).prev().getTime(); var lastShutdown = later.schedule(this._shutdownSchedule).prev().getTime(); return lastStartup > lastShutdown; }
javascript
function() { if (!this._startupSchedule || !this._shutdownSchedule) { return true; } var lastStartup = later.schedule(this._startupSchedule).prev().getTime(); var lastShutdown = later.schedule(this._shutdownSchedule).prev().getTime(); return lastStartup > lastShutdown; }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "_startupSchedule", "||", "!", "this", ".", "_shutdownSchedule", ")", "{", "return", "true", ";", "}", "var", "lastStartup", "=", "later", ".", "schedule", "(", "this", ".", "_startupSchedule", ")", ".", "prev", "(", ")", ".", "getTime", "(", ")", ";", "var", "lastShutdown", "=", "later", ".", "schedule", "(", "this", ".", "_shutdownSchedule", ")", ".", "prev", "(", ")", ".", "getTime", "(", ")", ";", "return", "lastStartup", ">", "lastShutdown", ";", "}" ]
Determine whether the app should be running, based on the cron schedules.
[ "Determine", "whether", "the", "app", "should", "be", "running", "based", "on", "the", "cron", "schedules", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/persistence.js#L223-L231
train
stimulant/ampm
model/persistence.js
function(message) { this._resetRestartTimeout(this.get('heartbeatTimeout')); if (!this._lastHeart) { this._isStartingUp = false; this._firstHeart = Date.now(); logger.info('App started.'); if (this.get('postLaunchCommand')) { spawn(this.get('postLaunchCommand'), null, null, function(err, output) { console.log(err, output); }); } if (this._startupCallback) { this._startupCallback(); this._startupCallback = null; } } this._lastHeart = Date.now(); this.trigger('heart'); }
javascript
function(message) { this._resetRestartTimeout(this.get('heartbeatTimeout')); if (!this._lastHeart) { this._isStartingUp = false; this._firstHeart = Date.now(); logger.info('App started.'); if (this.get('postLaunchCommand')) { spawn(this.get('postLaunchCommand'), null, null, function(err, output) { console.log(err, output); }); } if (this._startupCallback) { this._startupCallback(); this._startupCallback = null; } } this._lastHeart = Date.now(); this.trigger('heart'); }
[ "function", "(", "message", ")", "{", "this", ".", "_resetRestartTimeout", "(", "this", ".", "get", "(", "'heartbeatTimeout'", ")", ")", ";", "if", "(", "!", "this", ".", "_lastHeart", ")", "{", "this", ".", "_isStartingUp", "=", "false", ";", "this", ".", "_firstHeart", "=", "Date", ".", "now", "(", ")", ";", "logger", ".", "info", "(", "'App started.'", ")", ";", "if", "(", "this", ".", "get", "(", "'postLaunchCommand'", ")", ")", "{", "spawn", "(", "this", ".", "get", "(", "'postLaunchCommand'", ")", ",", "null", ",", "null", ",", "function", "(", "err", ",", "output", ")", "{", "console", ".", "log", "(", "err", ",", "output", ")", ";", "}", ")", ";", "}", "if", "(", "this", ".", "_startupCallback", ")", "{", "this", ".", "_startupCallback", "(", ")", ";", "this", ".", "_startupCallback", "=", "null", ";", "}", "}", "this", ".", "_lastHeart", "=", "Date", ".", "now", "(", ")", ";", "this", ".", "trigger", "(", "'heart'", ")", ";", "}" ]
Handle heartbeat messages from the app.
[ "Handle", "heartbeat", "messages", "from", "the", "app", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/persistence.js#L234-L255
train
stimulant/ampm
model/persistence.js
function(time) { clearTimeout(this._restartTimeout); if (!time) { return; } if (!this._isShuttingDown) { this._restartTimeout = setTimeout(_.bind(this._onRestartTimeout, this), time * 1000); } }
javascript
function(time) { clearTimeout(this._restartTimeout); if (!time) { return; } if (!this._isShuttingDown) { this._restartTimeout = setTimeout(_.bind(this._onRestartTimeout, this), time * 1000); } }
[ "function", "(", "time", ")", "{", "clearTimeout", "(", "this", ".", "_restartTimeout", ")", ";", "if", "(", "!", "time", ")", "{", "return", ";", "}", "if", "(", "!", "this", ".", "_isShuttingDown", ")", "{", "this", ".", "_restartTimeout", "=", "setTimeout", "(", "_", ".", "bind", "(", "this", ".", "_onRestartTimeout", ",", "this", ")", ",", "time", "*", "1000", ")", ";", "}", "}" ]
Cancel and reset the timeout that restarts the app.
[ "Cancel", "and", "reset", "the", "timeout", "that", "restarts", "the", "app", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/persistence.js#L258-L266
train
stimulant/ampm
model/persistence.js
function() { var that = this; // Save a screenshot. if ($$logging.get('screenshots').enabled) { var filename = $$logging.get('screenshots').filename.replace('{date}', moment().format('YYYYMMDDhhmmss')); logger.info('Saving screenshot to ' + filename); var winCmd = path.join(__dirname, '../tools', 'nircmd.exe'); var winArgs = ['savescreenshotfull', filename]; var macCmd = '/usr/sbin/screencapture'; var macArgs = ['-x', '-t', 'jpg', '-C', filename]; var cmd = process.platform === 'win32' ? winCmd : macCmd; var args = process.platform === 'win32' ? winArgs : macArgs; var screenshot = child_process.spawn(cmd, args); screenshot.on('close', function(code, signal) { logger.info('Screenshot saved, restarting.'); restart(); }); } else { restart(); } function restart() { var restartCount = that.get('restartCount'); restartCount++; var logList = 'App went away: ' + restartCount + ' times\n\n'; _.each($$logging.get('logCache'), function(log) { logList += log.time + ' ' + log.level + ': ' + log.msg + '\n'; }); logger.error(logList); that.trigger('crash'); if (restartCount >= that.get('restartMachineAfter')) { logger.info('Already restarted app ' + that.get('restartMachineAfter') + ' times, rebooting machine.'); that.restartMachine(); return; } that.set('restartCount', restartCount); that._isStartingUp = false; that._isShuttingDown = false; that.restartApp(); } }
javascript
function() { var that = this; // Save a screenshot. if ($$logging.get('screenshots').enabled) { var filename = $$logging.get('screenshots').filename.replace('{date}', moment().format('YYYYMMDDhhmmss')); logger.info('Saving screenshot to ' + filename); var winCmd = path.join(__dirname, '../tools', 'nircmd.exe'); var winArgs = ['savescreenshotfull', filename]; var macCmd = '/usr/sbin/screencapture'; var macArgs = ['-x', '-t', 'jpg', '-C', filename]; var cmd = process.platform === 'win32' ? winCmd : macCmd; var args = process.platform === 'win32' ? winArgs : macArgs; var screenshot = child_process.spawn(cmd, args); screenshot.on('close', function(code, signal) { logger.info('Screenshot saved, restarting.'); restart(); }); } else { restart(); } function restart() { var restartCount = that.get('restartCount'); restartCount++; var logList = 'App went away: ' + restartCount + ' times\n\n'; _.each($$logging.get('logCache'), function(log) { logList += log.time + ' ' + log.level + ': ' + log.msg + '\n'; }); logger.error(logList); that.trigger('crash'); if (restartCount >= that.get('restartMachineAfter')) { logger.info('Already restarted app ' + that.get('restartMachineAfter') + ' times, rebooting machine.'); that.restartMachine(); return; } that.set('restartCount', restartCount); that._isStartingUp = false; that._isShuttingDown = false; that.restartApp(); } }
[ "function", "(", ")", "{", "var", "that", "=", "this", ";", "if", "(", "$$logging", ".", "get", "(", "'screenshots'", ")", ".", "enabled", ")", "{", "var", "filename", "=", "$$logging", ".", "get", "(", "'screenshots'", ")", ".", "filename", ".", "replace", "(", "'{date}'", ",", "moment", "(", ")", ".", "format", "(", "'YYYYMMDDhhmmss'", ")", ")", ";", "logger", ".", "info", "(", "'Saving screenshot to '", "+", "filename", ")", ";", "var", "winCmd", "=", "path", ".", "join", "(", "__dirname", ",", "'../tools'", ",", "'nircmd.exe'", ")", ";", "var", "winArgs", "=", "[", "'savescreenshotfull'", ",", "filename", "]", ";", "var", "macCmd", "=", "'/usr/sbin/screencapture'", ";", "var", "macArgs", "=", "[", "'-x'", ",", "'-t'", ",", "'jpg'", ",", "'-C'", ",", "filename", "]", ";", "var", "cmd", "=", "process", ".", "platform", "===", "'win32'", "?", "winCmd", ":", "macCmd", ";", "var", "args", "=", "process", ".", "platform", "===", "'win32'", "?", "winArgs", ":", "macArgs", ";", "var", "screenshot", "=", "child_process", ".", "spawn", "(", "cmd", ",", "args", ")", ";", "screenshot", ".", "on", "(", "'close'", ",", "function", "(", "code", ",", "signal", ")", "{", "logger", ".", "info", "(", "'Screenshot saved, restarting.'", ")", ";", "restart", "(", ")", ";", "}", ")", ";", "}", "else", "{", "restart", "(", ")", ";", "}", "function", "restart", "(", ")", "{", "var", "restartCount", "=", "that", ".", "get", "(", "'restartCount'", ")", ";", "restartCount", "++", ";", "var", "logList", "=", "'App went away: '", "+", "restartCount", "+", "' times\\n\\n'", ";", "\\n", "\\n", "_", ".", "each", "(", "$$logging", ".", "get", "(", "'logCache'", ")", ",", "function", "(", "log", ")", "{", "logList", "+=", "log", ".", "time", "+", "' '", "+", "log", ".", "level", "+", "': '", "+", "log", ".", "msg", "+", "'\\n'", ";", "}", ")", ";", "\\n", "logger", ".", "error", "(", "logList", ")", ";", "that", ".", "trigger", "(", "'crash'", ")", ";", "if", "(", "restartCount", ">=", "that", ".", "get", "(", "'restartMachineAfter'", ")", ")", "{", "logger", ".", "info", "(", "'Already restarted app '", "+", "that", ".", "get", "(", "'restartMachineAfter'", ")", "+", "' times, rebooting machine.'", ")", ";", "that", ".", "restartMachine", "(", ")", ";", "return", ";", "}", "that", ".", "set", "(", "'restartCount'", ",", "restartCount", ")", ";", "}", "}" ]
When a heartbeat hasn't been received for a while, restart the app or the whole machine.
[ "When", "a", "heartbeat", "hasn", "t", "been", "received", "for", "a", "while", "restart", "the", "app", "or", "the", "whole", "machine", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/persistence.js#L269-L318
train
stimulant/ampm
model/persistence.js
function(callback) { if (this._isShuttingDown || this._isStartingUp) { return; } this._isShuttingDown = true; // See if the app is running. if (!this.processId() && !this.sideProcessId()) { this._isShuttingDown = false; // Nope, not running. if (callback) { callback(); } return; } // Kill the app. clearTimeout(this._restartTimeout); this._appProcess.kill(); if (this._sideProcess) { this._sideProcess.kill(); } // Check on an interval to see if it's dead. var check = setInterval(_.bind(function() { if (this.processId() || this.sideProcessId()) { return; } clearInterval(check); logger.info('App shut down by force.'); this._isShuttingDown = false; if (callback) { callback(); } }, this), 250); }
javascript
function(callback) { if (this._isShuttingDown || this._isStartingUp) { return; } this._isShuttingDown = true; // See if the app is running. if (!this.processId() && !this.sideProcessId()) { this._isShuttingDown = false; // Nope, not running. if (callback) { callback(); } return; } // Kill the app. clearTimeout(this._restartTimeout); this._appProcess.kill(); if (this._sideProcess) { this._sideProcess.kill(); } // Check on an interval to see if it's dead. var check = setInterval(_.bind(function() { if (this.processId() || this.sideProcessId()) { return; } clearInterval(check); logger.info('App shut down by force.'); this._isShuttingDown = false; if (callback) { callback(); } }, this), 250); }
[ "function", "(", "callback", ")", "{", "if", "(", "this", ".", "_isShuttingDown", "||", "this", ".", "_isStartingUp", ")", "{", "return", ";", "}", "this", ".", "_isShuttingDown", "=", "true", ";", "if", "(", "!", "this", ".", "processId", "(", ")", "&&", "!", "this", ".", "sideProcessId", "(", ")", ")", "{", "this", ".", "_isShuttingDown", "=", "false", ";", "if", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", "return", ";", "}", "clearTimeout", "(", "this", ".", "_restartTimeout", ")", ";", "this", ".", "_appProcess", ".", "kill", "(", ")", ";", "if", "(", "this", ".", "_sideProcess", ")", "{", "this", ".", "_sideProcess", ".", "kill", "(", ")", ";", "}", "var", "check", "=", "setInterval", "(", "_", ".", "bind", "(", "function", "(", ")", "{", "if", "(", "this", ".", "processId", "(", ")", "||", "this", ".", "sideProcessId", "(", ")", ")", "{", "return", ";", "}", "clearInterval", "(", "check", ")", ";", "logger", ".", "info", "(", "'App shut down by force.'", ")", ";", "this", ".", "_isShuttingDown", "=", "false", ";", "if", "(", "callback", ")", "{", "callback", "(", ")", ";", "}", "}", ",", "this", ")", ",", "250", ")", ";", "}" ]
Kill the app process.
[ "Kill", "the", "app", "process", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/persistence.js#L329-L367
train
stimulant/ampm
model/persistence.js
function(force, callback) { // Don't start if we're waiting for it to finish starting already. var should = !this._isStartingUp; // Don't start if we're outside the schedule, unless requested by the console. should = should && (this._shouldBeRunning() || force === true); // Don't start if it's already running. should = should && !this.processId(); // Don't start if there's no start command. should = should && this.get('launchCommand'); if (!should) { return; } if (this.get('startupTimeout')) { this._isStartingUp = true; } if (this.processId()) { // It's already running. this._isStartingUp = false; if (callback) { callback(true); } return; } this._lastHeart = null; this._firstHeart = null; this._startupCallback = callback; var parts = this._parseCommand(this.get('launchCommand')); // Start the app. logger.info('App starting up.'); this._appProcess = child_process.spawn(parts[0], parts.slice(1), { cwd: path.dirname(parts[0]) }) .on('exit', _.bind(function() { this._appProcess = null; }, this)) .on('error', _.bind(function(err) { logger.error('Application could not be started. Is the launchCommand path correct?'); this._appProcess = null; }, this)); this._resetRestartTimeout(this.get('startupTimeout')); if (!this.get('sideCommand')) { return; } // Start the side process. parts = this._parseCommand(this.get('sideCommand')); this._sideProcess = child_process.spawn(parts[0], parts.slice(1), { cwd: path.dirname(parts[0]) }).on('exit', _.bind(function() { this._sideProcess = null; }, this)); }
javascript
function(force, callback) { // Don't start if we're waiting for it to finish starting already. var should = !this._isStartingUp; // Don't start if we're outside the schedule, unless requested by the console. should = should && (this._shouldBeRunning() || force === true); // Don't start if it's already running. should = should && !this.processId(); // Don't start if there's no start command. should = should && this.get('launchCommand'); if (!should) { return; } if (this.get('startupTimeout')) { this._isStartingUp = true; } if (this.processId()) { // It's already running. this._isStartingUp = false; if (callback) { callback(true); } return; } this._lastHeart = null; this._firstHeart = null; this._startupCallback = callback; var parts = this._parseCommand(this.get('launchCommand')); // Start the app. logger.info('App starting up.'); this._appProcess = child_process.spawn(parts[0], parts.slice(1), { cwd: path.dirname(parts[0]) }) .on('exit', _.bind(function() { this._appProcess = null; }, this)) .on('error', _.bind(function(err) { logger.error('Application could not be started. Is the launchCommand path correct?'); this._appProcess = null; }, this)); this._resetRestartTimeout(this.get('startupTimeout')); if (!this.get('sideCommand')) { return; } // Start the side process. parts = this._parseCommand(this.get('sideCommand')); this._sideProcess = child_process.spawn(parts[0], parts.slice(1), { cwd: path.dirname(parts[0]) }).on('exit', _.bind(function() { this._sideProcess = null; }, this)); }
[ "function", "(", "force", ",", "callback", ")", "{", "var", "should", "=", "!", "this", ".", "_isStartingUp", ";", "should", "=", "should", "&&", "(", "this", ".", "_shouldBeRunning", "(", ")", "||", "force", "===", "true", ")", ";", "should", "=", "should", "&&", "!", "this", ".", "processId", "(", ")", ";", "should", "=", "should", "&&", "this", ".", "get", "(", "'launchCommand'", ")", ";", "if", "(", "!", "should", ")", "{", "return", ";", "}", "if", "(", "this", ".", "get", "(", "'startupTimeout'", ")", ")", "{", "this", ".", "_isStartingUp", "=", "true", ";", "}", "if", "(", "this", ".", "processId", "(", ")", ")", "{", "this", ".", "_isStartingUp", "=", "false", ";", "if", "(", "callback", ")", "{", "callback", "(", "true", ")", ";", "}", "return", ";", "}", "this", ".", "_lastHeart", "=", "null", ";", "this", ".", "_firstHeart", "=", "null", ";", "this", ".", "_startupCallback", "=", "callback", ";", "var", "parts", "=", "this", ".", "_parseCommand", "(", "this", ".", "get", "(", "'launchCommand'", ")", ")", ";", "logger", ".", "info", "(", "'App starting up.'", ")", ";", "this", ".", "_appProcess", "=", "child_process", ".", "spawn", "(", "parts", "[", "0", "]", ",", "parts", ".", "slice", "(", "1", ")", ",", "{", "cwd", ":", "path", ".", "dirname", "(", "parts", "[", "0", "]", ")", "}", ")", ".", "on", "(", "'exit'", ",", "_", ".", "bind", "(", "function", "(", ")", "{", "this", ".", "_appProcess", "=", "null", ";", "}", ",", "this", ")", ")", ".", "on", "(", "'error'", ",", "_", ".", "bind", "(", "function", "(", "err", ")", "{", "logger", ".", "error", "(", "'Application could not be started. Is the launchCommand path correct?'", ")", ";", "this", ".", "_appProcess", "=", "null", ";", "}", ",", "this", ")", ")", ";", "this", ".", "_resetRestartTimeout", "(", "this", ".", "get", "(", "'startupTimeout'", ")", ")", ";", "if", "(", "!", "this", ".", "get", "(", "'sideCommand'", ")", ")", "{", "return", ";", "}", "parts", "=", "this", ".", "_parseCommand", "(", "this", ".", "get", "(", "'sideCommand'", ")", ")", ";", "this", ".", "_sideProcess", "=", "child_process", ".", "spawn", "(", "parts", "[", "0", "]", ",", "parts", ".", "slice", "(", "1", ")", ",", "{", "cwd", ":", "path", ".", "dirname", "(", "parts", "[", "0", "]", ")", "}", ")", ".", "on", "(", "'exit'", ",", "_", ".", "bind", "(", "function", "(", ")", "{", "this", ".", "_sideProcess", "=", "null", ";", "}", ",", "this", ")", ")", ";", "}" ]
Start the app process.
[ "Start", "the", "app", "process", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/persistence.js#L370-L433
train
stimulant/ampm
model/persistence.js
function() { if (this._isShuttingDown) { return; } this._isShuttingDown = true; // Restart but wait a bit to log things. // -R - restart // -C - shutdown message // -T 0 - shutdown now // -F - don't wait for anything to shut down gracefully var winCmd = 'shutdown -R -T 0 -F -C "ampm restart"'; var macCmd = 'shutdown -r now'; var cmd = process.platform === 'win32' ? winCmd : macCmd; setTimeout(child_process.exec(cmd), 3000); }
javascript
function() { if (this._isShuttingDown) { return; } this._isShuttingDown = true; // Restart but wait a bit to log things. // -R - restart // -C - shutdown message // -T 0 - shutdown now // -F - don't wait for anything to shut down gracefully var winCmd = 'shutdown -R -T 0 -F -C "ampm restart"'; var macCmd = 'shutdown -r now'; var cmd = process.platform === 'win32' ? winCmd : macCmd; setTimeout(child_process.exec(cmd), 3000); }
[ "function", "(", ")", "{", "if", "(", "this", ".", "_isShuttingDown", ")", "{", "return", ";", "}", "this", ".", "_isShuttingDown", "=", "true", ";", "var", "winCmd", "=", "'shutdown -R -T 0 -F -C \"ampm restart\"'", ";", "var", "macCmd", "=", "'shutdown -r now'", ";", "var", "cmd", "=", "process", ".", "platform", "===", "'win32'", "?", "winCmd", ":", "macCmd", ";", "setTimeout", "(", "child_process", ".", "exec", "(", "cmd", ")", ",", "3000", ")", ";", "}" ]
Reboot the whole PC.
[ "Reboot", "the", "whole", "PC", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/persistence.js#L504-L519
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/eventExtender.js
function (collection) { if (!collection || !_.isObject(collection)) { var err = new Error('Please pass a valid collection!'); debug(err); throw err; } this.collection = collection; }
javascript
function (collection) { if (!collection || !_.isObject(collection)) { var err = new Error('Please pass a valid collection!'); debug(err); throw err; } this.collection = collection; }
[ "function", "(", "collection", ")", "{", "if", "(", "!", "collection", "||", "!", "_", ".", "isObject", "(", "collection", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass a valid collection!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "this", ".", "collection", "=", "collection", ";", "}" ]
Injects the needed collection. @param {Object} collection The collection object to inject.
[ "Injects", "the", "needed", "collection", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/eventExtender.js#L42-L50
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/eventExtender.js
function (evt, callback) { if (this.id && dotty.exists(evt, this.id)) { debug('found viewmodel id in event'); return callback(null, dotty.get(evt, this.id)); } if (this.getNewIdForThisEventExtender) { debug('[' + this.name + '] found eventextender id getter in event'); return this.getNewIdForThisEventExtender(evt, callback); } debug('not found viewmodel id in event, generate new id'); this.collection.getNewId(callback); }
javascript
function (evt, callback) { if (this.id && dotty.exists(evt, this.id)) { debug('found viewmodel id in event'); return callback(null, dotty.get(evt, this.id)); } if (this.getNewIdForThisEventExtender) { debug('[' + this.name + '] found eventextender id getter in event'); return this.getNewIdForThisEventExtender(evt, callback); } debug('not found viewmodel id in event, generate new id'); this.collection.getNewId(callback); }
[ "function", "(", "evt", ",", "callback", ")", "{", "if", "(", "this", ".", "id", "&&", "dotty", ".", "exists", "(", "evt", ",", "this", ".", "id", ")", ")", "{", "debug", "(", "'found viewmodel id in event'", ")", ";", "return", "callback", "(", "null", ",", "dotty", ".", "get", "(", "evt", ",", "this", ".", "id", ")", ")", ";", "}", "if", "(", "this", ".", "getNewIdForThisEventExtender", ")", "{", "debug", "(", "'['", "+", "this", ".", "name", "+", "'] found eventextender id getter in event'", ")", ";", "return", "this", ".", "getNewIdForThisEventExtender", "(", "evt", ",", "callback", ")", ";", "}", "debug", "(", "'not found viewmodel id in event, generate new id'", ")", ";", "this", ".", "collection", ".", "getNewId", "(", "callback", ")", ";", "}" ]
Extracts the id from the event or generates a new one. @param {Object} evt The event object. @param {Function} callback The function that will be called when this action has finished `function(err, id){}`
[ "Extracts", "the", "id", "from", "the", "event", "or", "generates", "a", "new", "one", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/eventExtender.js#L89-L102
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/eventExtender.js
function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } if (fn.length === 2) { this.getNewIdForThisEventExtender = fn; return this; } this.getNewIdForThisEventExtender = function (evt, callback) { callback(null, fn(evt)); }; return this; }
javascript
function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } if (fn.length === 2) { this.getNewIdForThisEventExtender = fn; return this; } this.getNewIdForThisEventExtender = function (evt, callback) { callback(null, fn(evt)); }; return this; }
[ "function", "(", "fn", ")", "{", "if", "(", "!", "fn", "||", "!", "_", ".", "isFunction", "(", "fn", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass a valid function!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "if", "(", "fn", ".", "length", "===", "2", ")", "{", "this", ".", "getNewIdForThisEventExtender", "=", "fn", ";", "return", "this", ";", "}", "this", ".", "getNewIdForThisEventExtender", "=", "function", "(", "evt", ",", "callback", ")", "{", "callback", "(", "null", ",", "fn", "(", "evt", ")", ")", ";", "}", ";", "return", "this", ";", "}" ]
Inject idGenerator for eventextender function if no id found. @param {Function} fn The function to be injected. @returns {EventExtender} to be able to chain...
[ "Inject", "idGenerator", "for", "eventextender", "function", "if", "no", "id", "found", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/eventExtender.js#L235-L253
train
stackfull/angular-webpack-plugin
lib/index.js
function(compiler){ bindCallbackMethod(compiler, "compilation", this, this.addDependencyFactories); bindCallbackMethod(compiler.parser, "expression window.angular", this, this.addAngularVariable); bindCallbackMethod(compiler.parser, "expression angular", this, this.addAngularVariable); bindCallbackMethod(compiler.parser, "call angular.module", this, this.parseModuleCall); bindCallbackMethod(compiler.resolvers.normal, "module-module", this, this.resolveModule); }
javascript
function(compiler){ bindCallbackMethod(compiler, "compilation", this, this.addDependencyFactories); bindCallbackMethod(compiler.parser, "expression window.angular", this, this.addAngularVariable); bindCallbackMethod(compiler.parser, "expression angular", this, this.addAngularVariable); bindCallbackMethod(compiler.parser, "call angular.module", this, this.parseModuleCall); bindCallbackMethod(compiler.resolvers.normal, "module-module", this, this.resolveModule); }
[ "function", "(", "compiler", ")", "{", "bindCallbackMethod", "(", "compiler", ",", "\"compilation\"", ",", "this", ",", "this", ".", "addDependencyFactories", ")", ";", "bindCallbackMethod", "(", "compiler", ".", "parser", ",", "\"expression window.angular\"", ",", "this", ",", "this", ".", "addAngularVariable", ")", ";", "bindCallbackMethod", "(", "compiler", ".", "parser", ",", "\"expression angular\"", ",", "this", ",", "this", ".", "addAngularVariable", ")", ";", "bindCallbackMethod", "(", "compiler", ".", "parser", ",", "\"call angular.module\"", ",", "this", ",", "this", ".", "parseModuleCall", ")", ";", "bindCallbackMethod", "(", "compiler", ".", "resolvers", ".", "normal", ",", "\"module-module\"", ",", "this", ",", "this", ".", "resolveModule", ")", ";", "}" ]
This is the entrypoint that is called when the plugin is added to a compiler
[ "This", "is", "the", "entrypoint", "that", "is", "called", "when", "the", "plugin", "is", "added", "to", "a", "compiler" ]
c245d36ae80d16d7de56b86de450109421fb69de
https://github.com/stackfull/angular-webpack-plugin/blob/c245d36ae80d16d7de56b86de450109421fb69de/lib/index.js#L56-L67
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/collection.js
function (repository) { if (!repository || !_.isObject(repository)) { var err = new Error('Please pass a valid repository!'); debug(err); throw err; } var extendObject = { collectionName: this.name, indexes: this.indexes, }; if (repository.repositoryType && this.repositorySettings[repository.repositoryType]) { extendObject.repositorySettings = {}; extendObject.repositorySettings[repository.repositoryType] = this.repositorySettings[repository.repositoryType]; } this.repository = repository.extend(extendObject); }
javascript
function (repository) { if (!repository || !_.isObject(repository)) { var err = new Error('Please pass a valid repository!'); debug(err); throw err; } var extendObject = { collectionName: this.name, indexes: this.indexes, }; if (repository.repositoryType && this.repositorySettings[repository.repositoryType]) { extendObject.repositorySettings = {}; extendObject.repositorySettings[repository.repositoryType] = this.repositorySettings[repository.repositoryType]; } this.repository = repository.extend(extendObject); }
[ "function", "(", "repository", ")", "{", "if", "(", "!", "repository", "||", "!", "_", ".", "isObject", "(", "repository", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass a valid repository!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "var", "extendObject", "=", "{", "collectionName", ":", "this", ".", "name", ",", "indexes", ":", "this", ".", "indexes", ",", "}", ";", "if", "(", "repository", ".", "repositoryType", "&&", "this", ".", "repositorySettings", "[", "repository", ".", "repositoryType", "]", ")", "{", "extendObject", ".", "repositorySettings", "=", "{", "}", ";", "extendObject", ".", "repositorySettings", "[", "repository", ".", "repositoryType", "]", "=", "this", ".", "repositorySettings", "[", "repository", ".", "repositoryType", "]", ";", "}", "this", ".", "repository", "=", "repository", ".", "extend", "(", "extendObject", ")", ";", "}" ]
Injects the needed repository. @param {Object} repository The repository object to inject.
[ "Injects", "the", "needed", "repository", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/collection.js#L39-L57
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/collection.js
function (viewBuilder) { if (!viewBuilder || !_.isObject(viewBuilder)) { var err = new Error('Please inject a valid view builder object!'); debug(err); throw err; } if (viewBuilder.payload === null || viewBuilder.payload === undefined) { viewBuilder.payload = this.defaultPayload; } if (this.viewBuilders.indexOf(viewBuilder) < 0) { viewBuilder.useCollection(this); this.viewBuilders.push(viewBuilder); } }
javascript
function (viewBuilder) { if (!viewBuilder || !_.isObject(viewBuilder)) { var err = new Error('Please inject a valid view builder object!'); debug(err); throw err; } if (viewBuilder.payload === null || viewBuilder.payload === undefined) { viewBuilder.payload = this.defaultPayload; } if (this.viewBuilders.indexOf(viewBuilder) < 0) { viewBuilder.useCollection(this); this.viewBuilders.push(viewBuilder); } }
[ "function", "(", "viewBuilder", ")", "{", "if", "(", "!", "viewBuilder", "||", "!", "_", ".", "isObject", "(", "viewBuilder", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please inject a valid view builder object!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "if", "(", "viewBuilder", ".", "payload", "===", "null", "||", "viewBuilder", ".", "payload", "===", "undefined", ")", "{", "viewBuilder", ".", "payload", "=", "this", ".", "defaultPayload", ";", "}", "if", "(", "this", ".", "viewBuilders", ".", "indexOf", "(", "viewBuilder", ")", "<", "0", ")", "{", "viewBuilder", ".", "useCollection", "(", "this", ")", ";", "this", ".", "viewBuilders", ".", "push", "(", "viewBuilder", ")", ";", "}", "}" ]
Add viewBuilder module. @param {ViewBuilder} viewBuilder The viewBuilder module to be injected.
[ "Add", "viewBuilder", "module", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/collection.js#L62-L75
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/collection.js
function (eventExtender) { if (!eventExtender || !_.isObject(eventExtender)) { var err = new Error('Please inject a valid event extender object!'); debug(err); throw err; } if (this.eventExtenders.indexOf(eventExtender) < 0) { eventExtender.useCollection(this); this.eventExtenders.push(eventExtender); } }
javascript
function (eventExtender) { if (!eventExtender || !_.isObject(eventExtender)) { var err = new Error('Please inject a valid event extender object!'); debug(err); throw err; } if (this.eventExtenders.indexOf(eventExtender) < 0) { eventExtender.useCollection(this); this.eventExtenders.push(eventExtender); } }
[ "function", "(", "eventExtender", ")", "{", "if", "(", "!", "eventExtender", "||", "!", "_", ".", "isObject", "(", "eventExtender", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please inject a valid event extender object!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "if", "(", "this", ".", "eventExtenders", ".", "indexOf", "(", "eventExtender", ")", "<", "0", ")", "{", "eventExtender", ".", "useCollection", "(", "this", ")", ";", "this", ".", "eventExtenders", ".", "push", "(", "eventExtender", ")", ";", "}", "}" ]
Add eventExtender module. @param {EventExtender} eventExtender The eventExtender module to be injected.
[ "Add", "eventExtender", "module", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/collection.js#L80-L90
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/collection.js
function (preEventExtender) { if (!preEventExtender || !_.isObject(preEventExtender)) { var err = new Error('Please inject a valid event extender object!'); debug(err); throw err; } if (this.preEventExtenders.indexOf(preEventExtender) < 0) { preEventExtender.useCollection(this); this.preEventExtenders.push(preEventExtender); } }
javascript
function (preEventExtender) { if (!preEventExtender || !_.isObject(preEventExtender)) { var err = new Error('Please inject a valid event extender object!'); debug(err); throw err; } if (this.preEventExtenders.indexOf(preEventExtender) < 0) { preEventExtender.useCollection(this); this.preEventExtenders.push(preEventExtender); } }
[ "function", "(", "preEventExtender", ")", "{", "if", "(", "!", "preEventExtender", "||", "!", "_", ".", "isObject", "(", "preEventExtender", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please inject a valid event extender object!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "if", "(", "this", ".", "preEventExtenders", ".", "indexOf", "(", "preEventExtender", ")", "<", "0", ")", "{", "preEventExtender", ".", "useCollection", "(", "this", ")", ";", "this", ".", "preEventExtenders", ".", "push", "(", "preEventExtender", ")", ";", "}", "}" ]
Add preEventExtender module. @param {PreEventExtender} preEventExtender The preEventExtender module to be injected.
[ "Add", "preEventExtender", "module", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/collection.js#L95-L105
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/collection.js
function (query) { if (!query || !_.isObject(query)) { return this.viewBuilders; } query.name = query.name || ''; query.version = query.version || 0; query.aggregate = query.aggregate || null; query.context = query.context || null; var found = _.filter(this.viewBuilders, function (vB) { return vB.name === query.name && (vB.version === query.version || vB.version === -1) && (vB.aggregate === query.aggregate) && (vB.context === query.context); }); if (found.length !== 0) { return found; } found = _.filter(this.viewBuilders, function (vB) { return vB.name === query.name && (vB.version === query.version || vB.version === -1) && (vB.aggregate === query.aggregate) && (vB.context === query.context || !query.context); }); if (found.length !== 0) { return found; } found = _.filter(this.viewBuilders, function (vB) { return vB.name === query.name && (vB.version === query.version || vB.version === -1) && (vB.aggregate === query.aggregate || !query.aggregate) && (vB.context === query.context || !query.context); }); if (found.length !== 0) { return found; } return _.filter(this.viewBuilders, function (vB) { return vB.name === '' && (vB.version === query.version || vB.version === -1) && (vB.aggregate === query.aggregate || !query.aggregate) && (vB.context === query.context || !query.context); }); }
javascript
function (query) { if (!query || !_.isObject(query)) { return this.viewBuilders; } query.name = query.name || ''; query.version = query.version || 0; query.aggregate = query.aggregate || null; query.context = query.context || null; var found = _.filter(this.viewBuilders, function (vB) { return vB.name === query.name && (vB.version === query.version || vB.version === -1) && (vB.aggregate === query.aggregate) && (vB.context === query.context); }); if (found.length !== 0) { return found; } found = _.filter(this.viewBuilders, function (vB) { return vB.name === query.name && (vB.version === query.version || vB.version === -1) && (vB.aggregate === query.aggregate) && (vB.context === query.context || !query.context); }); if (found.length !== 0) { return found; } found = _.filter(this.viewBuilders, function (vB) { return vB.name === query.name && (vB.version === query.version || vB.version === -1) && (vB.aggregate === query.aggregate || !query.aggregate) && (vB.context === query.context || !query.context); }); if (found.length !== 0) { return found; } return _.filter(this.viewBuilders, function (vB) { return vB.name === '' && (vB.version === query.version || vB.version === -1) && (vB.aggregate === query.aggregate || !query.aggregate) && (vB.context === query.context || !query.context); }); }
[ "function", "(", "query", ")", "{", "if", "(", "!", "query", "||", "!", "_", ".", "isObject", "(", "query", ")", ")", "{", "return", "this", ".", "viewBuilders", ";", "}", "query", ".", "name", "=", "query", ".", "name", "||", "''", ";", "query", ".", "version", "=", "query", ".", "version", "||", "0", ";", "query", ".", "aggregate", "=", "query", ".", "aggregate", "||", "null", ";", "query", ".", "context", "=", "query", ".", "context", "||", "null", ";", "var", "found", "=", "_", ".", "filter", "(", "this", ".", "viewBuilders", ",", "function", "(", "vB", ")", "{", "return", "vB", ".", "name", "===", "query", ".", "name", "&&", "(", "vB", ".", "version", "===", "query", ".", "version", "||", "vB", ".", "version", "===", "-", "1", ")", "&&", "(", "vB", ".", "aggregate", "===", "query", ".", "aggregate", ")", "&&", "(", "vB", ".", "context", "===", "query", ".", "context", ")", ";", "}", ")", ";", "if", "(", "found", ".", "length", "!==", "0", ")", "{", "return", "found", ";", "}", "found", "=", "_", ".", "filter", "(", "this", ".", "viewBuilders", ",", "function", "(", "vB", ")", "{", "return", "vB", ".", "name", "===", "query", ".", "name", "&&", "(", "vB", ".", "version", "===", "query", ".", "version", "||", "vB", ".", "version", "===", "-", "1", ")", "&&", "(", "vB", ".", "aggregate", "===", "query", ".", "aggregate", ")", "&&", "(", "vB", ".", "context", "===", "query", ".", "context", "||", "!", "query", ".", "context", ")", ";", "}", ")", ";", "if", "(", "found", ".", "length", "!==", "0", ")", "{", "return", "found", ";", "}", "found", "=", "_", ".", "filter", "(", "this", ".", "viewBuilders", ",", "function", "(", "vB", ")", "{", "return", "vB", ".", "name", "===", "query", ".", "name", "&&", "(", "vB", ".", "version", "===", "query", ".", "version", "||", "vB", ".", "version", "===", "-", "1", ")", "&&", "(", "vB", ".", "aggregate", "===", "query", ".", "aggregate", "||", "!", "query", ".", "aggregate", ")", "&&", "(", "vB", ".", "context", "===", "query", ".", "context", "||", "!", "query", ".", "context", ")", ";", "}", ")", ";", "if", "(", "found", ".", "length", "!==", "0", ")", "{", "return", "found", ";", "}", "return", "_", ".", "filter", "(", "this", ".", "viewBuilders", ",", "function", "(", "vB", ")", "{", "return", "vB", ".", "name", "===", "''", "&&", "(", "vB", ".", "version", "===", "query", ".", "version", "||", "vB", ".", "version", "===", "-", "1", ")", "&&", "(", "vB", ".", "aggregate", "===", "query", ".", "aggregate", "||", "!", "query", ".", "aggregate", ")", "&&", "(", "vB", ".", "context", "===", "query", ".", "context", "||", "!", "query", ".", "context", ")", ";", "}", ")", ";", "}" ]
Returns the viewBuilder module by query. @param {Object} query The query object. [optional] If not passed, all viewBuilders will be returned. @returns {Array}
[ "Returns", "the", "viewBuilder", "module", "by", "query", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/collection.js#L111-L152
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/collection.js
function (query) { if (!query || !_.isObject(query)) { var err = new Error('Please pass a valid query object!'); debug(err); throw err; } query.name = query.name || ''; query.version = query.version || 0; query.aggregate = query.aggregate || null; query.context = query.context || null; var found = _.find(this.eventExtenders, function (evExt) { return evExt.name === query.name && (evExt.version === query.version || evExt.version === -1) && (evExt.aggregate === query.aggregate) && (evExt.context === query.context); }); if (found) { return found; } found = _.find(this.eventExtenders, function (evExt) { return evExt.name === query.name && (evExt.version === query.version || evExt.version === -1) && (evExt.aggregate === query.aggregate || !query.aggregate || !evExt.aggregate) && (evExt.context === query.context); }); if (found) { return found; } found = _.find(this.eventExtenders, function (evExt) { return evExt.name === query.name && (evExt.version === query.version || evExt.version === -1) && (evExt.aggregate === query.aggregate || !query.aggregate || !evExt.aggregate) && (evExt.context === query.context || !query.context || !evExt.context); }); if (found) { return found; } return _.find(this.eventExtenders, function (evExt) { return evExt.name === '' && (evExt.version === query.version || evExt.version === -1) && (evExt.aggregate === query.aggregate || !query.aggregate || !evExt.aggregate) && (evExt.context === query.context || !query.context || !evExt.context); }); }
javascript
function (query) { if (!query || !_.isObject(query)) { var err = new Error('Please pass a valid query object!'); debug(err); throw err; } query.name = query.name || ''; query.version = query.version || 0; query.aggregate = query.aggregate || null; query.context = query.context || null; var found = _.find(this.eventExtenders, function (evExt) { return evExt.name === query.name && (evExt.version === query.version || evExt.version === -1) && (evExt.aggregate === query.aggregate) && (evExt.context === query.context); }); if (found) { return found; } found = _.find(this.eventExtenders, function (evExt) { return evExt.name === query.name && (evExt.version === query.version || evExt.version === -1) && (evExt.aggregate === query.aggregate || !query.aggregate || !evExt.aggregate) && (evExt.context === query.context); }); if (found) { return found; } found = _.find(this.eventExtenders, function (evExt) { return evExt.name === query.name && (evExt.version === query.version || evExt.version === -1) && (evExt.aggregate === query.aggregate || !query.aggregate || !evExt.aggregate) && (evExt.context === query.context || !query.context || !evExt.context); }); if (found) { return found; } return _.find(this.eventExtenders, function (evExt) { return evExt.name === '' && (evExt.version === query.version || evExt.version === -1) && (evExt.aggregate === query.aggregate || !query.aggregate || !evExt.aggregate) && (evExt.context === query.context || !query.context || !evExt.context); }); }
[ "function", "(", "query", ")", "{", "if", "(", "!", "query", "||", "!", "_", ".", "isObject", "(", "query", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass a valid query object!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "query", ".", "name", "=", "query", ".", "name", "||", "''", ";", "query", ".", "version", "=", "query", ".", "version", "||", "0", ";", "query", ".", "aggregate", "=", "query", ".", "aggregate", "||", "null", ";", "query", ".", "context", "=", "query", ".", "context", "||", "null", ";", "var", "found", "=", "_", ".", "find", "(", "this", ".", "eventExtenders", ",", "function", "(", "evExt", ")", "{", "return", "evExt", ".", "name", "===", "query", ".", "name", "&&", "(", "evExt", ".", "version", "===", "query", ".", "version", "||", "evExt", ".", "version", "===", "-", "1", ")", "&&", "(", "evExt", ".", "aggregate", "===", "query", ".", "aggregate", ")", "&&", "(", "evExt", ".", "context", "===", "query", ".", "context", ")", ";", "}", ")", ";", "if", "(", "found", ")", "{", "return", "found", ";", "}", "found", "=", "_", ".", "find", "(", "this", ".", "eventExtenders", ",", "function", "(", "evExt", ")", "{", "return", "evExt", ".", "name", "===", "query", ".", "name", "&&", "(", "evExt", ".", "version", "===", "query", ".", "version", "||", "evExt", ".", "version", "===", "-", "1", ")", "&&", "(", "evExt", ".", "aggregate", "===", "query", ".", "aggregate", "||", "!", "query", ".", "aggregate", "||", "!", "evExt", ".", "aggregate", ")", "&&", "(", "evExt", ".", "context", "===", "query", ".", "context", ")", ";", "}", ")", ";", "if", "(", "found", ")", "{", "return", "found", ";", "}", "found", "=", "_", ".", "find", "(", "this", ".", "eventExtenders", ",", "function", "(", "evExt", ")", "{", "return", "evExt", ".", "name", "===", "query", ".", "name", "&&", "(", "evExt", ".", "version", "===", "query", ".", "version", "||", "evExt", ".", "version", "===", "-", "1", ")", "&&", "(", "evExt", ".", "aggregate", "===", "query", ".", "aggregate", "||", "!", "query", ".", "aggregate", "||", "!", "evExt", ".", "aggregate", ")", "&&", "(", "evExt", ".", "context", "===", "query", ".", "context", "||", "!", "query", ".", "context", "||", "!", "evExt", ".", "context", ")", ";", "}", ")", ";", "if", "(", "found", ")", "{", "return", "found", ";", "}", "return", "_", ".", "find", "(", "this", ".", "eventExtenders", ",", "function", "(", "evExt", ")", "{", "return", "evExt", ".", "name", "===", "''", "&&", "(", "evExt", ".", "version", "===", "query", ".", "version", "||", "evExt", ".", "version", "===", "-", "1", ")", "&&", "(", "evExt", ".", "aggregate", "===", "query", ".", "aggregate", "||", "!", "query", ".", "aggregate", "||", "!", "evExt", ".", "aggregate", ")", "&&", "(", "evExt", ".", "context", "===", "query", ".", "context", "||", "!", "query", ".", "context", "||", "!", "evExt", ".", "context", ")", ";", "}", ")", ";", "}" ]
Returns the eventExtender module by query. @param {Object} query The query object. @returns {EventExtender}
[ "Returns", "the", "eventExtender", "module", "by", "query", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/collection.js#L158-L201
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/collection.js
function (callback) { this.repository.getNewId(function(err, newId) { if (err) { debug(err); return callback(err); } callback(null, newId); }); }
javascript
function (callback) { this.repository.getNewId(function(err, newId) { if (err) { debug(err); return callback(err); } callback(null, newId); }); }
[ "function", "(", "callback", ")", "{", "this", ".", "repository", ".", "getNewId", "(", "function", "(", "err", ",", "newId", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "callback", "(", "null", ",", "newId", ")", ";", "}", ")", ";", "}" ]
Use this function to obtain a new id. @param {Function} callback The function, that will be called when the this action is completed. `function(err, id){}` id is of type String.
[ "Use", "this", "function", "to", "obtain", "a", "new", "id", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/collection.js#L270-L278
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/collection.js
function (vm, callback) { if (this.isReplaying) { vm.actionOnCommitForReplay = vm.actionOnCommit; // Clone the values to be sure no reference mistakes happen! if (vm.attributes) { var flatAttr = flatten(vm.attributes); var undefines = []; _.each(flatAttr, function (v, k) { if (v === undefined) { undefines.push(k); } }); vm.attributes = vm.toJSON(); _.each(undefines, function (k) { vm.set(k, undefined); }); } this.replayingVms[vm.id] = vm; if (vm.actionOnCommit === 'delete') { delete this.replayingVms[vm.id]; if (!this.replayingVmsToDelete[vm.id]) this.replayingVmsToDelete[vm.id] = vm; } if (vm.actionOnCommit === 'create') { vm.actionOnCommit = 'update'; } return callback(null); } this.repository.commit(vm, callback); }
javascript
function (vm, callback) { if (this.isReplaying) { vm.actionOnCommitForReplay = vm.actionOnCommit; // Clone the values to be sure no reference mistakes happen! if (vm.attributes) { var flatAttr = flatten(vm.attributes); var undefines = []; _.each(flatAttr, function (v, k) { if (v === undefined) { undefines.push(k); } }); vm.attributes = vm.toJSON(); _.each(undefines, function (k) { vm.set(k, undefined); }); } this.replayingVms[vm.id] = vm; if (vm.actionOnCommit === 'delete') { delete this.replayingVms[vm.id]; if (!this.replayingVmsToDelete[vm.id]) this.replayingVmsToDelete[vm.id] = vm; } if (vm.actionOnCommit === 'create') { vm.actionOnCommit = 'update'; } return callback(null); } this.repository.commit(vm, callback); }
[ "function", "(", "vm", ",", "callback", ")", "{", "if", "(", "this", ".", "isReplaying", ")", "{", "vm", ".", "actionOnCommitForReplay", "=", "vm", ".", "actionOnCommit", ";", "if", "(", "vm", ".", "attributes", ")", "{", "var", "flatAttr", "=", "flatten", "(", "vm", ".", "attributes", ")", ";", "var", "undefines", "=", "[", "]", ";", "_", ".", "each", "(", "flatAttr", ",", "function", "(", "v", ",", "k", ")", "{", "if", "(", "v", "===", "undefined", ")", "{", "undefines", ".", "push", "(", "k", ")", ";", "}", "}", ")", ";", "vm", ".", "attributes", "=", "vm", ".", "toJSON", "(", ")", ";", "_", ".", "each", "(", "undefines", ",", "function", "(", "k", ")", "{", "vm", ".", "set", "(", "k", ",", "undefined", ")", ";", "}", ")", ";", "}", "this", ".", "replayingVms", "[", "vm", ".", "id", "]", "=", "vm", ";", "if", "(", "vm", ".", "actionOnCommit", "===", "'delete'", ")", "{", "delete", "this", ".", "replayingVms", "[", "vm", ".", "id", "]", ";", "if", "(", "!", "this", ".", "replayingVmsToDelete", "[", "vm", ".", "id", "]", ")", "this", ".", "replayingVmsToDelete", "[", "vm", ".", "id", "]", "=", "vm", ";", "}", "if", "(", "vm", ".", "actionOnCommit", "===", "'create'", ")", "{", "vm", ".", "actionOnCommit", "=", "'update'", ";", "}", "return", "callback", "(", "null", ")", ";", "}", "this", ".", "repository", ".", "commit", "(", "vm", ",", "callback", ")", ";", "}" ]
Save the passed viewModel object in the read model. @param {Object} vm The viewModel object. @param {Function} callback The function, that will be called when the this action is completed. [optional] `function(err){}`
[ "Save", "the", "passed", "viewModel", "object", "in", "the", "read", "model", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/collection.js#L285-L314
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/collection.js
function (id, callback) { if (this.isReplaying) { if (this.replayingVms[id]) { return callback(null, this.replayingVms[id]); } if (this.replayingVmsToDelete[id]) { var vm = new viewmodel.ViewModel({ id: id }, this.repository); var clonedInitValues = _.cloneDeep(this.modelInitValues); for (var prop in clonedInitValues) { if (!vm.has(prop)) { vm.set(prop, clonedInitValues[prop]); } } this.replayingVms[vm.id] = vm; return callback(null, this.replayingVms[id]); } } var self = this; this.repository.get(id, function(err, vm) { if (err) { debug(err); return callback(err); } if (!vm) { err = new Error('No vm object returned!'); debug(err); return callback(err); } var clonedInitValues = _.cloneDeep(self.modelInitValues); for (var prop in clonedInitValues) { if (!vm.has(prop)) { vm.set(prop, clonedInitValues[prop]); } } if (self.isReplaying) { if (!self.replayingVms[vm.id]) { self.replayingVms[vm.id] = vm; } return callback(null, self.replayingVms[vm.id]); } callback(null, vm); }); }
javascript
function (id, callback) { if (this.isReplaying) { if (this.replayingVms[id]) { return callback(null, this.replayingVms[id]); } if (this.replayingVmsToDelete[id]) { var vm = new viewmodel.ViewModel({ id: id }, this.repository); var clonedInitValues = _.cloneDeep(this.modelInitValues); for (var prop in clonedInitValues) { if (!vm.has(prop)) { vm.set(prop, clonedInitValues[prop]); } } this.replayingVms[vm.id] = vm; return callback(null, this.replayingVms[id]); } } var self = this; this.repository.get(id, function(err, vm) { if (err) { debug(err); return callback(err); } if (!vm) { err = new Error('No vm object returned!'); debug(err); return callback(err); } var clonedInitValues = _.cloneDeep(self.modelInitValues); for (var prop in clonedInitValues) { if (!vm.has(prop)) { vm.set(prop, clonedInitValues[prop]); } } if (self.isReplaying) { if (!self.replayingVms[vm.id]) { self.replayingVms[vm.id] = vm; } return callback(null, self.replayingVms[vm.id]); } callback(null, vm); }); }
[ "function", "(", "id", ",", "callback", ")", "{", "if", "(", "this", ".", "isReplaying", ")", "{", "if", "(", "this", ".", "replayingVms", "[", "id", "]", ")", "{", "return", "callback", "(", "null", ",", "this", ".", "replayingVms", "[", "id", "]", ")", ";", "}", "if", "(", "this", ".", "replayingVmsToDelete", "[", "id", "]", ")", "{", "var", "vm", "=", "new", "viewmodel", ".", "ViewModel", "(", "{", "id", ":", "id", "}", ",", "this", ".", "repository", ")", ";", "var", "clonedInitValues", "=", "_", ".", "cloneDeep", "(", "this", ".", "modelInitValues", ")", ";", "for", "(", "var", "prop", "in", "clonedInitValues", ")", "{", "if", "(", "!", "vm", ".", "has", "(", "prop", ")", ")", "{", "vm", ".", "set", "(", "prop", ",", "clonedInitValues", "[", "prop", "]", ")", ";", "}", "}", "this", ".", "replayingVms", "[", "vm", ".", "id", "]", "=", "vm", ";", "return", "callback", "(", "null", ",", "this", ".", "replayingVms", "[", "id", "]", ")", ";", "}", "}", "var", "self", "=", "this", ";", "this", ".", "repository", ".", "get", "(", "id", ",", "function", "(", "err", ",", "vm", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "if", "(", "!", "vm", ")", "{", "err", "=", "new", "Error", "(", "'No vm object returned!'", ")", ";", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "var", "clonedInitValues", "=", "_", ".", "cloneDeep", "(", "self", ".", "modelInitValues", ")", ";", "for", "(", "var", "prop", "in", "clonedInitValues", ")", "{", "if", "(", "!", "vm", ".", "has", "(", "prop", ")", ")", "{", "vm", ".", "set", "(", "prop", ",", "clonedInitValues", "[", "prop", "]", ")", ";", "}", "}", "if", "(", "self", ".", "isReplaying", ")", "{", "if", "(", "!", "self", ".", "replayingVms", "[", "vm", ".", "id", "]", ")", "{", "self", ".", "replayingVms", "[", "vm", ".", "id", "]", "=", "vm", ";", "}", "return", "callback", "(", "null", ",", "self", ".", "replayingVms", "[", "vm", ".", "id", "]", ")", ";", "}", "callback", "(", "null", ",", "vm", ")", ";", "}", ")", ";", "}" ]
Loads a viewModel object by id. @param {String} id The viewModel id. @param {Function} callback The function, that will be called when the this action is completed. `function(err, vm){}` vm is of type Object
[ "Loads", "a", "viewModel", "object", "by", "id", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/collection.js#L321-L363
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/collection.js
function (id, callback) { this.loadViewModel(id, function (err, vm) { if (err) { return callback(err); } if (!vm || vm.actionOnCommit === 'create') { return callback(null, null); } callback(null, vm); }); }
javascript
function (id, callback) { this.loadViewModel(id, function (err, vm) { if (err) { return callback(err); } if (!vm || vm.actionOnCommit === 'create') { return callback(null, null); } callback(null, vm); }); }
[ "function", "(", "id", ",", "callback", ")", "{", "this", ".", "loadViewModel", "(", "id", ",", "function", "(", "err", ",", "vm", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "if", "(", "!", "vm", "||", "vm", ".", "actionOnCommit", "===", "'create'", ")", "{", "return", "callback", "(", "null", ",", "null", ")", ";", "}", "callback", "(", "null", ",", "vm", ")", ";", "}", ")", ";", "}" ]
Loads a viewModel object by id if exists. @param {String} id The viewModel id. @param {Function} callback The function, that will be called when the this action is completed. `function(err, vm){}` vm is of type Object or null
[ "Loads", "a", "viewModel", "object", "by", "id", "if", "exists", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/collection.js#L370-L382
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/collection.js
function (callback) { if (!this.isReplaying) { var err = new Error('Not in replay mode!'); debug(err); return callback(err); } var replVms = _.values(this.replayingVms); var replVmsToDelete = _.values(this.replayingVmsToDelete); var self = this; function commit (vm, callback) { if (!vm.actionOnCommitForReplay) { return callback(null); } vm.actionOnCommit = vm.actionOnCommitForReplay; delete vm.actionOnCommitForReplay; self.repository.commit(vm, function (err) { if (err) { debug(err); debug(vm); } callback(err); }); } function prepareVmsForBulkCommit (vms) { return _.map(_.filter(vms, function(vm) { return vm.actionOnCommitForReplay }), function (vm) { vm.actionOnCommit = vm.actionOnCommitForReplay; delete vm.actionOnCommitForReplay; return vm; }) } function bulkCommit (vms, callback) { if (vms.length === 0) return callback(null); self.repository.bulkCommit(prepareVmsForBulkCommit(vms), function (err) { if (err) { debug(err); } callback(err); }); } async.series([ function (callback) { if (self.repository.bulkCommit) { return bulkCommit(replVmsToDelete, callback); } async.each(replVmsToDelete, commit, callback); }, function (callback) { if (self.repository.bulkCommit) { return bulkCommit(replVms, callback); } async.each(replVms, commit, callback); } ], function (err) { if (err) { debug(err); } self.replayingVms = {}; self.replayingVmsToDelete = {}; self.isReplaying = false; callback(err); }); }
javascript
function (callback) { if (!this.isReplaying) { var err = new Error('Not in replay mode!'); debug(err); return callback(err); } var replVms = _.values(this.replayingVms); var replVmsToDelete = _.values(this.replayingVmsToDelete); var self = this; function commit (vm, callback) { if (!vm.actionOnCommitForReplay) { return callback(null); } vm.actionOnCommit = vm.actionOnCommitForReplay; delete vm.actionOnCommitForReplay; self.repository.commit(vm, function (err) { if (err) { debug(err); debug(vm); } callback(err); }); } function prepareVmsForBulkCommit (vms) { return _.map(_.filter(vms, function(vm) { return vm.actionOnCommitForReplay }), function (vm) { vm.actionOnCommit = vm.actionOnCommitForReplay; delete vm.actionOnCommitForReplay; return vm; }) } function bulkCommit (vms, callback) { if (vms.length === 0) return callback(null); self.repository.bulkCommit(prepareVmsForBulkCommit(vms), function (err) { if (err) { debug(err); } callback(err); }); } async.series([ function (callback) { if (self.repository.bulkCommit) { return bulkCommit(replVmsToDelete, callback); } async.each(replVmsToDelete, commit, callback); }, function (callback) { if (self.repository.bulkCommit) { return bulkCommit(replVms, callback); } async.each(replVms, commit, callback); } ], function (err) { if (err) { debug(err); } self.replayingVms = {}; self.replayingVmsToDelete = {}; self.isReplaying = false; callback(err); }); }
[ "function", "(", "callback", ")", "{", "if", "(", "!", "this", ".", "isReplaying", ")", "{", "var", "err", "=", "new", "Error", "(", "'Not in replay mode!'", ")", ";", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "var", "replVms", "=", "_", ".", "values", "(", "this", ".", "replayingVms", ")", ";", "var", "replVmsToDelete", "=", "_", ".", "values", "(", "this", ".", "replayingVmsToDelete", ")", ";", "var", "self", "=", "this", ";", "function", "commit", "(", "vm", ",", "callback", ")", "{", "if", "(", "!", "vm", ".", "actionOnCommitForReplay", ")", "{", "return", "callback", "(", "null", ")", ";", "}", "vm", ".", "actionOnCommit", "=", "vm", ".", "actionOnCommitForReplay", ";", "delete", "vm", ".", "actionOnCommitForReplay", ";", "self", ".", "repository", ".", "commit", "(", "vm", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "debug", "(", "vm", ")", ";", "}", "callback", "(", "err", ")", ";", "}", ")", ";", "}", "function", "prepareVmsForBulkCommit", "(", "vms", ")", "{", "return", "_", ".", "map", "(", "_", ".", "filter", "(", "vms", ",", "function", "(", "vm", ")", "{", "return", "vm", ".", "actionOnCommitForReplay", "}", ")", ",", "function", "(", "vm", ")", "{", "vm", ".", "actionOnCommit", "=", "vm", ".", "actionOnCommitForReplay", ";", "delete", "vm", ".", "actionOnCommitForReplay", ";", "return", "vm", ";", "}", ")", "}", "function", "bulkCommit", "(", "vms", ",", "callback", ")", "{", "if", "(", "vms", ".", "length", "===", "0", ")", "return", "callback", "(", "null", ")", ";", "self", ".", "repository", ".", "bulkCommit", "(", "prepareVmsForBulkCommit", "(", "vms", ")", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "}", "callback", "(", "err", ")", ";", "}", ")", ";", "}", "async", ".", "series", "(", "[", "function", "(", "callback", ")", "{", "if", "(", "self", ".", "repository", ".", "bulkCommit", ")", "{", "return", "bulkCommit", "(", "replVmsToDelete", ",", "callback", ")", ";", "}", "async", ".", "each", "(", "replVmsToDelete", ",", "commit", ",", "callback", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "if", "(", "self", ".", "repository", ".", "bulkCommit", ")", "{", "return", "bulkCommit", "(", "replVms", ",", "callback", ")", ";", "}", "async", ".", "each", "(", "replVms", ",", "commit", ",", "callback", ")", ";", "}", "]", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "}", "self", ".", "replayingVms", "=", "{", "}", ";", "self", ".", "replayingVmsToDelete", "=", "{", "}", ";", "self", ".", "isReplaying", "=", "false", ";", "callback", "(", "err", ")", ";", "}", ")", ";", "}" ]
Saves all replaying viewmodels. @param {Function} callback The function, that will be called when the this action is completed. `function(err){}`
[ "Saves", "all", "replaying", "viewmodels", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/collection.js#L450-L515
train
ChristianRich/phone-number-extractor
lib/rule.js
function(name, data, testFunction){ if(!_.isString(name)){ throw new Error('String expected for parameter name'); } if(!_.isArray(data)){ throw new Error('Array expected for parameter data'); } if(!_.isFunction(testFunction)){ throw new Error('Function expected for parameter testFunction'); } this._name = name; this._testFunction = testFunction; this._res = []; this._data = data; this._itr = 0; }
javascript
function(name, data, testFunction){ if(!_.isString(name)){ throw new Error('String expected for parameter name'); } if(!_.isArray(data)){ throw new Error('Array expected for parameter data'); } if(!_.isFunction(testFunction)){ throw new Error('Function expected for parameter testFunction'); } this._name = name; this._testFunction = testFunction; this._res = []; this._data = data; this._itr = 0; }
[ "function", "(", "name", ",", "data", ",", "testFunction", ")", "{", "if", "(", "!", "_", ".", "isString", "(", "name", ")", ")", "{", "throw", "new", "Error", "(", "'String expected for parameter name'", ")", ";", "}", "if", "(", "!", "_", ".", "isArray", "(", "data", ")", ")", "{", "throw", "new", "Error", "(", "'Array expected for parameter data'", ")", ";", "}", "if", "(", "!", "_", ".", "isFunction", "(", "testFunction", ")", ")", "{", "throw", "new", "Error", "(", "'Function expected for parameter testFunction'", ")", ";", "}", "this", ".", "_name", "=", "name", ";", "this", ".", "_testFunction", "=", "testFunction", ";", "this", ".", "_res", "=", "[", "]", ";", "this", ".", "_data", "=", "data", ";", "this", ".", "_itr", "=", "0", ";", "}" ]
Encapsulate rules for identifying phone numbers @param {string }name - Name of the rule @param {array} data - The array of numbers to be examined @param {function} testFunction - The rule where the number crunching happens @constructor
[ "Encapsulate", "rules", "for", "identifying", "phone", "numbers" ]
6458e9177f2c59e3bc6377adec60042f24c21f3d
https://github.com/ChristianRich/phone-number-extractor/blob/6458e9177f2c59e3bc6377adec60042f24c21f3d/lib/rule.js#L10-L29
train
ChristianRich/phone-number-extractor
lib/rule.js
function(callback){ for(this._itr; this._itr < this._data.length; this._itr++) { this._testFunction.call(this, this._itr); } callback.call(this, this._res); }
javascript
function(callback){ for(this._itr; this._itr < this._data.length; this._itr++) { this._testFunction.call(this, this._itr); } callback.call(this, this._res); }
[ "function", "(", "callback", ")", "{", "for", "(", "this", ".", "_itr", ";", "this", ".", "_itr", "<", "this", ".", "_data", ".", "length", ";", "this", ".", "_itr", "++", ")", "{", "this", ".", "_testFunction", ".", "call", "(", "this", ",", "this", ".", "_itr", ")", ";", "}", "callback", ".", "call", "(", "this", ",", "this", ".", "_res", ")", ";", "}" ]
Execute the rules one by one @param {function} callback @return {void}
[ "Execute", "the", "rules", "one", "by", "one" ]
6458e9177f2c59e3bc6377adec60042f24c21f3d
https://github.com/ChristianRich/phone-number-extractor/blob/6458e9177f2c59e3bc6377adec60042f24c21f3d/lib/rule.js#L38-L44
train
ChristianRich/phone-number-extractor
lib/locale/AU.js
function(s){ if (s.substr(0, 2) === '02' || s.substr(0, 2) === '03' || s.substr(0, 2) === '04' || s.substr(0, 2) === '07' || s.substr(0, 2) === '08') return true; return (s.substr(0, 2) === '61') || (s.substr(0, 4) === '0061'); }
javascript
function(s){ if (s.substr(0, 2) === '02' || s.substr(0, 2) === '03' || s.substr(0, 2) === '04' || s.substr(0, 2) === '07' || s.substr(0, 2) === '08') return true; return (s.substr(0, 2) === '61') || (s.substr(0, 4) === '0061'); }
[ "function", "(", "s", ")", "{", "if", "(", "s", ".", "substr", "(", "0", ",", "2", ")", "===", "'02'", "||", "s", ".", "substr", "(", "0", ",", "2", ")", "===", "'03'", "||", "s", ".", "substr", "(", "0", ",", "2", ")", "===", "'04'", "||", "s", ".", "substr", "(", "0", ",", "2", ")", "===", "'07'", "||", "s", ".", "substr", "(", "0", ",", "2", ")", "===", "'08'", ")", "return", "true", ";", "return", "(", "s", ".", "substr", "(", "0", ",", "2", ")", "===", "'61'", ")", "||", "(", "s", ".", "substr", "(", "0", ",", "4", ")", "===", "'0061'", ")", ";", "}" ]
Returns true if the area code or prefix exhibits AU number characteristics @param {string} s @returns {boolean}
[ "Returns", "true", "if", "the", "area", "code", "or", "prefix", "exhibits", "AU", "number", "characteristics" ]
6458e9177f2c59e3bc6377adec60042f24c21f3d
https://github.com/ChristianRich/phone-number-extractor/blob/6458e9177f2c59e3bc6377adec60042f24c21f3d/lib/locale/AU.js#L16-L19
train
ChristianRich/phone-number-extractor
lib/locale/AU.js
function(n){ // Examine international prefix if(n.substr(0,2) === '61'){ return n.length === 11; } // Examine international prefix if(n.substr(0,4) === '0061'){ return n.length === 13; } // Examine number of digits return n.length === 10; }
javascript
function(n){ // Examine international prefix if(n.substr(0,2) === '61'){ return n.length === 11; } // Examine international prefix if(n.substr(0,4) === '0061'){ return n.length === 13; } // Examine number of digits return n.length === 10; }
[ "function", "(", "n", ")", "{", "if", "(", "n", ".", "substr", "(", "0", ",", "2", ")", "===", "'61'", ")", "{", "return", "n", ".", "length", "===", "11", ";", "}", "if", "(", "n", ".", "substr", "(", "0", ",", "4", ")", "===", "'0061'", ")", "{", "return", "n", ".", "length", "===", "13", ";", "}", "return", "n", ".", "length", "===", "10", ";", "}" ]
Returns true if land line part of the number exhibits AU number characteristics @param {string} n @return {boolean}
[ "Returns", "true", "if", "land", "line", "part", "of", "the", "number", "exhibits", "AU", "number", "characteristics" ]
6458e9177f2c59e3bc6377adec60042f24c21f3d
https://github.com/ChristianRich/phone-number-extractor/blob/6458e9177f2c59e3bc6377adec60042f24c21f3d/lib/locale/AU.js#L26-L40
train
stimulant/ampm
model/serverState.js
function() { try { this.set(fs.existsSync(this._stateFile) ? JSON.parse(fs.readFileSync(this._stateFile)) : {}); } catch (e) {} }
javascript
function() { try { this.set(fs.existsSync(this._stateFile) ? JSON.parse(fs.readFileSync(this._stateFile)) : {}); } catch (e) {} }
[ "function", "(", ")", "{", "try", "{", "this", ".", "set", "(", "fs", ".", "existsSync", "(", "this", ".", "_stateFile", ")", "?", "JSON", ".", "parse", "(", "fs", ".", "readFileSync", "(", "this", ".", "_stateFile", ")", ")", ":", "{", "}", ")", ";", "}", "catch", "(", "e", ")", "{", "}", "}" ]
Decode the state file.
[ "Decode", "the", "state", "file", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/serverState.js#L19-L23
train
stimulant/ampm
model/serverState.js
function(key, value, callback) { if (this.get(key) == value) { return; } this.set(key, value); clearTimeout(this._saveTimeout); this._saveTimeout = setTimeout(_.bind(function() { fs.writeFile(this._stateFile, JSON.stringify(this.attributes, null, '\t'), _.bind(function() { logger.info(key + ' saved to ' + path.join(process.cwd(), this._stateFile)); while (this._callbacks && this._callbacks.length) { this._callbacks.shift()(); } }, this)); }, this), 1000); if (callback) { if (!this._callbacks) { this._callbacks = []; } this._callbacks.push(callback); } }
javascript
function(key, value, callback) { if (this.get(key) == value) { return; } this.set(key, value); clearTimeout(this._saveTimeout); this._saveTimeout = setTimeout(_.bind(function() { fs.writeFile(this._stateFile, JSON.stringify(this.attributes, null, '\t'), _.bind(function() { logger.info(key + ' saved to ' + path.join(process.cwd(), this._stateFile)); while (this._callbacks && this._callbacks.length) { this._callbacks.shift()(); } }, this)); }, this), 1000); if (callback) { if (!this._callbacks) { this._callbacks = []; } this._callbacks.push(callback); } }
[ "function", "(", "key", ",", "value", ",", "callback", ")", "{", "if", "(", "this", ".", "get", "(", "key", ")", "==", "value", ")", "{", "return", ";", "}", "this", ".", "set", "(", "key", ",", "value", ")", ";", "clearTimeout", "(", "this", ".", "_saveTimeout", ")", ";", "this", ".", "_saveTimeout", "=", "setTimeout", "(", "_", ".", "bind", "(", "function", "(", ")", "{", "fs", ".", "writeFile", "(", "this", ".", "_stateFile", ",", "JSON", ".", "stringify", "(", "this", ".", "attributes", ",", "null", ",", "'\\t'", ")", ",", "\\t", ")", ";", "}", ",", "this", ")", ",", "_", ".", "bind", "(", "function", "(", ")", "{", "logger", ".", "info", "(", "key", "+", "' saved to '", "+", "path", ".", "join", "(", "process", ".", "cwd", "(", ")", ",", "this", ".", "_stateFile", ")", ")", ";", "while", "(", "this", ".", "_callbacks", "&&", "this", ".", "_callbacks", ".", "length", ")", "{", "this", ".", "_callbacks", ".", "shift", "(", ")", "(", ")", ";", "}", "}", ",", "this", ")", ")", ";", "1000", "}" ]
Write to the state file.
[ "Write", "to", "the", "state", "file", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/serverState.js#L26-L49
train
stimulant/ampm
model/network.js
function(transport, message, info) { var e = message[0].replace('/', ''); var data = null; if (message[1]) { try { data = JSON.parse(message[1]); } catch (e) { logger.warn('OSC messages should be JSON'); } } transport.emit(e, data); }
javascript
function(transport, message, info) { var e = message[0].replace('/', ''); var data = null; if (message[1]) { try { data = JSON.parse(message[1]); } catch (e) { logger.warn('OSC messages should be JSON'); } } transport.emit(e, data); }
[ "function", "(", "transport", ",", "message", ",", "info", ")", "{", "var", "e", "=", "message", "[", "0", "]", ".", "replace", "(", "'/'", ",", "''", ")", ";", "var", "data", "=", "null", ";", "if", "(", "message", "[", "1", "]", ")", "{", "try", "{", "data", "=", "JSON", ".", "parse", "(", "message", "[", "1", "]", ")", ";", "}", "catch", "(", "e", ")", "{", "logger", ".", "warn", "(", "'OSC messages should be JSON'", ")", ";", "}", "}", "transport", ".", "emit", "(", "e", ",", "data", ")", ";", "}" ]
Generic handler to decode and re-post OSC messages as native events.
[ "Generic", "handler", "to", "decode", "and", "re", "-", "post", "OSC", "messages", "as", "native", "events", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/network.js#L164-L177
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/viewBuilder.js
function (evt, vm) { var notification = {}; // event if (!!this.definitions.notification.meta && !!this.definitions.event.meta) { dotty.put(notification, this.definitions.notification.meta, _.cloneDeep(dotty.get(evt, this.definitions.event.meta))); } if (!!this.definitions.notification.eventId && !!this.definitions.event.id) { dotty.put(notification, this.definitions.notification.eventId, dotty.get(evt, this.definitions.event.id)); } if (!!this.definitions.notification.event && !!this.definitions.event.name) { dotty.put(notification, this.definitions.notification.event, dotty.get(evt, this.definitions.event.name)); } if (!!this.definitions.notification.aggregateId && !!this.definitions.event.aggregateId) { dotty.put(notification, this.definitions.notification.aggregateId, dotty.get(evt, this.definitions.event.aggregateId)); } if (!!this.definitions.notification.aggregate && !!this.definitions.event.aggregate) { dotty.put(notification, this.definitions.notification.aggregate, dotty.get(evt, this.definitions.event.aggregate)); } if (!!this.definitions.notification.context && !!this.definitions.event.context) { dotty.put(notification, this.definitions.notification.context, dotty.get(evt, this.definitions.event.context)); } if (!!this.definitions.notification.revision && !!this.definitions.event.revision) { dotty.put(notification, this.definitions.notification.revision, dotty.get(evt, this.definitions.event.revision)); } dotty.put(notification, this.definitions.notification.correlationId, dotty.get(evt, this.definitions.event.correlationId)); // vm dotty.put(notification, this.definitions.notification.payload, vm.toJSON()); dotty.put(notification, this.definitions.notification.collection, this.collection.name); dotty.put(notification, this.definitions.notification.action, vm.actionOnCommit); return notification; }
javascript
function (evt, vm) { var notification = {}; // event if (!!this.definitions.notification.meta && !!this.definitions.event.meta) { dotty.put(notification, this.definitions.notification.meta, _.cloneDeep(dotty.get(evt, this.definitions.event.meta))); } if (!!this.definitions.notification.eventId && !!this.definitions.event.id) { dotty.put(notification, this.definitions.notification.eventId, dotty.get(evt, this.definitions.event.id)); } if (!!this.definitions.notification.event && !!this.definitions.event.name) { dotty.put(notification, this.definitions.notification.event, dotty.get(evt, this.definitions.event.name)); } if (!!this.definitions.notification.aggregateId && !!this.definitions.event.aggregateId) { dotty.put(notification, this.definitions.notification.aggregateId, dotty.get(evt, this.definitions.event.aggregateId)); } if (!!this.definitions.notification.aggregate && !!this.definitions.event.aggregate) { dotty.put(notification, this.definitions.notification.aggregate, dotty.get(evt, this.definitions.event.aggregate)); } if (!!this.definitions.notification.context && !!this.definitions.event.context) { dotty.put(notification, this.definitions.notification.context, dotty.get(evt, this.definitions.event.context)); } if (!!this.definitions.notification.revision && !!this.definitions.event.revision) { dotty.put(notification, this.definitions.notification.revision, dotty.get(evt, this.definitions.event.revision)); } dotty.put(notification, this.definitions.notification.correlationId, dotty.get(evt, this.definitions.event.correlationId)); // vm dotty.put(notification, this.definitions.notification.payload, vm.toJSON()); dotty.put(notification, this.definitions.notification.collection, this.collection.name); dotty.put(notification, this.definitions.notification.action, vm.actionOnCommit); return notification; }
[ "function", "(", "evt", ",", "vm", ")", "{", "var", "notification", "=", "{", "}", ";", "if", "(", "!", "!", "this", ".", "definitions", ".", "notification", ".", "meta", "&&", "!", "!", "this", ".", "definitions", ".", "event", ".", "meta", ")", "{", "dotty", ".", "put", "(", "notification", ",", "this", ".", "definitions", ".", "notification", ".", "meta", ",", "_", ".", "cloneDeep", "(", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "meta", ")", ")", ")", ";", "}", "if", "(", "!", "!", "this", ".", "definitions", ".", "notification", ".", "eventId", "&&", "!", "!", "this", ".", "definitions", ".", "event", ".", "id", ")", "{", "dotty", ".", "put", "(", "notification", ",", "this", ".", "definitions", ".", "notification", ".", "eventId", ",", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "id", ")", ")", ";", "}", "if", "(", "!", "!", "this", ".", "definitions", ".", "notification", ".", "event", "&&", "!", "!", "this", ".", "definitions", ".", "event", ".", "name", ")", "{", "dotty", ".", "put", "(", "notification", ",", "this", ".", "definitions", ".", "notification", ".", "event", ",", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "name", ")", ")", ";", "}", "if", "(", "!", "!", "this", ".", "definitions", ".", "notification", ".", "aggregateId", "&&", "!", "!", "this", ".", "definitions", ".", "event", ".", "aggregateId", ")", "{", "dotty", ".", "put", "(", "notification", ",", "this", ".", "definitions", ".", "notification", ".", "aggregateId", ",", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "aggregateId", ")", ")", ";", "}", "if", "(", "!", "!", "this", ".", "definitions", ".", "notification", ".", "aggregate", "&&", "!", "!", "this", ".", "definitions", ".", "event", ".", "aggregate", ")", "{", "dotty", ".", "put", "(", "notification", ",", "this", ".", "definitions", ".", "notification", ".", "aggregate", ",", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "aggregate", ")", ")", ";", "}", "if", "(", "!", "!", "this", ".", "definitions", ".", "notification", ".", "context", "&&", "!", "!", "this", ".", "definitions", ".", "event", ".", "context", ")", "{", "dotty", ".", "put", "(", "notification", ",", "this", ".", "definitions", ".", "notification", ".", "context", ",", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "context", ")", ")", ";", "}", "if", "(", "!", "!", "this", ".", "definitions", ".", "notification", ".", "revision", "&&", "!", "!", "this", ".", "definitions", ".", "event", ".", "revision", ")", "{", "dotty", ".", "put", "(", "notification", ",", "this", ".", "definitions", ".", "notification", ".", "revision", ",", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "revision", ")", ")", ";", "}", "dotty", ".", "put", "(", "notification", ",", "this", ".", "definitions", ".", "notification", ".", "correlationId", ",", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "correlationId", ")", ")", ";", "dotty", ".", "put", "(", "notification", ",", "this", ".", "definitions", ".", "notification", ".", "payload", ",", "vm", ".", "toJSON", "(", ")", ")", ";", "dotty", ".", "put", "(", "notification", ",", "this", ".", "definitions", ".", "notification", ".", "collection", ",", "this", ".", "collection", ".", "name", ")", ";", "dotty", ".", "put", "(", "notification", ",", "this", ".", "definitions", ".", "notification", ".", "action", ",", "vm", ".", "actionOnCommit", ")", ";", "return", "notification", ";", "}" ]
Generates a notification from event and viewModel. @param {Object} evt The event object. @param {Object} vm The viewModel. @returns {Object}
[ "Generates", "a", "notification", "from", "event", "and", "viewModel", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/viewBuilder.js#L222-L255
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/viewBuilder.js
function (evt, query, callback) { var self = this; this.findViewModels(query, function (err, vms) { if (err) { debug(err); return callback(err); } async.map(vms, function (vm, callback) { self.handleOne(vm, evt, function (err, notification) { if (err) { debug(err); return callback(err); } callback(null, notification); }); }, function (err, notifications) { if (err) { debug(err); return callback(err); } notifications = _.filter(notifications, function (n) { return !!n; }); callback(null, notifications); }); }); }
javascript
function (evt, query, callback) { var self = this; this.findViewModels(query, function (err, vms) { if (err) { debug(err); return callback(err); } async.map(vms, function (vm, callback) { self.handleOne(vm, evt, function (err, notification) { if (err) { debug(err); return callback(err); } callback(null, notification); }); }, function (err, notifications) { if (err) { debug(err); return callback(err); } notifications = _.filter(notifications, function (n) { return !!n; }); callback(null, notifications); }); }); }
[ "function", "(", "evt", ",", "query", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "this", ".", "findViewModels", "(", "query", ",", "function", "(", "err", ",", "vms", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "async", ".", "map", "(", "vms", ",", "function", "(", "vm", ",", "callback", ")", "{", "self", ".", "handleOne", "(", "vm", ",", "evt", ",", "function", "(", "err", ",", "notification", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "callback", "(", "null", ",", "notification", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ",", "notifications", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "notifications", "=", "_", ".", "filter", "(", "notifications", ",", "function", "(", "n", ")", "{", "return", "!", "!", "n", ";", "}", ")", ";", "callback", "(", "null", ",", "notifications", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Handles denormalization with a query instead of an id. @param {Object} evt The event object. @param {Object} query The query object. @param {Function} callback The function, that will be called when this action is completed. `function(err, notification){}`
[ "Handles", "denormalization", "with", "a", "query", "instead", "of", "an", "id", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/viewBuilder.js#L419-L449
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/viewBuilder.js
function (evt, callback) { var self = this; this.executeDenormFnForEach(evt, function (err, res) { if (err) { debug(err); return callback(err); } async.each(res, function (item, callback) { if (item.id) { return callback(null); } self.collection.getNewId(function (err, newId) { if (err) { return callback(err); } item.id = newId; callback(null); }); }, function (err) { if (err) { debug(err); return callback(err); } async.map(res, function (item, callback) { self.loadViewModel(item.id, function (err, vm) { if (err) { return callback(err); } self.handleOne(vm, evt, item, function (err, notification) { if (err) { return callback(err); } callback(null, notification); }); }); }, function (err, notis) { if (err) { debug(err); return callback(err); } callback(null, notis); }); }); }); }
javascript
function (evt, callback) { var self = this; this.executeDenormFnForEach(evt, function (err, res) { if (err) { debug(err); return callback(err); } async.each(res, function (item, callback) { if (item.id) { return callback(null); } self.collection.getNewId(function (err, newId) { if (err) { return callback(err); } item.id = newId; callback(null); }); }, function (err) { if (err) { debug(err); return callback(err); } async.map(res, function (item, callback) { self.loadViewModel(item.id, function (err, vm) { if (err) { return callback(err); } self.handleOne(vm, evt, item, function (err, notification) { if (err) { return callback(err); } callback(null, notification); }); }); }, function (err, notis) { if (err) { debug(err); return callback(err); } callback(null, notis); }); }); }); }
[ "function", "(", "evt", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "this", ".", "executeDenormFnForEach", "(", "evt", ",", "function", "(", "err", ",", "res", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "async", ".", "each", "(", "res", ",", "function", "(", "item", ",", "callback", ")", "{", "if", "(", "item", ".", "id", ")", "{", "return", "callback", "(", "null", ")", ";", "}", "self", ".", "collection", ".", "getNewId", "(", "function", "(", "err", ",", "newId", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "item", ".", "id", "=", "newId", ";", "callback", "(", "null", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "async", ".", "map", "(", "res", ",", "function", "(", "item", ",", "callback", ")", "{", "self", ".", "loadViewModel", "(", "item", ".", "id", ",", "function", "(", "err", ",", "vm", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "self", ".", "handleOne", "(", "vm", ",", "evt", ",", "item", ",", "function", "(", "err", ",", "notification", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "callback", "(", "null", ",", "notification", ")", ";", "}", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ",", "notis", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "callback", "(", "null", ",", "notis", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Denormalizes an event for each item passed in executeForEach function. @param {Object} evt The passed event. @param {Function} callback The function, that will be called when this action is completed. `function(err, notifications){}`
[ "Denormalizes", "an", "event", "for", "each", "item", "passed", "in", "executeForEach", "function", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/viewBuilder.js#L457-L507
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/viewBuilder.js
function (evt, callback) { var self = this; function denorm() { if (self.executeDenormFnForEach) { return self.denormalizeForEach(evt, callback); } if (self.query) { return self.handleQuery(evt, self.query, callback); } if (!self.query && self.getQueryForThisViewBuilder) { self.getQueryForThisViewBuilder(evt, function (err, query) { if (err) { debug(err); return callback(err); } self.handleQuery(evt, query, callback); }); return; } self.extractId(evt, function (err, id) { if (err) { debug(err); return callback(err); } self.loadViewModel(id, function (err, vm) { if (err) { debug(err); return callback(err); } if (vm.actionOnCommit === 'create' && !self.autoCreate) { return callback(null, []); } self.handleOne(vm, evt, function (err, notification) { if (err) { debug(err); return callback(err); } var notis = []; if (notification) { notis.push(notification); } callback(null, notis); }); }); }); } // if (this.shouldHandleRequestsOnlyEvent) { this.shouldHandleEvent(evt, function (err, doHandle) { if (err) { return callback(err); } if (!doHandle) { return callback(null, []); } denorm(); }); // } else { // denorm(); // } }
javascript
function (evt, callback) { var self = this; function denorm() { if (self.executeDenormFnForEach) { return self.denormalizeForEach(evt, callback); } if (self.query) { return self.handleQuery(evt, self.query, callback); } if (!self.query && self.getQueryForThisViewBuilder) { self.getQueryForThisViewBuilder(evt, function (err, query) { if (err) { debug(err); return callback(err); } self.handleQuery(evt, query, callback); }); return; } self.extractId(evt, function (err, id) { if (err) { debug(err); return callback(err); } self.loadViewModel(id, function (err, vm) { if (err) { debug(err); return callback(err); } if (vm.actionOnCommit === 'create' && !self.autoCreate) { return callback(null, []); } self.handleOne(vm, evt, function (err, notification) { if (err) { debug(err); return callback(err); } var notis = []; if (notification) { notis.push(notification); } callback(null, notis); }); }); }); } // if (this.shouldHandleRequestsOnlyEvent) { this.shouldHandleEvent(evt, function (err, doHandle) { if (err) { return callback(err); } if (!doHandle) { return callback(null, []); } denorm(); }); // } else { // denorm(); // } }
[ "function", "(", "evt", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "function", "denorm", "(", ")", "{", "if", "(", "self", ".", "executeDenormFnForEach", ")", "{", "return", "self", ".", "denormalizeForEach", "(", "evt", ",", "callback", ")", ";", "}", "if", "(", "self", ".", "query", ")", "{", "return", "self", ".", "handleQuery", "(", "evt", ",", "self", ".", "query", ",", "callback", ")", ";", "}", "if", "(", "!", "self", ".", "query", "&&", "self", ".", "getQueryForThisViewBuilder", ")", "{", "self", ".", "getQueryForThisViewBuilder", "(", "evt", ",", "function", "(", "err", ",", "query", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "self", ".", "handleQuery", "(", "evt", ",", "query", ",", "callback", ")", ";", "}", ")", ";", "return", ";", "}", "self", ".", "extractId", "(", "evt", ",", "function", "(", "err", ",", "id", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "self", ".", "loadViewModel", "(", "id", ",", "function", "(", "err", ",", "vm", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "if", "(", "vm", ".", "actionOnCommit", "===", "'create'", "&&", "!", "self", ".", "autoCreate", ")", "{", "return", "callback", "(", "null", ",", "[", "]", ")", ";", "}", "self", ".", "handleOne", "(", "vm", ",", "evt", ",", "function", "(", "err", ",", "notification", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "return", "callback", "(", "err", ")", ";", "}", "var", "notis", "=", "[", "]", ";", "if", "(", "notification", ")", "{", "notis", ".", "push", "(", "notification", ")", ";", "}", "callback", "(", "null", ",", "notis", ")", ";", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}", "this", ".", "shouldHandleEvent", "(", "evt", ",", "function", "(", "err", ",", "doHandle", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "if", "(", "!", "doHandle", ")", "{", "return", "callback", "(", "null", ",", "[", "]", ")", ";", "}", "denorm", "(", ")", ";", "}", ")", ";", "}" ]
Denormalizes an event. @param {Object} evt The passed event. @param {Function} callback The function, that will be called when this action is completed. `function(err, notifications){}`
[ "Denormalizes", "an", "event", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/viewBuilder.js#L515-L586
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/viewBuilder.js
function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } if (fn.length === 2) { this.getQueryForThisViewBuilder = fn; return this; } this.getQueryForThisViewBuilder = function (evt, callback) { callback(null, fn(evt)); }; var unwrappedFn = this.getQueryForThisViewBuilder; this.getQueryForThisViewBuilder = function (evt, clb) { var wrappedCallback = function () { try { clb.apply(this, _.toArray(arguments)); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; try { unwrappedFn.call(this, evt, wrappedCallback); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; return this; }
javascript
function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } if (fn.length === 2) { this.getQueryForThisViewBuilder = fn; return this; } this.getQueryForThisViewBuilder = function (evt, callback) { callback(null, fn(evt)); }; var unwrappedFn = this.getQueryForThisViewBuilder; this.getQueryForThisViewBuilder = function (evt, clb) { var wrappedCallback = function () { try { clb.apply(this, _.toArray(arguments)); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; try { unwrappedFn.call(this, evt, wrappedCallback); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; return this; }
[ "function", "(", "fn", ")", "{", "if", "(", "!", "fn", "||", "!", "_", ".", "isFunction", "(", "fn", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass a valid function!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "if", "(", "fn", ".", "length", "===", "2", ")", "{", "this", ".", "getQueryForThisViewBuilder", "=", "fn", ";", "return", "this", ";", "}", "this", ".", "getQueryForThisViewBuilder", "=", "function", "(", "evt", ",", "callback", ")", "{", "callback", "(", "null", ",", "fn", "(", "evt", ")", ")", ";", "}", ";", "var", "unwrappedFn", "=", "this", ".", "getQueryForThisViewBuilder", ";", "this", ".", "getQueryForThisViewBuilder", "=", "function", "(", "evt", ",", "clb", ")", "{", "var", "wrappedCallback", "=", "function", "(", ")", "{", "try", "{", "clb", ".", "apply", "(", "this", ",", "_", ".", "toArray", "(", "arguments", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "e", ")", ";", "process", ".", "emit", "(", "'uncaughtException'", ",", "e", ")", ";", "}", "}", ";", "try", "{", "unwrappedFn", ".", "call", "(", "this", ",", "evt", ",", "wrappedCallback", ")", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "e", ")", ";", "process", ".", "emit", "(", "'uncaughtException'", ",", "e", ")", ";", "}", "}", ";", "return", "this", ";", "}" ]
Inject useAsQuery function if no query and no id found. @param {Function} fn The function to be injected. @returns {ViewBuilder} to be able to chain...
[ "Inject", "useAsQuery", "function", "if", "no", "query", "and", "no", "id", "found", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/viewBuilder.js#L619-L656
train
adrai/node-cqrs-eventdenormalizer
lib/definitions/viewBuilder.js
function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } if (fn.length === 3) { this.handleAfterCommit = fn; return this; } this.handleAfterCommit = function (evt, vm, callback) { callback(null, fn(evt, vm)); }; var unwrappedHandleAfterCommit = this.handleAfterCommit; this.handleAfterCommit = function (evt, vm, clb) { var wrappedCallback = function () { try { clb.apply(this, _.toArray(arguments)); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; try { unwrappedHandleAfterCommit.call(this, evt, vm, wrappedCallback); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; return this; }
javascript
function (fn) { if (!fn || !_.isFunction(fn)) { var err = new Error('Please pass a valid function!'); debug(err); throw err; } if (fn.length === 3) { this.handleAfterCommit = fn; return this; } this.handleAfterCommit = function (evt, vm, callback) { callback(null, fn(evt, vm)); }; var unwrappedHandleAfterCommit = this.handleAfterCommit; this.handleAfterCommit = function (evt, vm, clb) { var wrappedCallback = function () { try { clb.apply(this, _.toArray(arguments)); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; try { unwrappedHandleAfterCommit.call(this, evt, vm, wrappedCallback); } catch (e) { debug(e); process.emit('uncaughtException', e); } }; return this; }
[ "function", "(", "fn", ")", "{", "if", "(", "!", "fn", "||", "!", "_", ".", "isFunction", "(", "fn", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass a valid function!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "if", "(", "fn", ".", "length", "===", "3", ")", "{", "this", ".", "handleAfterCommit", "=", "fn", ";", "return", "this", ";", "}", "this", ".", "handleAfterCommit", "=", "function", "(", "evt", ",", "vm", ",", "callback", ")", "{", "callback", "(", "null", ",", "fn", "(", "evt", ",", "vm", ")", ")", ";", "}", ";", "var", "unwrappedHandleAfterCommit", "=", "this", ".", "handleAfterCommit", ";", "this", ".", "handleAfterCommit", "=", "function", "(", "evt", ",", "vm", ",", "clb", ")", "{", "var", "wrappedCallback", "=", "function", "(", ")", "{", "try", "{", "clb", ".", "apply", "(", "this", ",", "_", ".", "toArray", "(", "arguments", ")", ")", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "e", ")", ";", "process", ".", "emit", "(", "'uncaughtException'", ",", "e", ")", ";", "}", "}", ";", "try", "{", "unwrappedHandleAfterCommit", ".", "call", "(", "this", ",", "evt", ",", "vm", ",", "wrappedCallback", ")", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "e", ")", ";", "process", ".", "emit", "(", "'uncaughtException'", ",", "e", ")", ";", "}", "}", ";", "return", "this", ";", "}" ]
Inject onAfterCommit function. @param {Function} fn The function to be injected. @returns {ViewBuilder} to be able to chain...
[ "Inject", "onAfterCommit", "function", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/definitions/viewBuilder.js#L802-L839
train
stimulant/ampm
view/libs/humanize.js
function () { return (f.L() ? dayTableLeap[f.n()] : dayTableCommon[f.n()]) + f.j() - 1; }
javascript
function () { return (f.L() ? dayTableLeap[f.n()] : dayTableCommon[f.n()]) + f.j() - 1; }
[ "function", "(", ")", "{", "return", "(", "f", ".", "L", "(", ")", "?", "dayTableLeap", "[", "f", ".", "n", "(", ")", "]", ":", "dayTableCommon", "[", "f", ".", "n", "(", ")", "]", ")", "+", "f", ".", "j", "(", ")", "-", "1", ";", "}" ]
Day of year; 0..365
[ "Day", "of", "year", ";", "0", "..", "365" ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/view/libs/humanize.js#L114-L116
train
stimulant/ampm
view/libs/humanize.js
function () { var unixTime = jsdate.getTime() / 1000; var secondsPassedToday = unixTime % 86400 + 3600; // since it's based off of UTC+1 if (secondsPassedToday < 0) { secondsPassedToday += 86400; } var beats = ((secondsPassedToday) / 86.4) % 1000; if (unixTime < 0) { return Math.ceil(beats); } return Math.floor(beats); }
javascript
function () { var unixTime = jsdate.getTime() / 1000; var secondsPassedToday = unixTime % 86400 + 3600; // since it's based off of UTC+1 if (secondsPassedToday < 0) { secondsPassedToday += 86400; } var beats = ((secondsPassedToday) / 86.4) % 1000; if (unixTime < 0) { return Math.ceil(beats); } return Math.floor(beats); }
[ "function", "(", ")", "{", "var", "unixTime", "=", "jsdate", ".", "getTime", "(", ")", "/", "1000", ";", "var", "secondsPassedToday", "=", "unixTime", "%", "86400", "+", "3600", ";", "if", "(", "secondsPassedToday", "<", "0", ")", "{", "secondsPassedToday", "+=", "86400", ";", "}", "var", "beats", "=", "(", "(", "secondsPassedToday", ")", "/", "86.4", ")", "%", "1000", ";", "if", "(", "unixTime", "<", "0", ")", "{", "return", "Math", ".", "ceil", "(", "beats", ")", ";", "}", "return", "Math", ".", "floor", "(", "beats", ")", ";", "}" ]
Swatch Internet time; 000..999
[ "Swatch", "Internet", "time", ";", "000", "..", "999" ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/view/libs/humanize.js#L169-L178
train
stimulant/ampm
model/consoleState.js
function() { BaseModel.prototype.initialize.apply(this); $$persistence.on('heart', this._onHeart, this); this._updateStats(); this._updateCpuWin(); this._updateMemoryWin(); this._updateMemoryCpuMac(); $$network.transports.socketToConsole.sockets.on('connection', _.bind(this._onConnection, this)); }
javascript
function() { BaseModel.prototype.initialize.apply(this); $$persistence.on('heart', this._onHeart, this); this._updateStats(); this._updateCpuWin(); this._updateMemoryWin(); this._updateMemoryCpuMac(); $$network.transports.socketToConsole.sockets.on('connection', _.bind(this._onConnection, this)); }
[ "function", "(", ")", "{", "BaseModel", ".", "prototype", ".", "initialize", ".", "apply", "(", "this", ")", ";", "$$persistence", ".", "on", "(", "'heart'", ",", "this", ".", "_onHeart", ",", "this", ")", ";", "this", ".", "_updateStats", "(", ")", ";", "this", ".", "_updateCpuWin", "(", ")", ";", "this", ".", "_updateMemoryWin", "(", ")", ";", "this", ".", "_updateMemoryCpuMac", "(", ")", ";", "$$network", ".", "transports", ".", "socketToConsole", ".", "sockets", ".", "on", "(", "'connection'", ",", "_", ".", "bind", "(", "this", ".", "_onConnection", ",", "this", ")", ")", ";", "}" ]
Set up update loops.
[ "Set", "up", "update", "loops", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/consoleState.js#L46-L55
train
stimulant/ampm
model/consoleState.js
function(user) { var config = _.cloneDeep($$config); var network = _.cloneDeep($$network.attributes); delete network.config; var persistence = _.cloneDeep($$persistence.attributes); delete persistence.config; var logging = _.cloneDeep($$logging.attributes); delete logging.config; delete logging.logCache; delete logging.eventCache; var permissions = user ? $$config.permissions[user] : null; return _.merge(_.cloneDeep($$config), { network: network, persistence: persistence, logging: logging, permissions: permissions }); }
javascript
function(user) { var config = _.cloneDeep($$config); var network = _.cloneDeep($$network.attributes); delete network.config; var persistence = _.cloneDeep($$persistence.attributes); delete persistence.config; var logging = _.cloneDeep($$logging.attributes); delete logging.config; delete logging.logCache; delete logging.eventCache; var permissions = user ? $$config.permissions[user] : null; return _.merge(_.cloneDeep($$config), { network: network, persistence: persistence, logging: logging, permissions: permissions }); }
[ "function", "(", "user", ")", "{", "var", "config", "=", "_", ".", "cloneDeep", "(", "$$config", ")", ";", "var", "network", "=", "_", ".", "cloneDeep", "(", "$$network", ".", "attributes", ")", ";", "delete", "network", ".", "config", ";", "var", "persistence", "=", "_", ".", "cloneDeep", "(", "$$persistence", ".", "attributes", ")", ";", "delete", "persistence", ".", "config", ";", "var", "logging", "=", "_", ".", "cloneDeep", "(", "$$logging", ".", "attributes", ")", ";", "delete", "logging", ".", "config", ";", "delete", "logging", ".", "logCache", ";", "delete", "logging", ".", "eventCache", ";", "var", "permissions", "=", "user", "?", "$$config", ".", "permissions", "[", "user", "]", ":", "null", ";", "return", "_", ".", "merge", "(", "_", ".", "cloneDeep", "(", "$$config", ")", ",", "{", "network", ":", "network", ",", "persistence", ":", "persistence", ",", "logging", ":", "logging", ",", "permissions", ":", "permissions", "}", ")", ";", "}" ]
Build an object representing the whole configuration of the server.
[ "Build", "an", "object", "representing", "the", "whole", "configuration", "of", "the", "server", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/consoleState.js#L58-L80
train
stimulant/ampm
model/consoleState.js
function(socket) { var username = null; var permissions = null; if (socket.handshake.headers.authorization) { username = socket.handshake.headers.authorization.match(/username="([^"]+)"/)[1]; permissions = $$config.permissions ? $$config.permissions[username] : null; } // Responds to requests for appState updates, but throttle it to _updateConsoleRate. var updateConsole = _.bind(this._updateConsole, this); socket.on('appStateRequest', _.bind(function() { clearTimeout(this._updateConsoleTimeout); this._updateConsoleTimeout = setTimeout(updateConsole, this._updateConsoleRate); }, this)); socket.on('start', _.bind(function() { if (permissions && !permissions.app) { return; } logger.info('Startup requested from console.'); $$serverState.saveState('runApp', true); $$persistence.startApp(true); }, this)); socket.on('restart-app', _.bind(function() { if (permissions && !permissions.app) { return; } logger.info('Restart requested from console.'); $$serverState.saveState('runApp', true); $$persistence.restartApp(true); }, this)); socket.on('shutdown-app', _.bind(function() { if (permissions && !permissions.app) { return; } logger.info('Shutdown requested from console.'); $$serverState.saveState('runApp', false); $$persistence.shutdownApp(); }, this)); socket.on('restart-pc', _.bind(function() { if (permissions && !permissions.computer) { return; } logger.info('Reboot requested from console.'); $$persistence.restartMachine(); }, this)); socket.on('shutdown-pc', _.bind(function() { if (permissions && !permissions.computer) { return; } logger.info('Shutdown requested from console.'); $$persistence.shutdownMachine(); }, this)); socket.on('switchConfig', _.bind(function(config) { $$serverState.saveState('configFile', config, $$persistence.restartServer); }, this)); $$network.transports.socketToConsole.sockets.emit('config', this.fullConfig(username), this.get('configs')); }
javascript
function(socket) { var username = null; var permissions = null; if (socket.handshake.headers.authorization) { username = socket.handshake.headers.authorization.match(/username="([^"]+)"/)[1]; permissions = $$config.permissions ? $$config.permissions[username] : null; } // Responds to requests for appState updates, but throttle it to _updateConsoleRate. var updateConsole = _.bind(this._updateConsole, this); socket.on('appStateRequest', _.bind(function() { clearTimeout(this._updateConsoleTimeout); this._updateConsoleTimeout = setTimeout(updateConsole, this._updateConsoleRate); }, this)); socket.on('start', _.bind(function() { if (permissions && !permissions.app) { return; } logger.info('Startup requested from console.'); $$serverState.saveState('runApp', true); $$persistence.startApp(true); }, this)); socket.on('restart-app', _.bind(function() { if (permissions && !permissions.app) { return; } logger.info('Restart requested from console.'); $$serverState.saveState('runApp', true); $$persistence.restartApp(true); }, this)); socket.on('shutdown-app', _.bind(function() { if (permissions && !permissions.app) { return; } logger.info('Shutdown requested from console.'); $$serverState.saveState('runApp', false); $$persistence.shutdownApp(); }, this)); socket.on('restart-pc', _.bind(function() { if (permissions && !permissions.computer) { return; } logger.info('Reboot requested from console.'); $$persistence.restartMachine(); }, this)); socket.on('shutdown-pc', _.bind(function() { if (permissions && !permissions.computer) { return; } logger.info('Shutdown requested from console.'); $$persistence.shutdownMachine(); }, this)); socket.on('switchConfig', _.bind(function(config) { $$serverState.saveState('configFile', config, $$persistence.restartServer); }, this)); $$network.transports.socketToConsole.sockets.emit('config', this.fullConfig(username), this.get('configs')); }
[ "function", "(", "socket", ")", "{", "var", "username", "=", "null", ";", "var", "permissions", "=", "null", ";", "if", "(", "socket", ".", "handshake", ".", "headers", ".", "authorization", ")", "{", "username", "=", "socket", ".", "handshake", ".", "headers", ".", "authorization", ".", "match", "(", "/", "username=\"([^\"]+)\"", "/", ")", "[", "1", "]", ";", "permissions", "=", "$$config", ".", "permissions", "?", "$$config", ".", "permissions", "[", "username", "]", ":", "null", ";", "}", "var", "updateConsole", "=", "_", ".", "bind", "(", "this", ".", "_updateConsole", ",", "this", ")", ";", "socket", ".", "on", "(", "'appStateRequest'", ",", "_", ".", "bind", "(", "function", "(", ")", "{", "clearTimeout", "(", "this", ".", "_updateConsoleTimeout", ")", ";", "this", ".", "_updateConsoleTimeout", "=", "setTimeout", "(", "updateConsole", ",", "this", ".", "_updateConsoleRate", ")", ";", "}", ",", "this", ")", ")", ";", "socket", ".", "on", "(", "'start'", ",", "_", ".", "bind", "(", "function", "(", ")", "{", "if", "(", "permissions", "&&", "!", "permissions", ".", "app", ")", "{", "return", ";", "}", "logger", ".", "info", "(", "'Startup requested from console.'", ")", ";", "$$serverState", ".", "saveState", "(", "'runApp'", ",", "true", ")", ";", "$$persistence", ".", "startApp", "(", "true", ")", ";", "}", ",", "this", ")", ")", ";", "socket", ".", "on", "(", "'restart-app'", ",", "_", ".", "bind", "(", "function", "(", ")", "{", "if", "(", "permissions", "&&", "!", "permissions", ".", "app", ")", "{", "return", ";", "}", "logger", ".", "info", "(", "'Restart requested from console.'", ")", ";", "$$serverState", ".", "saveState", "(", "'runApp'", ",", "true", ")", ";", "$$persistence", ".", "restartApp", "(", "true", ")", ";", "}", ",", "this", ")", ")", ";", "socket", ".", "on", "(", "'shutdown-app'", ",", "_", ".", "bind", "(", "function", "(", ")", "{", "if", "(", "permissions", "&&", "!", "permissions", ".", "app", ")", "{", "return", ";", "}", "logger", ".", "info", "(", "'Shutdown requested from console.'", ")", ";", "$$serverState", ".", "saveState", "(", "'runApp'", ",", "false", ")", ";", "$$persistence", ".", "shutdownApp", "(", ")", ";", "}", ",", "this", ")", ")", ";", "socket", ".", "on", "(", "'restart-pc'", ",", "_", ".", "bind", "(", "function", "(", ")", "{", "if", "(", "permissions", "&&", "!", "permissions", ".", "computer", ")", "{", "return", ";", "}", "logger", ".", "info", "(", "'Reboot requested from console.'", ")", ";", "$$persistence", ".", "restartMachine", "(", ")", ";", "}", ",", "this", ")", ")", ";", "socket", ".", "on", "(", "'shutdown-pc'", ",", "_", ".", "bind", "(", "function", "(", ")", "{", "if", "(", "permissions", "&&", "!", "permissions", ".", "computer", ")", "{", "return", ";", "}", "logger", ".", "info", "(", "'Shutdown requested from console.'", ")", ";", "$$persistence", ".", "shutdownMachine", "(", ")", ";", "}", ",", "this", ")", ")", ";", "socket", ".", "on", "(", "'switchConfig'", ",", "_", ".", "bind", "(", "function", "(", "config", ")", "{", "$$serverState", ".", "saveState", "(", "'configFile'", ",", "config", ",", "$$persistence", ".", "restartServer", ")", ";", "}", ",", "this", ")", ")", ";", "$$network", ".", "transports", ".", "socketToConsole", ".", "sockets", ".", "emit", "(", "'config'", ",", "this", ".", "fullConfig", "(", "username", ")", ",", "this", ".", "get", "(", "'configs'", ")", ")", ";", "}" ]
On initial socket connection with the console, listen for commands and send out the config.
[ "On", "initial", "socket", "connection", "with", "the", "console", "listen", "for", "commands", "and", "send", "out", "the", "config", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/consoleState.js#L83-L152
train
stimulant/ampm
model/consoleState.js
function() { var message = _.clone(this.attributes); message.restartCount = $$persistence.get('restartCount'); message.logs = $$logging.get('logCache'); message.events = $$logging.get('eventCache'); $$network.transports.socketToConsole.sockets.emit('appState', message); }
javascript
function() { var message = _.clone(this.attributes); message.restartCount = $$persistence.get('restartCount'); message.logs = $$logging.get('logCache'); message.events = $$logging.get('eventCache'); $$network.transports.socketToConsole.sockets.emit('appState', message); }
[ "function", "(", ")", "{", "var", "message", "=", "_", ".", "clone", "(", "this", ".", "attributes", ")", ";", "message", ".", "restartCount", "=", "$$persistence", ".", "get", "(", "'restartCount'", ")", ";", "message", ".", "logs", "=", "$$logging", ".", "get", "(", "'logCache'", ")", ";", "message", ".", "events", "=", "$$logging", ".", "get", "(", "'eventCache'", ")", ";", "$$network", ".", "transports", ".", "socketToConsole", ".", "sockets", ".", "emit", "(", "'appState'", ",", "message", ")", ";", "}" ]
Send the console new data on an interval.
[ "Send", "the", "console", "new", "data", "on", "an", "interval", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/consoleState.js#L155-L162
train
stimulant/ampm
model/consoleState.js
function() { var fpsHistory = this.get('fps'); if (!fpsHistory) { fpsHistory = []; this.set({ fps: fpsHistory, }); } // Update FPS. if (this._tickSum) { var fps = 1000 / (this._tickSum / this._maxTicks); fps *= 100; fps = Math.round(fps); fps /= 100; fpsHistory.push(fps); while (fpsHistory.length > this._statHistory) { fpsHistory.shift(); } var avg = 0; fpsHistory.filter(function(f) { return f !== null; }).forEach(function(f) { avg += f; }); avg /= fpsHistory.length; this.set({ avgFps: Math.round(avg) }); } if ($$persistence.processId()) { // Update the uptime. var wasRunning = this.get('isRunning'); if (!wasRunning) { this._startupTime = Date.now(); } this.set('uptime', Date.now() - this._startupTime); this.set('isRunning', true); } else { // Not running, so reset everything. this.set({ isRunning: false, fps: null, memory: null, uptime: 0 }); } clearTimeout(this._updateStatsTimeout); this._updateStatsTimeout = setTimeout(_.bind(this._updateStats, this), this._updateStatsRate); }
javascript
function() { var fpsHistory = this.get('fps'); if (!fpsHistory) { fpsHistory = []; this.set({ fps: fpsHistory, }); } // Update FPS. if (this._tickSum) { var fps = 1000 / (this._tickSum / this._maxTicks); fps *= 100; fps = Math.round(fps); fps /= 100; fpsHistory.push(fps); while (fpsHistory.length > this._statHistory) { fpsHistory.shift(); } var avg = 0; fpsHistory.filter(function(f) { return f !== null; }).forEach(function(f) { avg += f; }); avg /= fpsHistory.length; this.set({ avgFps: Math.round(avg) }); } if ($$persistence.processId()) { // Update the uptime. var wasRunning = this.get('isRunning'); if (!wasRunning) { this._startupTime = Date.now(); } this.set('uptime', Date.now() - this._startupTime); this.set('isRunning', true); } else { // Not running, so reset everything. this.set({ isRunning: false, fps: null, memory: null, uptime: 0 }); } clearTimeout(this._updateStatsTimeout); this._updateStatsTimeout = setTimeout(_.bind(this._updateStats, this), this._updateStatsRate); }
[ "function", "(", ")", "{", "var", "fpsHistory", "=", "this", ".", "get", "(", "'fps'", ")", ";", "if", "(", "!", "fpsHistory", ")", "{", "fpsHistory", "=", "[", "]", ";", "this", ".", "set", "(", "{", "fps", ":", "fpsHistory", ",", "}", ")", ";", "}", "if", "(", "this", ".", "_tickSum", ")", "{", "var", "fps", "=", "1000", "/", "(", "this", ".", "_tickSum", "/", "this", ".", "_maxTicks", ")", ";", "fps", "*=", "100", ";", "fps", "=", "Math", ".", "round", "(", "fps", ")", ";", "fps", "/=", "100", ";", "fpsHistory", ".", "push", "(", "fps", ")", ";", "while", "(", "fpsHistory", ".", "length", ">", "this", ".", "_statHistory", ")", "{", "fpsHistory", ".", "shift", "(", ")", ";", "}", "var", "avg", "=", "0", ";", "fpsHistory", ".", "filter", "(", "function", "(", "f", ")", "{", "return", "f", "!==", "null", ";", "}", ")", ".", "forEach", "(", "function", "(", "f", ")", "{", "avg", "+=", "f", ";", "}", ")", ";", "avg", "/=", "fpsHistory", ".", "length", ";", "this", ".", "set", "(", "{", "avgFps", ":", "Math", ".", "round", "(", "avg", ")", "}", ")", ";", "}", "if", "(", "$$persistence", ".", "processId", "(", ")", ")", "{", "var", "wasRunning", "=", "this", ".", "get", "(", "'isRunning'", ")", ";", "if", "(", "!", "wasRunning", ")", "{", "this", ".", "_startupTime", "=", "Date", ".", "now", "(", ")", ";", "}", "this", ".", "set", "(", "'uptime'", ",", "Date", ".", "now", "(", ")", "-", "this", ".", "_startupTime", ")", ";", "this", ".", "set", "(", "'isRunning'", ",", "true", ")", ";", "}", "else", "{", "this", ".", "set", "(", "{", "isRunning", ":", "false", ",", "fps", ":", "null", ",", "memory", ":", "null", ",", "uptime", ":", "0", "}", ")", ";", "}", "clearTimeout", "(", "this", ".", "_updateStatsTimeout", ")", ";", "this", ".", "_updateStatsTimeout", "=", "setTimeout", "(", "_", ".", "bind", "(", "this", ".", "_updateStats", ",", "this", ")", ",", "this", ".", "_updateStatsRate", ")", ";", "}" ]
Update the internal objects which specify the FPS, whether the app is running, memory usage, and uptime.
[ "Update", "the", "internal", "objects", "which", "specify", "the", "FPS", "whether", "the", "app", "is", "running", "memory", "usage", "and", "uptime", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/consoleState.js#L166-L219
train
stimulant/ampm
model/consoleState.js
function() { if (process.platform !== 'win32') { return; } var id = $$persistence.processId(); if (id) { child_process.exec('tasklist /FI "PID eq ' + id + '" /FO LIST', _.bind(function(error, stdout, stderror) { /* // tasklist.exe output looks like this: Image Name: Client.exe PID: 12008 Session Name: Console Session#: 1 Mem Usage: 39,384 K */ stdout = stdout.toString(); var match = XRegExp.exec(stdout, XRegExp('[\\d,]+\\sK')); if (!match) { return; } match = match[0]; // "39,384 K" match = match.replace(',', '').replace(' K', ''); // "39384" var memory = parseInt(match) * 1024; // 40329216 this._memoryFrame(memory); clearTimeout(this._updateMemoryWinTimeout); this._updateMemoryWinTimeout = setTimeout(_.bind(this._updateMemoryWin, this), this._updateStatsRate); $$persistence.checkMemory(memory); }, this)); } else { clearTimeout(this._updateMemoryWinTimeout); this._updateMemoryWinTimeout = setTimeout(_.bind(this._updateMemoryWin, this), this._updateStatsRate); } }
javascript
function() { if (process.platform !== 'win32') { return; } var id = $$persistence.processId(); if (id) { child_process.exec('tasklist /FI "PID eq ' + id + '" /FO LIST', _.bind(function(error, stdout, stderror) { /* // tasklist.exe output looks like this: Image Name: Client.exe PID: 12008 Session Name: Console Session#: 1 Mem Usage: 39,384 K */ stdout = stdout.toString(); var match = XRegExp.exec(stdout, XRegExp('[\\d,]+\\sK')); if (!match) { return; } match = match[0]; // "39,384 K" match = match.replace(',', '').replace(' K', ''); // "39384" var memory = parseInt(match) * 1024; // 40329216 this._memoryFrame(memory); clearTimeout(this._updateMemoryWinTimeout); this._updateMemoryWinTimeout = setTimeout(_.bind(this._updateMemoryWin, this), this._updateStatsRate); $$persistence.checkMemory(memory); }, this)); } else { clearTimeout(this._updateMemoryWinTimeout); this._updateMemoryWinTimeout = setTimeout(_.bind(this._updateMemoryWin, this), this._updateStatsRate); } }
[ "function", "(", ")", "{", "if", "(", "process", ".", "platform", "!==", "'win32'", ")", "{", "return", ";", "}", "var", "id", "=", "$$persistence", ".", "processId", "(", ")", ";", "if", "(", "id", ")", "{", "child_process", ".", "exec", "(", "'tasklist /FI \"PID eq '", "+", "id", "+", "'\" /FO LIST'", ",", "_", ".", "bind", "(", "function", "(", "error", ",", "stdout", ",", "stderror", ")", "{", "stdout", "=", "stdout", ".", "toString", "(", ")", ";", "var", "match", "=", "XRegExp", ".", "exec", "(", "stdout", ",", "XRegExp", "(", "'[\\\\d,]+\\\\sK'", ")", ")", ";", "\\\\", "\\\\", "if", "(", "!", "match", ")", "{", "return", ";", "}", "match", "=", "match", "[", "0", "]", ";", "match", "=", "match", ".", "replace", "(", "','", ",", "''", ")", ".", "replace", "(", "' K'", ",", "''", ")", ";", "var", "memory", "=", "parseInt", "(", "match", ")", "*", "1024", ";", "this", ".", "_memoryFrame", "(", "memory", ")", ";", "clearTimeout", "(", "this", ".", "_updateMemoryWinTimeout", ")", ";", "}", ",", "this", ")", ")", ";", "}", "else", "this", ".", "_updateMemoryWinTimeout", "=", "setTimeout", "(", "_", ".", "bind", "(", "this", ".", "_updateMemoryWin", ",", "this", ")", ",", "this", ".", "_updateStatsRate", ")", ";", "}" ]
Request to update the memory.
[ "Request", "to", "update", "the", "memory", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/consoleState.js#L222-L259
train
stimulant/ampm
model/consoleState.js
function() { if (process.platform !== 'darwin') { return; } // top is running in logging mode, spewing process info to stdout every second. this._topConsole = child_process.spawn('/usr/bin/top', ['-l', '0', '-stats', 'pid,cpu,mem,command']); this._topConsole.stdout.on('data', _.bind(function(stdout) { var id = $$persistence.processId(); if (!id) { return; } // Find the line with the process id that matches what we're watching. stdout = stdout.toString(); var lines = stdout.split('\n'); var line = lines.filter(function(line) { return line.indexOf(id) === 0; })[0]; if (!line) { return; } var parts = line.split(/\s+/g); // Add to the CPU history. var cpu = parseFloat(parts[1]); this._cpuFrame(cpu); // Add to the memory history. var memory = parts[2]; var unit = 1; if (memory.indexOf('K') !== -1) { unit = 1024; } else if (memory.indexOf('M') !== -1) { unit = 1024 * 1024; } else if (memory.indexOf('G') !== -1) { unit = 1024 * 1024 * 1024; } memory = memory.replace(/[\D]/g, ''); memory = parseInt(memory) * unit; this._memoryFrame(memory); }, this)); }
javascript
function() { if (process.platform !== 'darwin') { return; } // top is running in logging mode, spewing process info to stdout every second. this._topConsole = child_process.spawn('/usr/bin/top', ['-l', '0', '-stats', 'pid,cpu,mem,command']); this._topConsole.stdout.on('data', _.bind(function(stdout) { var id = $$persistence.processId(); if (!id) { return; } // Find the line with the process id that matches what we're watching. stdout = stdout.toString(); var lines = stdout.split('\n'); var line = lines.filter(function(line) { return line.indexOf(id) === 0; })[0]; if (!line) { return; } var parts = line.split(/\s+/g); // Add to the CPU history. var cpu = parseFloat(parts[1]); this._cpuFrame(cpu); // Add to the memory history. var memory = parts[2]; var unit = 1; if (memory.indexOf('K') !== -1) { unit = 1024; } else if (memory.indexOf('M') !== -1) { unit = 1024 * 1024; } else if (memory.indexOf('G') !== -1) { unit = 1024 * 1024 * 1024; } memory = memory.replace(/[\D]/g, ''); memory = parseInt(memory) * unit; this._memoryFrame(memory); }, this)); }
[ "function", "(", ")", "{", "if", "(", "process", ".", "platform", "!==", "'darwin'", ")", "{", "return", ";", "}", "this", ".", "_topConsole", "=", "child_process", ".", "spawn", "(", "'/usr/bin/top'", ",", "[", "'-l'", ",", "'0'", ",", "'-stats'", ",", "'pid,cpu,mem,command'", "]", ")", ";", "this", ".", "_topConsole", ".", "stdout", ".", "on", "(", "'data'", ",", "_", ".", "bind", "(", "function", "(", "stdout", ")", "{", "var", "id", "=", "$$persistence", ".", "processId", "(", ")", ";", "if", "(", "!", "id", ")", "{", "return", ";", "}", "stdout", "=", "stdout", ".", "toString", "(", ")", ";", "var", "lines", "=", "stdout", ".", "split", "(", "'\\n'", ")", ";", "\\n", "var", "line", "=", "lines", ".", "filter", "(", "function", "(", "line", ")", "{", "return", "line", ".", "indexOf", "(", "id", ")", "===", "0", ";", "}", ")", "[", "0", "]", ";", "if", "(", "!", "line", ")", "{", "return", ";", "}", "var", "parts", "=", "line", ".", "split", "(", "/", "\\s+", "/", "g", ")", ";", "var", "cpu", "=", "parseFloat", "(", "parts", "[", "1", "]", ")", ";", "this", ".", "_cpuFrame", "(", "cpu", ")", ";", "var", "memory", "=", "parts", "[", "2", "]", ";", "var", "unit", "=", "1", ";", "if", "(", "memory", ".", "indexOf", "(", "'K'", ")", "!==", "-", "1", ")", "{", "unit", "=", "1024", ";", "}", "else", "if", "(", "memory", ".", "indexOf", "(", "'M'", ")", "!==", "-", "1", ")", "{", "unit", "=", "1024", "*", "1024", ";", "}", "else", "if", "(", "memory", ".", "indexOf", "(", "'G'", ")", "!==", "-", "1", ")", "{", "unit", "=", "1024", "*", "1024", "*", "1024", ";", "}", "memory", "=", "memory", ".", "replace", "(", "/", "[\\D]", "/", "g", ",", "''", ")", ";", "memory", "=", "parseInt", "(", "memory", ")", "*", "unit", ";", "}", ",", "this", ")", ")", ";", "}" ]
Run 'top' to get the CPU and memory usage of the app process on Mac.
[ "Run", "top", "to", "get", "the", "CPU", "and", "memory", "usage", "of", "the", "app", "process", "on", "Mac", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/consoleState.js#L279-L322
train
stimulant/ampm
model/consoleState.js
function(cpu) { if (!isNaN(cpu)) { var cpuHistory = this.get('cpu'); if (!cpuHistory) { cpuHistory = []; this.set('cpu', cpuHistory); } cpuHistory.push(cpu); while (cpuHistory.length > this._statHistory) { cpuHistory.shift(); } var avg = 0; cpuHistory.filter(function(f) { return f !== null; }).forEach(function(f) { avg += f; }); avg /= cpuHistory.length; this.set({ avgCpu: Math.round(avg) }); } }
javascript
function(cpu) { if (!isNaN(cpu)) { var cpuHistory = this.get('cpu'); if (!cpuHistory) { cpuHistory = []; this.set('cpu', cpuHistory); } cpuHistory.push(cpu); while (cpuHistory.length > this._statHistory) { cpuHistory.shift(); } var avg = 0; cpuHistory.filter(function(f) { return f !== null; }).forEach(function(f) { avg += f; }); avg /= cpuHistory.length; this.set({ avgCpu: Math.round(avg) }); } }
[ "function", "(", "cpu", ")", "{", "if", "(", "!", "isNaN", "(", "cpu", ")", ")", "{", "var", "cpuHistory", "=", "this", ".", "get", "(", "'cpu'", ")", ";", "if", "(", "!", "cpuHistory", ")", "{", "cpuHistory", "=", "[", "]", ";", "this", ".", "set", "(", "'cpu'", ",", "cpuHistory", ")", ";", "}", "cpuHistory", ".", "push", "(", "cpu", ")", ";", "while", "(", "cpuHistory", ".", "length", ">", "this", ".", "_statHistory", ")", "{", "cpuHistory", ".", "shift", "(", ")", ";", "}", "var", "avg", "=", "0", ";", "cpuHistory", ".", "filter", "(", "function", "(", "f", ")", "{", "return", "f", "!==", "null", ";", "}", ")", ".", "forEach", "(", "function", "(", "f", ")", "{", "avg", "+=", "f", ";", "}", ")", ";", "avg", "/=", "cpuHistory", ".", "length", ";", "this", ".", "set", "(", "{", "avgCpu", ":", "Math", ".", "round", "(", "avg", ")", "}", ")", ";", "}", "}" ]
Add a CPU sample to the history.
[ "Add", "a", "CPU", "sample", "to", "the", "history", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/consoleState.js#L325-L349
train
stimulant/ampm
model/consoleState.js
function(memory) { var memoryHistory = this.get('memory'); if (!memoryHistory) { memoryHistory = []; this.set({ memory: memoryHistory }); } memoryHistory.push(memory); while (memoryHistory.length > this._statHistory) { memoryHistory.shift(); } var avg = 0; memoryHistory.filter(function(f) { return f !== null; }).forEach(function(f) { avg += f; }); avg /= memoryHistory.length; this.set({ avgMemory: Math.round(avg) }); }
javascript
function(memory) { var memoryHistory = this.get('memory'); if (!memoryHistory) { memoryHistory = []; this.set({ memory: memoryHistory }); } memoryHistory.push(memory); while (memoryHistory.length > this._statHistory) { memoryHistory.shift(); } var avg = 0; memoryHistory.filter(function(f) { return f !== null; }).forEach(function(f) { avg += f; }); avg /= memoryHistory.length; this.set({ avgMemory: Math.round(avg) }); }
[ "function", "(", "memory", ")", "{", "var", "memoryHistory", "=", "this", ".", "get", "(", "'memory'", ")", ";", "if", "(", "!", "memoryHistory", ")", "{", "memoryHistory", "=", "[", "]", ";", "this", ".", "set", "(", "{", "memory", ":", "memoryHistory", "}", ")", ";", "}", "memoryHistory", ".", "push", "(", "memory", ")", ";", "while", "(", "memoryHistory", ".", "length", ">", "this", ".", "_statHistory", ")", "{", "memoryHistory", ".", "shift", "(", ")", ";", "}", "var", "avg", "=", "0", ";", "memoryHistory", ".", "filter", "(", "function", "(", "f", ")", "{", "return", "f", "!==", "null", ";", "}", ")", ".", "forEach", "(", "function", "(", "f", ")", "{", "avg", "+=", "f", ";", "}", ")", ";", "avg", "/=", "memoryHistory", ".", "length", ";", "this", ".", "set", "(", "{", "avgMemory", ":", "Math", ".", "round", "(", "avg", ")", "}", ")", ";", "}" ]
Add a memory usage sample to the history.
[ "Add", "a", "memory", "usage", "sample", "to", "the", "history", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/consoleState.js#L352-L377
train
stimulant/ampm
model/consoleState.js
function(message) { if (!this._tickList) { this._tickList = []; while (this._tickList.length < this._maxTicks) { this._tickList.push(0); } } if (!this._lastHeart) { this._lastHeart = Date.now(); this._lastFpsUpdate = this._lastHeart; return; } var newHeart = Date.now(); var newTick = newHeart - this._lastHeart; this._lastHeart = newHeart; this._tickSum -= this._tickList[this._tickIndex]; this._tickSum += newTick; this._tickList[this._tickIndex] = newTick; if (++this._tickIndex == this._maxTicks) { this._tickIndex = 0; } }
javascript
function(message) { if (!this._tickList) { this._tickList = []; while (this._tickList.length < this._maxTicks) { this._tickList.push(0); } } if (!this._lastHeart) { this._lastHeart = Date.now(); this._lastFpsUpdate = this._lastHeart; return; } var newHeart = Date.now(); var newTick = newHeart - this._lastHeart; this._lastHeart = newHeart; this._tickSum -= this._tickList[this._tickIndex]; this._tickSum += newTick; this._tickList[this._tickIndex] = newTick; if (++this._tickIndex == this._maxTicks) { this._tickIndex = 0; } }
[ "function", "(", "message", ")", "{", "if", "(", "!", "this", ".", "_tickList", ")", "{", "this", ".", "_tickList", "=", "[", "]", ";", "while", "(", "this", ".", "_tickList", ".", "length", "<", "this", ".", "_maxTicks", ")", "{", "this", ".", "_tickList", ".", "push", "(", "0", ")", ";", "}", "}", "if", "(", "!", "this", ".", "_lastHeart", ")", "{", "this", ".", "_lastHeart", "=", "Date", ".", "now", "(", ")", ";", "this", ".", "_lastFpsUpdate", "=", "this", ".", "_lastHeart", ";", "return", ";", "}", "var", "newHeart", "=", "Date", ".", "now", "(", ")", ";", "var", "newTick", "=", "newHeart", "-", "this", ".", "_lastHeart", ";", "this", ".", "_lastHeart", "=", "newHeart", ";", "this", ".", "_tickSum", "-=", "this", ".", "_tickList", "[", "this", ".", "_tickIndex", "]", ";", "this", ".", "_tickSum", "+=", "newTick", ";", "this", ".", "_tickList", "[", "this", ".", "_tickIndex", "]", "=", "newTick", ";", "if", "(", "++", "this", ".", "_tickIndex", "==", "this", ".", "_maxTicks", ")", "{", "this", ".", "_tickIndex", "=", "0", ";", "}", "}" ]
Update the FPS whenever a heartbeat message is received from the app.
[ "Update", "the", "FPS", "whenever", "a", "heartbeat", "message", "is", "received", "from", "the", "app", "." ]
c83c39fa2e8f322e5212016a5204b7a08c88d483
https://github.com/stimulant/ampm/blob/c83c39fa2e8f322e5212016a5204b7a08c88d483/model/consoleState.js#L387-L411
train
ChristianRich/phone-number-extractor
lib/extractor.js
function(text, countryCode, useGooglePhoneLib){ const that = this, resultsFormatted = []; return new Promise(function(resolve, reject){ const data = utils.formatString(text); let countryRules; if(_.isString(countryCode)){ countryCode = countryCode.toUpperCase(); } if(countryCode === 'AU'){ countryRules = new locale.AU(data); } if(countryCode === 'US'){ countryRules = new locale.US(data); } if(!countryRules){ return reject('Unsupported county code "' + countryCode + '". Supported codes are "AU" (Australia) and "US" (United States)'); } async.map(countryRules.getRules(), function(rule, cb){ rule.run(function(result){ cb(null, result); }); }, function(err, results){ results = _.flatten(results || []); if(useGooglePhoneLib === true){ _.each(results, function(n){ resultsFormatted.push( that.formati18n(n, countryCode) ) }); return resolve(resultsFormatted); } resolve(results); }); }); }
javascript
function(text, countryCode, useGooglePhoneLib){ const that = this, resultsFormatted = []; return new Promise(function(resolve, reject){ const data = utils.formatString(text); let countryRules; if(_.isString(countryCode)){ countryCode = countryCode.toUpperCase(); } if(countryCode === 'AU'){ countryRules = new locale.AU(data); } if(countryCode === 'US'){ countryRules = new locale.US(data); } if(!countryRules){ return reject('Unsupported county code "' + countryCode + '". Supported codes are "AU" (Australia) and "US" (United States)'); } async.map(countryRules.getRules(), function(rule, cb){ rule.run(function(result){ cb(null, result); }); }, function(err, results){ results = _.flatten(results || []); if(useGooglePhoneLib === true){ _.each(results, function(n){ resultsFormatted.push( that.formati18n(n, countryCode) ) }); return resolve(resultsFormatted); } resolve(results); }); }); }
[ "function", "(", "text", ",", "countryCode", ",", "useGooglePhoneLib", ")", "{", "const", "that", "=", "this", ",", "resultsFormatted", "=", "[", "]", ";", "return", "new", "Promise", "(", "function", "(", "resolve", ",", "reject", ")", "{", "const", "data", "=", "utils", ".", "formatString", "(", "text", ")", ";", "let", "countryRules", ";", "if", "(", "_", ".", "isString", "(", "countryCode", ")", ")", "{", "countryCode", "=", "countryCode", ".", "toUpperCase", "(", ")", ";", "}", "if", "(", "countryCode", "===", "'AU'", ")", "{", "countryRules", "=", "new", "locale", ".", "AU", "(", "data", ")", ";", "}", "if", "(", "countryCode", "===", "'US'", ")", "{", "countryRules", "=", "new", "locale", ".", "US", "(", "data", ")", ";", "}", "if", "(", "!", "countryRules", ")", "{", "return", "reject", "(", "'Unsupported county code \"'", "+", "countryCode", "+", "'\". Supported codes are \"AU\" (Australia) and \"US\" (United States)'", ")", ";", "}", "async", ".", "map", "(", "countryRules", ".", "getRules", "(", ")", ",", "function", "(", "rule", ",", "cb", ")", "{", "rule", ".", "run", "(", "function", "(", "result", ")", "{", "cb", "(", "null", ",", "result", ")", ";", "}", ")", ";", "}", ",", "function", "(", "err", ",", "results", ")", "{", "results", "=", "_", ".", "flatten", "(", "results", "||", "[", "]", ")", ";", "if", "(", "useGooglePhoneLib", "===", "true", ")", "{", "_", ".", "each", "(", "results", ",", "function", "(", "n", ")", "{", "resultsFormatted", ".", "push", "(", "that", ".", "formati18n", "(", "n", ",", "countryCode", ")", ")", "}", ")", ";", "return", "resolve", "(", "resultsFormatted", ")", ";", "}", "resolve", "(", "results", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Returns an array of possible phone number candidates for a specific country code @param {string} text - Text string from where the phone numbers are extracted @param {string} countryCode - au or us @param {boolean=} useGooglePhoneLib - When true uses Google LibPhoneNumber to format the result. https://github.com/googlei18n/libphonenumber @return {Promise}
[ "Returns", "an", "array", "of", "possible", "phone", "number", "candidates", "for", "a", "specific", "country", "code" ]
6458e9177f2c59e3bc6377adec60042f24c21f3d
https://github.com/ChristianRich/phone-number-extractor/blob/6458e9177f2c59e3bc6377adec60042f24c21f3d/lib/extractor.js#L19-L68
train
ChristianRich/phone-number-extractor
lib/extractor.js
function(n, countryCode){ const number = phoneUtil.parse(n, countryCode), isPossibleNumber = phoneUtil.isPossibleNumber(number), res = { input: n, countryCode: countryCode, isPossibleNumber: isPossibleNumber, isPossibleNumberWithReason: phoneUtil.isPossibleNumberWithReason(number) }; if(isPossibleNumber){ res.isPossibleNumber = true; res.isNumberValid = phoneUtil.isValidNumber(number); res.countryCode = countryCode; res.formatted = phoneUtil.formatInOriginalFormat(number, countryCode); res.national = phoneUtil.format(number, PNF.NATIONAL); res.international = phoneUtil.format(number, PNF.INTERNATIONAL) } switch (phoneUtil.isPossibleNumberWithReason(number)){ case PNV.IS_POSSIBLE: res.isPossibleNumberWithReason = 'IS_POSSIBLE'; break; case PNV.INVALID_COUNTRY_CODE: res.isPossibleNumberWithReason = 'INVALID_COUNTRY_CODE'; break; case PNV.TOO_SHORT: res.isPossibleNumberWithReason = 'TOO_SHORT'; break; case PNV.TOO_LONG: res.isPossibleNumberWithReason = 'TOO_LONG'; break; } return res; }
javascript
function(n, countryCode){ const number = phoneUtil.parse(n, countryCode), isPossibleNumber = phoneUtil.isPossibleNumber(number), res = { input: n, countryCode: countryCode, isPossibleNumber: isPossibleNumber, isPossibleNumberWithReason: phoneUtil.isPossibleNumberWithReason(number) }; if(isPossibleNumber){ res.isPossibleNumber = true; res.isNumberValid = phoneUtil.isValidNumber(number); res.countryCode = countryCode; res.formatted = phoneUtil.formatInOriginalFormat(number, countryCode); res.national = phoneUtil.format(number, PNF.NATIONAL); res.international = phoneUtil.format(number, PNF.INTERNATIONAL) } switch (phoneUtil.isPossibleNumberWithReason(number)){ case PNV.IS_POSSIBLE: res.isPossibleNumberWithReason = 'IS_POSSIBLE'; break; case PNV.INVALID_COUNTRY_CODE: res.isPossibleNumberWithReason = 'INVALID_COUNTRY_CODE'; break; case PNV.TOO_SHORT: res.isPossibleNumberWithReason = 'TOO_SHORT'; break; case PNV.TOO_LONG: res.isPossibleNumberWithReason = 'TOO_LONG'; break; } return res; }
[ "function", "(", "n", ",", "countryCode", ")", "{", "const", "number", "=", "phoneUtil", ".", "parse", "(", "n", ",", "countryCode", ")", ",", "isPossibleNumber", "=", "phoneUtil", ".", "isPossibleNumber", "(", "number", ")", ",", "res", "=", "{", "input", ":", "n", ",", "countryCode", ":", "countryCode", ",", "isPossibleNumber", ":", "isPossibleNumber", ",", "isPossibleNumberWithReason", ":", "phoneUtil", ".", "isPossibleNumberWithReason", "(", "number", ")", "}", ";", "if", "(", "isPossibleNumber", ")", "{", "res", ".", "isPossibleNumber", "=", "true", ";", "res", ".", "isNumberValid", "=", "phoneUtil", ".", "isValidNumber", "(", "number", ")", ";", "res", ".", "countryCode", "=", "countryCode", ";", "res", ".", "formatted", "=", "phoneUtil", ".", "formatInOriginalFormat", "(", "number", ",", "countryCode", ")", ";", "res", ".", "national", "=", "phoneUtil", ".", "format", "(", "number", ",", "PNF", ".", "NATIONAL", ")", ";", "res", ".", "international", "=", "phoneUtil", ".", "format", "(", "number", ",", "PNF", ".", "INTERNATIONAL", ")", "}", "switch", "(", "phoneUtil", ".", "isPossibleNumberWithReason", "(", "number", ")", ")", "{", "case", "PNV", ".", "IS_POSSIBLE", ":", "res", ".", "isPossibleNumberWithReason", "=", "'IS_POSSIBLE'", ";", "break", ";", "case", "PNV", ".", "INVALID_COUNTRY_CODE", ":", "res", ".", "isPossibleNumberWithReason", "=", "'INVALID_COUNTRY_CODE'", ";", "break", ";", "case", "PNV", ".", "TOO_SHORT", ":", "res", ".", "isPossibleNumberWithReason", "=", "'TOO_SHORT'", ";", "break", ";", "case", "PNV", ".", "TOO_LONG", ":", "res", ".", "isPossibleNumberWithReason", "=", "'TOO_LONG'", ";", "break", ";", "}", "return", "res", ";", "}" ]
Uses Google LibPhoneNumber to format and verify the number @param {number|string} n @param {string} countryCode @return {object}
[ "Uses", "Google", "LibPhoneNumber", "to", "format", "and", "verify", "the", "number" ]
6458e9177f2c59e3bc6377adec60042f24c21f3d
https://github.com/ChristianRich/phone-number-extractor/blob/6458e9177f2c59e3bc6377adec60042f24c21f3d/lib/extractor.js#L76-L116
train
adrai/node-cqrs-eventdenormalizer
lib/eventDispatcher.js
function (evt) { if (!evt || !_.isObject(evt)) { var err = new Error('Please pass a valid event!'); debug(err); throw err; } var name = dotty.get(evt, this.definition.name) || ''; var version = 0; if (dotty.exists(evt, this.definition.version)) { version = dotty.get(evt, this.definition.version); } else { debug('no version found, handling as version: 0'); } var aggregate = null; if (dotty.exists(evt, this.definition.aggregate)) { aggregate = dotty.get(evt, this.definition.aggregate); } else { debug('no aggregate found'); } var context = null; if (dotty.exists(evt, this.definition.context)) { context = dotty.get(evt, this.definition.context); } else { debug('no context found'); } return { name: name, version: version, aggregate: aggregate, context: context }; }
javascript
function (evt) { if (!evt || !_.isObject(evt)) { var err = new Error('Please pass a valid event!'); debug(err); throw err; } var name = dotty.get(evt, this.definition.name) || ''; var version = 0; if (dotty.exists(evt, this.definition.version)) { version = dotty.get(evt, this.definition.version); } else { debug('no version found, handling as version: 0'); } var aggregate = null; if (dotty.exists(evt, this.definition.aggregate)) { aggregate = dotty.get(evt, this.definition.aggregate); } else { debug('no aggregate found'); } var context = null; if (dotty.exists(evt, this.definition.context)) { context = dotty.get(evt, this.definition.context); } else { debug('no context found'); } return { name: name, version: version, aggregate: aggregate, context: context }; }
[ "function", "(", "evt", ")", "{", "if", "(", "!", "evt", "||", "!", "_", ".", "isObject", "(", "evt", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass a valid event!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "var", "name", "=", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definition", ".", "name", ")", "||", "''", ";", "var", "version", "=", "0", ";", "if", "(", "dotty", ".", "exists", "(", "evt", ",", "this", ".", "definition", ".", "version", ")", ")", "{", "version", "=", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definition", ".", "version", ")", ";", "}", "else", "{", "debug", "(", "'no version found, handling as version: 0'", ")", ";", "}", "var", "aggregate", "=", "null", ";", "if", "(", "dotty", ".", "exists", "(", "evt", ",", "this", ".", "definition", ".", "aggregate", ")", ")", "{", "aggregate", "=", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definition", ".", "aggregate", ")", ";", "}", "else", "{", "debug", "(", "'no aggregate found'", ")", ";", "}", "var", "context", "=", "null", ";", "if", "(", "dotty", ".", "exists", "(", "evt", ",", "this", ".", "definition", ".", "context", ")", ")", "{", "context", "=", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definition", ".", "context", ")", ";", "}", "else", "{", "debug", "(", "'no context found'", ")", ";", "}", "return", "{", "name", ":", "name", ",", "version", ":", "version", ",", "aggregate", ":", "aggregate", ",", "context", ":", "context", "}", ";", "}" ]
Returns the target information of this event. @param {Object} evt The passed event. @returns {{name: 'eventName', aggregateId: 'aggregateId', version: 0, aggregate: 'aggregateName', context: 'contextName'}}
[ "Returns", "the", "target", "information", "of", "this", "event", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/eventDispatcher.js#L50-L86
train
adrai/node-cqrs-eventdenormalizer
lib/denormalizer.js
function (callback) { var self = this; var warnings = null; async.series([ // load domain files... function (callback) { debug('load denormalizer files..'); self.structureLoader(self.options.denormalizerPath, function (err, tree, warns) { if (err) { return callback(err); } warnings = warns; self.tree = attachLookupFunctions(tree); callback(null); }); }, // prepare infrastructure... function (callback) { debug('prepare infrastructure...'); async.parallel([ // prepare repository... function (callback) { debug('prepare repository...'); self.repository.on('connect', function () { self.emit('connect'); }); self.repository.on('disconnect', function () { self.emit('disconnect'); }); self.repository.connect(callback); }, // prepare revisionGuard... function (callback) { debug('prepare revisionGuard...'); self.revisionGuardStore.on('connect', function () { self.emit('connect'); }); self.revisionGuardStore.on('disconnect', function () { self.emit('disconnect'); }); self.revisionGuardStore.connect(callback); } ], callback); }, // inject all needed dependencies... function (callback) { debug('inject all needed dependencies...'); self.revisionGuard = new RevisionGuard(self.revisionGuardStore, self.options.revisionGuard); self.revisionGuard.onEventMissing(function (info, evt) { self.onEventMissingHandle(info, evt); }); self.eventDispatcher = new EventDispatcher(self.tree, self.definitions.event); self.tree.defineOptions(self.options) .defineEvent(self.definitions.event) .defineNotification(self.definitions.notification) .idGenerator(self.getNewId) .useRepository(self.repository); self.revisionGuard.defineEvent(self.definitions.event); self.replayHandler = new ReplayHandler(self.eventDispatcher, self.revisionGuardStore, self.definitions.event, self.options); callback(null); } ], function (err) { if (err) { debug(err); } if (callback) { callback(err, warnings); } }); }
javascript
function (callback) { var self = this; var warnings = null; async.series([ // load domain files... function (callback) { debug('load denormalizer files..'); self.structureLoader(self.options.denormalizerPath, function (err, tree, warns) { if (err) { return callback(err); } warnings = warns; self.tree = attachLookupFunctions(tree); callback(null); }); }, // prepare infrastructure... function (callback) { debug('prepare infrastructure...'); async.parallel([ // prepare repository... function (callback) { debug('prepare repository...'); self.repository.on('connect', function () { self.emit('connect'); }); self.repository.on('disconnect', function () { self.emit('disconnect'); }); self.repository.connect(callback); }, // prepare revisionGuard... function (callback) { debug('prepare revisionGuard...'); self.revisionGuardStore.on('connect', function () { self.emit('connect'); }); self.revisionGuardStore.on('disconnect', function () { self.emit('disconnect'); }); self.revisionGuardStore.connect(callback); } ], callback); }, // inject all needed dependencies... function (callback) { debug('inject all needed dependencies...'); self.revisionGuard = new RevisionGuard(self.revisionGuardStore, self.options.revisionGuard); self.revisionGuard.onEventMissing(function (info, evt) { self.onEventMissingHandle(info, evt); }); self.eventDispatcher = new EventDispatcher(self.tree, self.definitions.event); self.tree.defineOptions(self.options) .defineEvent(self.definitions.event) .defineNotification(self.definitions.notification) .idGenerator(self.getNewId) .useRepository(self.repository); self.revisionGuard.defineEvent(self.definitions.event); self.replayHandler = new ReplayHandler(self.eventDispatcher, self.revisionGuardStore, self.definitions.event, self.options); callback(null); } ], function (err) { if (err) { debug(err); } if (callback) { callback(err, warnings); } }); }
[ "function", "(", "callback", ")", "{", "var", "self", "=", "this", ";", "var", "warnings", "=", "null", ";", "async", ".", "series", "(", "[", "function", "(", "callback", ")", "{", "debug", "(", "'load denormalizer files..'", ")", ";", "self", ".", "structureLoader", "(", "self", ".", "options", ".", "denormalizerPath", ",", "function", "(", "err", ",", "tree", ",", "warns", ")", "{", "if", "(", "err", ")", "{", "return", "callback", "(", "err", ")", ";", "}", "warnings", "=", "warns", ";", "self", ".", "tree", "=", "attachLookupFunctions", "(", "tree", ")", ";", "callback", "(", "null", ")", ";", "}", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "debug", "(", "'prepare infrastructure...'", ")", ";", "async", ".", "parallel", "(", "[", "function", "(", "callback", ")", "{", "debug", "(", "'prepare repository...'", ")", ";", "self", ".", "repository", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'connect'", ")", ";", "}", ")", ";", "self", ".", "repository", ".", "on", "(", "'disconnect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'disconnect'", ")", ";", "}", ")", ";", "self", ".", "repository", ".", "connect", "(", "callback", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "debug", "(", "'prepare revisionGuard...'", ")", ";", "self", ".", "revisionGuardStore", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'connect'", ")", ";", "}", ")", ";", "self", ".", "revisionGuardStore", ".", "on", "(", "'disconnect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'disconnect'", ")", ";", "}", ")", ";", "self", ".", "revisionGuardStore", ".", "connect", "(", "callback", ")", ";", "}", "]", ",", "callback", ")", ";", "}", ",", "function", "(", "callback", ")", "{", "debug", "(", "'inject all needed dependencies...'", ")", ";", "self", ".", "revisionGuard", "=", "new", "RevisionGuard", "(", "self", ".", "revisionGuardStore", ",", "self", ".", "options", ".", "revisionGuard", ")", ";", "self", ".", "revisionGuard", ".", "onEventMissing", "(", "function", "(", "info", ",", "evt", ")", "{", "self", ".", "onEventMissingHandle", "(", "info", ",", "evt", ")", ";", "}", ")", ";", "self", ".", "eventDispatcher", "=", "new", "EventDispatcher", "(", "self", ".", "tree", ",", "self", ".", "definitions", ".", "event", ")", ";", "self", ".", "tree", ".", "defineOptions", "(", "self", ".", "options", ")", ".", "defineEvent", "(", "self", ".", "definitions", ".", "event", ")", ".", "defineNotification", "(", "self", ".", "definitions", ".", "notification", ")", ".", "idGenerator", "(", "self", ".", "getNewId", ")", ".", "useRepository", "(", "self", ".", "repository", ")", ";", "self", ".", "revisionGuard", ".", "defineEvent", "(", "self", ".", "definitions", ".", "event", ")", ";", "self", ".", "replayHandler", "=", "new", "ReplayHandler", "(", "self", ".", "eventDispatcher", ",", "self", ".", "revisionGuardStore", ",", "self", ".", "definitions", ".", "event", ",", "self", ".", "options", ")", ";", "callback", "(", "null", ")", ";", "}", "]", ",", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "}", "if", "(", "callback", ")", "{", "callback", "(", "err", ",", "warnings", ")", ";", "}", "}", ")", ";", "}" ]
Call this function to initialize the denormalizer. @param {Function} callback the function that will be called when this action has finished [optional] `function(err){}`
[ "Call", "this", "function", "to", "initialize", "the", "denormalizer", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/denormalizer.js#L274-L359
train
adrai/node-cqrs-eventdenormalizer
lib/denormalizer.js
function (callback) { debug('prepare repository...'); self.repository.on('connect', function () { self.emit('connect'); }); self.repository.on('disconnect', function () { self.emit('disconnect'); }); self.repository.connect(callback); }
javascript
function (callback) { debug('prepare repository...'); self.repository.on('connect', function () { self.emit('connect'); }); self.repository.on('disconnect', function () { self.emit('disconnect'); }); self.repository.connect(callback); }
[ "function", "(", "callback", ")", "{", "debug", "(", "'prepare repository...'", ")", ";", "self", ".", "repository", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'connect'", ")", ";", "}", ")", ";", "self", ".", "repository", ".", "on", "(", "'disconnect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'disconnect'", ")", ";", "}", ")", ";", "self", ".", "repository", ".", "connect", "(", "callback", ")", ";", "}" ]
prepare repository...
[ "prepare", "repository", "..." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/denormalizer.js#L300-L312
train
adrai/node-cqrs-eventdenormalizer
lib/denormalizer.js
function (callback) { debug('prepare revisionGuard...'); self.revisionGuardStore.on('connect', function () { self.emit('connect'); }); self.revisionGuardStore.on('disconnect', function () { self.emit('disconnect'); }); self.revisionGuardStore.connect(callback); }
javascript
function (callback) { debug('prepare revisionGuard...'); self.revisionGuardStore.on('connect', function () { self.emit('connect'); }); self.revisionGuardStore.on('disconnect', function () { self.emit('disconnect'); }); self.revisionGuardStore.connect(callback); }
[ "function", "(", "callback", ")", "{", "debug", "(", "'prepare revisionGuard...'", ")", ";", "self", ".", "revisionGuardStore", ".", "on", "(", "'connect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'connect'", ")", ";", "}", ")", ";", "self", ".", "revisionGuardStore", ".", "on", "(", "'disconnect'", ",", "function", "(", ")", "{", "self", ".", "emit", "(", "'disconnect'", ")", ";", "}", ")", ";", "self", ".", "revisionGuardStore", ".", "connect", "(", "callback", ")", ";", "}" ]
prepare revisionGuard...
[ "prepare", "revisionGuard", "..." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/denormalizer.js#L315-L327
train
adrai/node-cqrs-eventdenormalizer
lib/denormalizer.js
function (evt, callback) { var self = this; var extendedEvent = evt; this.extendEventHandle(evt, function (err, extEvt) { if (err) { debug(err); } extendedEvent = extEvt || extendedEvent; var eventExtender = self.tree.getEventExtender(self.eventDispatcher.getTargetInformation(evt)); if (!eventExtender) { return callback(err, extendedEvent); } eventExtender.extend(extendedEvent, function (err, extEvt) { if (err) { debug(err); } extendedEvent = extEvt || extendedEvent; callback(err, extendedEvent); }); }); }
javascript
function (evt, callback) { var self = this; var extendedEvent = evt; this.extendEventHandle(evt, function (err, extEvt) { if (err) { debug(err); } extendedEvent = extEvt || extendedEvent; var eventExtender = self.tree.getEventExtender(self.eventDispatcher.getTargetInformation(evt)); if (!eventExtender) { return callback(err, extendedEvent); } eventExtender.extend(extendedEvent, function (err, extEvt) { if (err) { debug(err); } extendedEvent = extEvt || extendedEvent; callback(err, extendedEvent); }); }); }
[ "function", "(", "evt", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "var", "extendedEvent", "=", "evt", ";", "this", ".", "extendEventHandle", "(", "evt", ",", "function", "(", "err", ",", "extEvt", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "}", "extendedEvent", "=", "extEvt", "||", "extendedEvent", ";", "var", "eventExtender", "=", "self", ".", "tree", ".", "getEventExtender", "(", "self", ".", "eventDispatcher", ".", "getTargetInformation", "(", "evt", ")", ")", ";", "if", "(", "!", "eventExtender", ")", "{", "return", "callback", "(", "err", ",", "extendedEvent", ")", ";", "}", "eventExtender", ".", "extend", "(", "extendedEvent", ",", "function", "(", "err", ",", "extEvt", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "}", "extendedEvent", "=", "extEvt", "||", "extendedEvent", ";", "callback", "(", "err", ",", "extendedEvent", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Call this function to extend the passed event. @param {Object} evt The event object @param {Function} callback The function that will be called when this action has finished [optional] `function(errs, extendedEvent){}`
[ "Call", "this", "function", "to", "extend", "the", "passed", "event", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/denormalizer.js#L381-L408
train
adrai/node-cqrs-eventdenormalizer
lib/denormalizer.js
function (evt, callback) { var self = this; var extendedEvent = evt; var eventExtender = self.tree.getPreEventExtender(self.eventDispatcher.getTargetInformation(evt)); if (!eventExtender) { return callback(null, extendedEvent); } eventExtender.extend(extendedEvent, function (err, extEvt) { if (err) { debug(err); } extendedEvent = extEvt || extendedEvent; callback(err, extendedEvent); }); }
javascript
function (evt, callback) { var self = this; var extendedEvent = evt; var eventExtender = self.tree.getPreEventExtender(self.eventDispatcher.getTargetInformation(evt)); if (!eventExtender) { return callback(null, extendedEvent); } eventExtender.extend(extendedEvent, function (err, extEvt) { if (err) { debug(err); } extendedEvent = extEvt || extendedEvent; callback(err, extendedEvent); }); }
[ "function", "(", "evt", ",", "callback", ")", "{", "var", "self", "=", "this", ";", "var", "extendedEvent", "=", "evt", ";", "var", "eventExtender", "=", "self", ".", "tree", ".", "getPreEventExtender", "(", "self", ".", "eventDispatcher", ".", "getTargetInformation", "(", "evt", ")", ")", ";", "if", "(", "!", "eventExtender", ")", "{", "return", "callback", "(", "null", ",", "extendedEvent", ")", ";", "}", "eventExtender", ".", "extend", "(", "extendedEvent", ",", "function", "(", "err", ",", "extEvt", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "}", "extendedEvent", "=", "extEvt", "||", "extendedEvent", ";", "callback", "(", "err", ",", "extendedEvent", ")", ";", "}", ")", ";", "}" ]
Call this function to pre extend the passed event. @param {Object} evt The event object @param {Function} callback The function that will be called when this action has finished [optional] `function(errs, preExtendedEvent){}`
[ "Call", "this", "function", "to", "pre", "extend", "the", "passed", "event", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/denormalizer.js#L416-L434
train
adrai/node-cqrs-eventdenormalizer
lib/denormalizer.js
function (evt, callback) { if (!evt || !_.isObject(evt)) { var err = new Error('Please pass a valid event!'); debug(err); throw err; } var res = false; var self = this; var evtName = dotty.get(evt, this.definitions.event.name); var evtPayload = dotty.get(evt, this.definitions.event.payload); if (evtName === this.options.commandRejectedEventName && evtPayload && evtPayload.reason && evtPayload.reason.name === 'AggregateDestroyedError') { res = true; var info = { aggregateId: evtPayload.reason.aggregateId, aggregateRevision: evtPayload.reason.aggregateRevision, aggregate: !!this.definitions.event.aggregate ? dotty.get(evt, this.definitions.event.aggregate) : undefined, context: !!this.definitions.event.context ? dotty.get(evt, this.definitions.event.context) : undefined }; if (!this.definitions.event.revision || !dotty.exists(evt, this.definitions.event.revision) || !evtPayload.reason.aggregateId || (typeof evtPayload.reason.aggregateId !== 'string' && typeof evtPayload.reason.aggregateId !== 'number')) { this.onEventMissingHandle(info, evt); if (callback) { callback(null, evt, []); } return res; } this.revisionGuardStore.get(evtPayload.reason.aggregateId, function (err, rev) { if (err) { debug(err); if (callback) { callback([err]) } return; } debug('revision in store is "' + rev + '" but domain says: "' + evtPayload.reason.aggregateRevision + '"') if (rev - 1 < evtPayload.reason.aggregateRevision) { info.guardRevision = rev; self.onEventMissingHandle(info, evt); } else if (rev - 1 > evtPayload.reason.aggregateRevision) { debug('strange: revision in store greater than revision in domain, replay?') } if (callback) { callback(null, evt, []); } }); return res; } return res; }
javascript
function (evt, callback) { if (!evt || !_.isObject(evt)) { var err = new Error('Please pass a valid event!'); debug(err); throw err; } var res = false; var self = this; var evtName = dotty.get(evt, this.definitions.event.name); var evtPayload = dotty.get(evt, this.definitions.event.payload); if (evtName === this.options.commandRejectedEventName && evtPayload && evtPayload.reason && evtPayload.reason.name === 'AggregateDestroyedError') { res = true; var info = { aggregateId: evtPayload.reason.aggregateId, aggregateRevision: evtPayload.reason.aggregateRevision, aggregate: !!this.definitions.event.aggregate ? dotty.get(evt, this.definitions.event.aggregate) : undefined, context: !!this.definitions.event.context ? dotty.get(evt, this.definitions.event.context) : undefined }; if (!this.definitions.event.revision || !dotty.exists(evt, this.definitions.event.revision) || !evtPayload.reason.aggregateId || (typeof evtPayload.reason.aggregateId !== 'string' && typeof evtPayload.reason.aggregateId !== 'number')) { this.onEventMissingHandle(info, evt); if (callback) { callback(null, evt, []); } return res; } this.revisionGuardStore.get(evtPayload.reason.aggregateId, function (err, rev) { if (err) { debug(err); if (callback) { callback([err]) } return; } debug('revision in store is "' + rev + '" but domain says: "' + evtPayload.reason.aggregateRevision + '"') if (rev - 1 < evtPayload.reason.aggregateRevision) { info.guardRevision = rev; self.onEventMissingHandle(info, evt); } else if (rev - 1 > evtPayload.reason.aggregateRevision) { debug('strange: revision in store greater than revision in domain, replay?') } if (callback) { callback(null, evt, []); } }); return res; } return res; }
[ "function", "(", "evt", ",", "callback", ")", "{", "if", "(", "!", "evt", "||", "!", "_", ".", "isObject", "(", "evt", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass a valid event!'", ")", ";", "debug", "(", "err", ")", ";", "throw", "err", ";", "}", "var", "res", "=", "false", ";", "var", "self", "=", "this", ";", "var", "evtName", "=", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "name", ")", ";", "var", "evtPayload", "=", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "payload", ")", ";", "if", "(", "evtName", "===", "this", ".", "options", ".", "commandRejectedEventName", "&&", "evtPayload", "&&", "evtPayload", ".", "reason", "&&", "evtPayload", ".", "reason", ".", "name", "===", "'AggregateDestroyedError'", ")", "{", "res", "=", "true", ";", "var", "info", "=", "{", "aggregateId", ":", "evtPayload", ".", "reason", ".", "aggregateId", ",", "aggregateRevision", ":", "evtPayload", ".", "reason", ".", "aggregateRevision", ",", "aggregate", ":", "!", "!", "this", ".", "definitions", ".", "event", ".", "aggregate", "?", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "aggregate", ")", ":", "undefined", ",", "context", ":", "!", "!", "this", ".", "definitions", ".", "event", ".", "context", "?", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "context", ")", ":", "undefined", "}", ";", "if", "(", "!", "this", ".", "definitions", ".", "event", ".", "revision", "||", "!", "dotty", ".", "exists", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "revision", ")", "||", "!", "evtPayload", ".", "reason", ".", "aggregateId", "||", "(", "typeof", "evtPayload", ".", "reason", ".", "aggregateId", "!==", "'string'", "&&", "typeof", "evtPayload", ".", "reason", ".", "aggregateId", "!==", "'number'", ")", ")", "{", "this", ".", "onEventMissingHandle", "(", "info", ",", "evt", ")", ";", "if", "(", "callback", ")", "{", "callback", "(", "null", ",", "evt", ",", "[", "]", ")", ";", "}", "return", "res", ";", "}", "this", ".", "revisionGuardStore", ".", "get", "(", "evtPayload", ".", "reason", ".", "aggregateId", ",", "function", "(", "err", ",", "rev", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "if", "(", "callback", ")", "{", "callback", "(", "[", "err", "]", ")", "}", "return", ";", "}", "debug", "(", "'revision in store is \"'", "+", "rev", "+", "'\" but domain says: \"'", "+", "evtPayload", ".", "reason", ".", "aggregateRevision", "+", "'\"'", ")", "if", "(", "rev", "-", "1", "<", "evtPayload", ".", "reason", ".", "aggregateRevision", ")", "{", "info", ".", "guardRevision", "=", "rev", ";", "self", ".", "onEventMissingHandle", "(", "info", ",", "evt", ")", ";", "}", "else", "if", "(", "rev", "-", "1", ">", "evtPayload", ".", "reason", ".", "aggregateRevision", ")", "{", "debug", "(", "'strange: revision in store greater than revision in domain, replay?'", ")", "}", "if", "(", "callback", ")", "{", "callback", "(", "null", ",", "evt", ",", "[", "]", ")", ";", "}", "}", ")", ";", "return", "res", ";", "}", "return", "res", ";", "}" ]
Returns true if the passed event is a command rejected event. Callbacks on its own! @param {Object} evt The event object @param {Function} callback The function that will be called when this action has finished [optional] `function(errs, evt, notifications){}` notifications is of type Array @returns {boolean}
[ "Returns", "true", "if", "the", "passed", "event", "is", "a", "command", "rejected", "event", ".", "Callbacks", "on", "its", "own!" ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/denormalizer.js#L443-L503
train
adrai/node-cqrs-eventdenormalizer
lib/denormalizer.js
function (evt, callback) { if (!evt || !_.isObject(evt) || !dotty.exists(evt, this.definitions.event.name)) { var err = new Error('Please pass a valid event!'); debug(err); if (callback) callback([err]); return; } var self = this; if (this.isCommandRejected(evt, callback)) { return; } var workWithRevisionGuard = false; if (!!this.definitions.event.revision && dotty.exists(evt, this.definitions.event.revision) && !!this.definitions.event.aggregateId && dotty.exists(evt, this.definitions.event.aggregateId)) { workWithRevisionGuard = true; } if (dotty.get(evt, this.definitions.event.name) === this.options.commandRejectedEventName) { workWithRevisionGuard = false; } if (!workWithRevisionGuard) { return this.dispatch(evt, callback); } this.revisionGuard.guard(evt, function (err, done) { if (err) { debug(err); if (callback) { try { callback([err]); } catch (e) { debug(e); process.emit('uncaughtException', e); } } return; } self.dispatch(evt, function (errs, extendedEvt, notifications) { if (errs) { debug(errs); if (callback) { try { callback(errs, extendedEvt, notifications); } catch (e) { debug(e); process.emit('uncaughtException', e); } } return; } done(function (err) { if (err) { if (!errs) { errs = [err]; } else if (_.isArray(errs)) { errs.unshift(err); } debug(err); } if (callback) { try { callback(errs, extendedEvt, notifications); } catch (e) { debug(e); process.emit('uncaughtException', e); } } }); }); }); }
javascript
function (evt, callback) { if (!evt || !_.isObject(evt) || !dotty.exists(evt, this.definitions.event.name)) { var err = new Error('Please pass a valid event!'); debug(err); if (callback) callback([err]); return; } var self = this; if (this.isCommandRejected(evt, callback)) { return; } var workWithRevisionGuard = false; if (!!this.definitions.event.revision && dotty.exists(evt, this.definitions.event.revision) && !!this.definitions.event.aggregateId && dotty.exists(evt, this.definitions.event.aggregateId)) { workWithRevisionGuard = true; } if (dotty.get(evt, this.definitions.event.name) === this.options.commandRejectedEventName) { workWithRevisionGuard = false; } if (!workWithRevisionGuard) { return this.dispatch(evt, callback); } this.revisionGuard.guard(evt, function (err, done) { if (err) { debug(err); if (callback) { try { callback([err]); } catch (e) { debug(e); process.emit('uncaughtException', e); } } return; } self.dispatch(evt, function (errs, extendedEvt, notifications) { if (errs) { debug(errs); if (callback) { try { callback(errs, extendedEvt, notifications); } catch (e) { debug(e); process.emit('uncaughtException', e); } } return; } done(function (err) { if (err) { if (!errs) { errs = [err]; } else if (_.isArray(errs)) { errs.unshift(err); } debug(err); } if (callback) { try { callback(errs, extendedEvt, notifications); } catch (e) { debug(e); process.emit('uncaughtException', e); } } }); }); }); }
[ "function", "(", "evt", ",", "callback", ")", "{", "if", "(", "!", "evt", "||", "!", "_", ".", "isObject", "(", "evt", ")", "||", "!", "dotty", ".", "exists", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "name", ")", ")", "{", "var", "err", "=", "new", "Error", "(", "'Please pass a valid event!'", ")", ";", "debug", "(", "err", ")", ";", "if", "(", "callback", ")", "callback", "(", "[", "err", "]", ")", ";", "return", ";", "}", "var", "self", "=", "this", ";", "if", "(", "this", ".", "isCommandRejected", "(", "evt", ",", "callback", ")", ")", "{", "return", ";", "}", "var", "workWithRevisionGuard", "=", "false", ";", "if", "(", "!", "!", "this", ".", "definitions", ".", "event", ".", "revision", "&&", "dotty", ".", "exists", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "revision", ")", "&&", "!", "!", "this", ".", "definitions", ".", "event", ".", "aggregateId", "&&", "dotty", ".", "exists", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "aggregateId", ")", ")", "{", "workWithRevisionGuard", "=", "true", ";", "}", "if", "(", "dotty", ".", "get", "(", "evt", ",", "this", ".", "definitions", ".", "event", ".", "name", ")", "===", "this", ".", "options", ".", "commandRejectedEventName", ")", "{", "workWithRevisionGuard", "=", "false", ";", "}", "if", "(", "!", "workWithRevisionGuard", ")", "{", "return", "this", ".", "dispatch", "(", "evt", ",", "callback", ")", ";", "}", "this", ".", "revisionGuard", ".", "guard", "(", "evt", ",", "function", "(", "err", ",", "done", ")", "{", "if", "(", "err", ")", "{", "debug", "(", "err", ")", ";", "if", "(", "callback", ")", "{", "try", "{", "callback", "(", "[", "err", "]", ")", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "e", ")", ";", "process", ".", "emit", "(", "'uncaughtException'", ",", "e", ")", ";", "}", "}", "return", ";", "}", "self", ".", "dispatch", "(", "evt", ",", "function", "(", "errs", ",", "extendedEvt", ",", "notifications", ")", "{", "if", "(", "errs", ")", "{", "debug", "(", "errs", ")", ";", "if", "(", "callback", ")", "{", "try", "{", "callback", "(", "errs", ",", "extendedEvt", ",", "notifications", ")", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "e", ")", ";", "process", ".", "emit", "(", "'uncaughtException'", ",", "e", ")", ";", "}", "}", "return", ";", "}", "done", "(", "function", "(", "err", ")", "{", "if", "(", "err", ")", "{", "if", "(", "!", "errs", ")", "{", "errs", "=", "[", "err", "]", ";", "}", "else", "if", "(", "_", ".", "isArray", "(", "errs", ")", ")", "{", "errs", ".", "unshift", "(", "err", ")", ";", "}", "debug", "(", "err", ")", ";", "}", "if", "(", "callback", ")", "{", "try", "{", "callback", "(", "errs", ",", "extendedEvt", ",", "notifications", ")", ";", "}", "catch", "(", "e", ")", "{", "debug", "(", "e", ")", ";", "process", ".", "emit", "(", "'uncaughtException'", ",", "e", ")", ";", "}", "}", "}", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Call this function to let the denormalizer handle it. @param {Object} evt The event object @param {Function} callback The function that will be called when this action has finished [optional] `function(errs, evt, notifications){}` notifications is of type Array
[ "Call", "this", "function", "to", "let", "the", "denormalizer", "handle", "it", "." ]
fd3411044e0673bd1b3613832599d6e85c456fea
https://github.com/adrai/node-cqrs-eventdenormalizer/blob/fd3411044e0673bd1b3613832599d6e85c456fea/lib/denormalizer.js#L596-L673
train
emfjson/ecore.js
src/ecore.js
function(attributes) { if (!attributes) attributes = {}; this.eClass = attributes.eClass; this.values = {}; // stores function for eOperations. attributes._ && (this._ = attributes._); // Initialize values according to the eClass features. initValues(this); setValues(this, attributes); initOperations(this); return this; }
javascript
function(attributes) { if (!attributes) attributes = {}; this.eClass = attributes.eClass; this.values = {}; // stores function for eOperations. attributes._ && (this._ = attributes._); // Initialize values according to the eClass features. initValues(this); setValues(this, attributes); initOperations(this); return this; }
[ "function", "(", "attributes", ")", "{", "if", "(", "!", "attributes", ")", "attributes", "=", "{", "}", ";", "this", ".", "eClass", "=", "attributes", ".", "eClass", ";", "this", ".", "values", "=", "{", "}", ";", "attributes", ".", "_", "&&", "(", "this", ".", "_", "=", "attributes", ".", "_", ")", ";", "initValues", "(", "this", ")", ";", "setValues", "(", "this", ",", "attributes", ")", ";", "initOperations", "(", "this", ")", ";", "return", "this", ";", "}" ]
EObject Implementation of EObject. The constructor takes as parameter a hash containing values to be set. Values must be defined accordingly to the eClass features.
[ "EObject", "Implementation", "of", "EObject", ".", "The", "constructor", "takes", "as", "parameter", "a", "hash", "containing", "values", "to", "be", "set", ".", "Values", "must", "be", "defined", "accordingly", "to", "the", "eClass", "features", "." ]
c039974fc08389b153b4765764c97e66f051dc1c
https://github.com/emfjson/ecore.js/blob/c039974fc08389b153b4765764c97e66f051dc1c/src/ecore.js#L157-L172
train
emfjson/ecore.js
src/ecore.js
function(name) { if (!this.has(name)) return false; var eClass = this.eClass; if (!eClass) return false; var value = this.get(name); if (value instanceof EList) { return value.size() > 0; } else { return value !== null && typeof value !== 'undefined'; } }
javascript
function(name) { if (!this.has(name)) return false; var eClass = this.eClass; if (!eClass) return false; var value = this.get(name); if (value instanceof EList) { return value.size() > 0; } else { return value !== null && typeof value !== 'undefined'; } }
[ "function", "(", "name", ")", "{", "if", "(", "!", "this", ".", "has", "(", "name", ")", ")", "return", "false", ";", "var", "eClass", "=", "this", ".", "eClass", ";", "if", "(", "!", "eClass", ")", "return", "false", ";", "var", "value", "=", "this", ".", "get", "(", "name", ")", ";", "if", "(", "value", "instanceof", "EList", ")", "{", "return", "value", ".", "size", "(", ")", ">", "0", ";", "}", "else", "{", "return", "value", "!==", "null", "&&", "typeof", "value", "!==", "'undefined'", ";", "}", "}" ]
Returns true if property has its value set. @method isSet @param {String} name @return {Boolean}
[ "Returns", "true", "if", "property", "has", "its", "value", "set", "." ]
c039974fc08389b153b4765764c97e66f051dc1c
https://github.com/emfjson/ecore.js/blob/c039974fc08389b153b4765764c97e66f051dc1c/src/ecore.js#L328-L340
train
emfjson/ecore.js
src/ecore.js
function(attrs, options) { var attr, key, val, eve; if (attrs === null) return this; if (attrs.eClass) { attrs = attrs.get('name'); } // Handle attrs is a hash or attrs is // property and options the value to be set. if (!_.isObject(attrs)) { key = attrs; (attrs = {})[key] = options; } var eResource = this.eResource(); for (attr in attrs) { val = attrs[attr]; if (typeof val !== 'undefined' && this.has(attr)) { if (this.isSet(attr)) { this.unset(attr); } var feature = getEStructuralFeature(this.eClass, attr), isContainment = feature.get('containment'); var settingContainmentAttribute = (attr === 'containment') && (typeof(val) === 'string') && (this.eClass.values.name === 'EReference'); if (settingContainmentAttribute) { // Convert string 'true' to boolean true val = (val.toLowerCase() === 'true'); } this.values[attr] = val; if (isContainment) { val.eContainingFeature = feature; val.eContainer = this; } eve = 'change:' + attr; this.trigger('change ' + eve, attr); if (eResource) eResource.trigger('change', this); } } return this; }
javascript
function(attrs, options) { var attr, key, val, eve; if (attrs === null) return this; if (attrs.eClass) { attrs = attrs.get('name'); } // Handle attrs is a hash or attrs is // property and options the value to be set. if (!_.isObject(attrs)) { key = attrs; (attrs = {})[key] = options; } var eResource = this.eResource(); for (attr in attrs) { val = attrs[attr]; if (typeof val !== 'undefined' && this.has(attr)) { if (this.isSet(attr)) { this.unset(attr); } var feature = getEStructuralFeature(this.eClass, attr), isContainment = feature.get('containment'); var settingContainmentAttribute = (attr === 'containment') && (typeof(val) === 'string') && (this.eClass.values.name === 'EReference'); if (settingContainmentAttribute) { // Convert string 'true' to boolean true val = (val.toLowerCase() === 'true'); } this.values[attr] = val; if (isContainment) { val.eContainingFeature = feature; val.eContainer = this; } eve = 'change:' + attr; this.trigger('change ' + eve, attr); if (eResource) eResource.trigger('change', this); } } return this; }
[ "function", "(", "attrs", ",", "options", ")", "{", "var", "attr", ",", "key", ",", "val", ",", "eve", ";", "if", "(", "attrs", "===", "null", ")", "return", "this", ";", "if", "(", "attrs", ".", "eClass", ")", "{", "attrs", "=", "attrs", ".", "get", "(", "'name'", ")", ";", "}", "if", "(", "!", "_", ".", "isObject", "(", "attrs", ")", ")", "{", "key", "=", "attrs", ";", "(", "attrs", "=", "{", "}", ")", "[", "key", "]", "=", "options", ";", "}", "var", "eResource", "=", "this", ".", "eResource", "(", ")", ";", "for", "(", "attr", "in", "attrs", ")", "{", "val", "=", "attrs", "[", "attr", "]", ";", "if", "(", "typeof", "val", "!==", "'undefined'", "&&", "this", ".", "has", "(", "attr", ")", ")", "{", "if", "(", "this", ".", "isSet", "(", "attr", ")", ")", "{", "this", ".", "unset", "(", "attr", ")", ";", "}", "var", "feature", "=", "getEStructuralFeature", "(", "this", ".", "eClass", ",", "attr", ")", ",", "isContainment", "=", "feature", ".", "get", "(", "'containment'", ")", ";", "var", "settingContainmentAttribute", "=", "(", "attr", "===", "'containment'", ")", "&&", "(", "typeof", "(", "val", ")", "===", "'string'", ")", "&&", "(", "this", ".", "eClass", ".", "values", ".", "name", "===", "'EReference'", ")", ";", "if", "(", "settingContainmentAttribute", ")", "{", "val", "=", "(", "val", ".", "toLowerCase", "(", ")", "===", "'true'", ")", ";", "}", "this", ".", "values", "[", "attr", "]", "=", "val", ";", "if", "(", "isContainment", ")", "{", "val", ".", "eContainingFeature", "=", "feature", ";", "val", ".", "eContainer", "=", "this", ";", "}", "eve", "=", "'change:'", "+", "attr", ";", "this", ".", "trigger", "(", "'change '", "+", "eve", ",", "attr", ")", ";", "if", "(", "eResource", ")", "eResource", ".", "trigger", "(", "'change'", ",", "this", ")", ";", "}", "}", "return", "this", ";", "}" ]
Setter for the property identified by the first parameter. @method set @param {String} name @param {Object} value @return {EObject}
[ "Setter", "for", "the", "property", "identified", "by", "the", "first", "parameter", "." ]
c039974fc08389b153b4765764c97e66f051dc1c
https://github.com/emfjson/ecore.js/blob/c039974fc08389b153b4765764c97e66f051dc1c/src/ecore.js#L349-L395
train
emfjson/ecore.js
src/ecore.js
function(attrs, options) { var attr, key, eve; if (attrs === null) return this; if (attrs.eClass) { attrs = attrs.get('name'); } // Handle attrs is a hash or attrs is // property and options the value to be set. if (!_.isObject(attrs)) { key = attrs; (attrs = {})[key] = undefined; } var eResource = this.eResource(); for (attr in attrs) { if (this.has(attr) && this.isSet(attr)) { // unset var feature = getEStructuralFeature(this.eClass, attr), isContainment = Boolean(feature.get('containment')) === true; var value = this.values[attr]; if (isContainment) { value.eContainingFeature = undefined; value.eContainer = undefined; } this.values[attr] = undefined; eve = 'unset:' + attr; this.trigger('unset ' + eve, attr); if (eResource) eResource.trigger('change', this); } } return this; }
javascript
function(attrs, options) { var attr, key, eve; if (attrs === null) return this; if (attrs.eClass) { attrs = attrs.get('name'); } // Handle attrs is a hash or attrs is // property and options the value to be set. if (!_.isObject(attrs)) { key = attrs; (attrs = {})[key] = undefined; } var eResource = this.eResource(); for (attr in attrs) { if (this.has(attr) && this.isSet(attr)) { // unset var feature = getEStructuralFeature(this.eClass, attr), isContainment = Boolean(feature.get('containment')) === true; var value = this.values[attr]; if (isContainment) { value.eContainingFeature = undefined; value.eContainer = undefined; } this.values[attr] = undefined; eve = 'unset:' + attr; this.trigger('unset ' + eve, attr); if (eResource) eResource.trigger('change', this); } } return this; }
[ "function", "(", "attrs", ",", "options", ")", "{", "var", "attr", ",", "key", ",", "eve", ";", "if", "(", "attrs", "===", "null", ")", "return", "this", ";", "if", "(", "attrs", ".", "eClass", ")", "{", "attrs", "=", "attrs", ".", "get", "(", "'name'", ")", ";", "}", "if", "(", "!", "_", ".", "isObject", "(", "attrs", ")", ")", "{", "key", "=", "attrs", ";", "(", "attrs", "=", "{", "}", ")", "[", "key", "]", "=", "undefined", ";", "}", "var", "eResource", "=", "this", ".", "eResource", "(", ")", ";", "for", "(", "attr", "in", "attrs", ")", "{", "if", "(", "this", ".", "has", "(", "attr", ")", "&&", "this", ".", "isSet", "(", "attr", ")", ")", "{", "var", "feature", "=", "getEStructuralFeature", "(", "this", ".", "eClass", ",", "attr", ")", ",", "isContainment", "=", "Boolean", "(", "feature", ".", "get", "(", "'containment'", ")", ")", "===", "true", ";", "var", "value", "=", "this", ".", "values", "[", "attr", "]", ";", "if", "(", "isContainment", ")", "{", "value", ".", "eContainingFeature", "=", "undefined", ";", "value", ".", "eContainer", "=", "undefined", ";", "}", "this", ".", "values", "[", "attr", "]", "=", "undefined", ";", "eve", "=", "'unset:'", "+", "attr", ";", "this", ".", "trigger", "(", "'unset '", "+", "eve", ",", "attr", ")", ";", "if", "(", "eResource", ")", "eResource", ".", "trigger", "(", "'change'", ",", "this", ")", ";", "}", "}", "return", "this", ";", "}" ]
Unset for the property identified by the first parameter. @method unset @param {String} name @return {EObject}
[ "Unset", "for", "the", "property", "identified", "by", "the", "first", "parameter", "." ]
c039974fc08389b153b4765764c97e66f051dc1c
https://github.com/emfjson/ecore.js/blob/c039974fc08389b153b4765764c97e66f051dc1c/src/ecore.js#L402-L440
train
emfjson/ecore.js
src/ecore.js
function(feature) { if (!feature) return null; var featureName = feature.eClass ? feature.get('name') : feature; if (!_.has(this.values, featureName) && this.has(featureName)) { initValue(this, getEStructuralFeature(this.eClass, featureName)); } var value = this.values[featureName]; if (typeof value === 'function') { return value.apply(this); } else { return value; } }
javascript
function(feature) { if (!feature) return null; var featureName = feature.eClass ? feature.get('name') : feature; if (!_.has(this.values, featureName) && this.has(featureName)) { initValue(this, getEStructuralFeature(this.eClass, featureName)); } var value = this.values[featureName]; if (typeof value === 'function') { return value.apply(this); } else { return value; } }
[ "function", "(", "feature", ")", "{", "if", "(", "!", "feature", ")", "return", "null", ";", "var", "featureName", "=", "feature", ".", "eClass", "?", "feature", ".", "get", "(", "'name'", ")", ":", "feature", ";", "if", "(", "!", "_", ".", "has", "(", "this", ".", "values", ",", "featureName", ")", "&&", "this", ".", "has", "(", "featureName", ")", ")", "{", "initValue", "(", "this", ",", "getEStructuralFeature", "(", "this", ".", "eClass", ",", "featureName", ")", ")", ";", "}", "var", "value", "=", "this", ".", "values", "[", "featureName", "]", ";", "if", "(", "typeof", "value", "===", "'function'", ")", "{", "return", "value", ".", "apply", "(", "this", ")", ";", "}", "else", "{", "return", "value", ";", "}", "}" ]
Getter for the property identified by the first parameter. @method get @param {EStructuralFeature} feature or @param {String} feature name @return {Object}
[ "Getter", "for", "the", "property", "identified", "by", "the", "first", "parameter", "." ]
c039974fc08389b153b4765764c97e66f051dc1c
https://github.com/emfjson/ecore.js/blob/c039974fc08389b153b4765764c97e66f051dc1c/src/ecore.js#L452-L468
train
emfjson/ecore.js
src/ecore.js
function(type) { if (!type || !this.eClass) return false; var typeName = type.eClass ? type.get('name') : type; return this.eClass.get('name') === typeName; }
javascript
function(type) { if (!type || !this.eClass) return false; var typeName = type.eClass ? type.get('name') : type; return this.eClass.get('name') === typeName; }
[ "function", "(", "type", ")", "{", "if", "(", "!", "type", "||", "!", "this", ".", "eClass", ")", "return", "false", ";", "var", "typeName", "=", "type", ".", "eClass", "?", "type", ".", "get", "(", "'name'", ")", ":", "type", ";", "return", "this", ".", "eClass", ".", "get", "(", "'name'", ")", "===", "typeName", ";", "}" ]
Returns true if the EObject is a direct instance of the EClass. @method isTypeOf @param {String} type @return {Boolean}
[ "Returns", "true", "if", "the", "EObject", "is", "a", "direct", "instance", "of", "the", "EClass", "." ]
c039974fc08389b153b4765764c97e66f051dc1c
https://github.com/emfjson/ecore.js/blob/c039974fc08389b153b4765764c97e66f051dc1c/src/ecore.js#L476-L482
train
emfjson/ecore.js
src/ecore.js
function(type) { if(!type || !this.eClass) return false; if (this.isTypeOf(type)) return true; var typeName = type.eClass ? type.get('name') : type, superTypes = this.eClass.get('eAllSuperTypes'); return _.any(superTypes, function(eSuper) { return eSuper.get('name') === typeName; }); }
javascript
function(type) { if(!type || !this.eClass) return false; if (this.isTypeOf(type)) return true; var typeName = type.eClass ? type.get('name') : type, superTypes = this.eClass.get('eAllSuperTypes'); return _.any(superTypes, function(eSuper) { return eSuper.get('name') === typeName; }); }
[ "function", "(", "type", ")", "{", "if", "(", "!", "type", "||", "!", "this", ".", "eClass", ")", "return", "false", ";", "if", "(", "this", ".", "isTypeOf", "(", "type", ")", ")", "return", "true", ";", "var", "typeName", "=", "type", ".", "eClass", "?", "type", ".", "get", "(", "'name'", ")", ":", "type", ",", "superTypes", "=", "this", ".", "eClass", ".", "get", "(", "'eAllSuperTypes'", ")", ";", "return", "_", ".", "any", "(", "superTypes", ",", "function", "(", "eSuper", ")", "{", "return", "eSuper", ".", "get", "(", "'name'", ")", "===", "typeName", ";", "}", ")", ";", "}" ]
Returns true if the EObject is an direct instance of the EClass or if it is part of the class hierarchy. @method isKindOf @param {String} @return {Boolean}
[ "Returns", "true", "if", "the", "EObject", "is", "an", "direct", "instance", "of", "the", "EClass", "or", "if", "it", "is", "part", "of", "the", "class", "hierarchy", "." ]
c039974fc08389b153b4765764c97e66f051dc1c
https://github.com/emfjson/ecore.js/blob/c039974fc08389b153b4765764c97e66f051dc1c/src/ecore.js#L491-L501
train
emfjson/ecore.js
src/ecore.js
function() { if (!this.eClass) return []; if (_.isUndefined(this.__updateContents)) { this.__updateContents = true; var resource = this.eResource(); if (resource) { var me = this; resource.on('add remove', function() { me.__updateContents = true; }) } } if (this.__updateContents) { var eAllFeatures = this.eClass.get('eAllStructuralFeatures'); var eContainments = _.filter(eAllFeatures, function(feature) { return feature.isTypeOf('EReference') && feature.get('containment') && this.isSet(feature.get('name')); }, this); var value = null; this.__eContents = _.flatten(_.map(eContainments, function(c) { value = this.get(c.get('name')); return value ? (value.array ? value.array() : value) : []; }, this)); this.__updateContents = false; } return this.__eContents; }
javascript
function() { if (!this.eClass) return []; if (_.isUndefined(this.__updateContents)) { this.__updateContents = true; var resource = this.eResource(); if (resource) { var me = this; resource.on('add remove', function() { me.__updateContents = true; }) } } if (this.__updateContents) { var eAllFeatures = this.eClass.get('eAllStructuralFeatures'); var eContainments = _.filter(eAllFeatures, function(feature) { return feature.isTypeOf('EReference') && feature.get('containment') && this.isSet(feature.get('name')); }, this); var value = null; this.__eContents = _.flatten(_.map(eContainments, function(c) { value = this.get(c.get('name')); return value ? (value.array ? value.array() : value) : []; }, this)); this.__updateContents = false; } return this.__eContents; }
[ "function", "(", ")", "{", "if", "(", "!", "this", ".", "eClass", ")", "return", "[", "]", ";", "if", "(", "_", ".", "isUndefined", "(", "this", ".", "__updateContents", ")", ")", "{", "this", ".", "__updateContents", "=", "true", ";", "var", "resource", "=", "this", ".", "eResource", "(", ")", ";", "if", "(", "resource", ")", "{", "var", "me", "=", "this", ";", "resource", ".", "on", "(", "'add remove'", ",", "function", "(", ")", "{", "me", ".", "__updateContents", "=", "true", ";", "}", ")", "}", "}", "if", "(", "this", ".", "__updateContents", ")", "{", "var", "eAllFeatures", "=", "this", ".", "eClass", ".", "get", "(", "'eAllStructuralFeatures'", ")", ";", "var", "eContainments", "=", "_", ".", "filter", "(", "eAllFeatures", ",", "function", "(", "feature", ")", "{", "return", "feature", ".", "isTypeOf", "(", "'EReference'", ")", "&&", "feature", ".", "get", "(", "'containment'", ")", "&&", "this", ".", "isSet", "(", "feature", ".", "get", "(", "'name'", ")", ")", ";", "}", ",", "this", ")", ";", "var", "value", "=", "null", ";", "this", ".", "__eContents", "=", "_", ".", "flatten", "(", "_", ".", "map", "(", "eContainments", ",", "function", "(", "c", ")", "{", "value", "=", "this", ".", "get", "(", "c", ".", "get", "(", "'name'", ")", ")", ";", "return", "value", "?", "(", "value", ".", "array", "?", "value", ".", "array", "(", ")", ":", "value", ")", ":", "[", "]", ";", "}", ",", "this", ")", ")", ";", "this", ".", "__updateContents", "=", "false", ";", "}", "return", "this", ".", "__eContents", ";", "}" ]
Returns the content of an EObject. @method eContents @return {Array}
[ "Returns", "the", "content", "of", "an", "EObject", "." ]
c039974fc08389b153b4765764c97e66f051dc1c
https://github.com/emfjson/ecore.js/blob/c039974fc08389b153b4765764c97e66f051dc1c/src/ecore.js#L521-L554
train
emfjson/ecore.js
src/ecore.js
function() { var eContainer = this.eContainer, eClass = this.eClass, iD = eClass.get('eIDAttribute'), eFeature, contents, fragment; // Must be at least contain in a Resource or EObject. if (!eContainer) return null; // Use ID has fragment if (iD) return this.get(iD.get('name')); if (this._id) return this._id; // ModelElement uses names except for roots if (this.isKindOf('EModelElement')) { if (!eContainer) { return '/'; } else if (eContainer.isKindOf('Resource')) { contents = eContainer.get('contents'); return contents.size() > 1 ? '/' + contents.indexOf(this) : '/'; } else { return eContainer.fragment() + '/' + this.get('name'); } } // Default fragments if (eContainer.isKindOf('Resource')) { contents = eContainer.get('contents'); fragment = contents.size() > 1 ? '/' + contents.indexOf(this) : '/'; } else { eFeature = this.eContainingFeature; if (eFeature) { fragment = eContainer.fragment() + '/@' + eFeature.get('name'); if (eFeature.get('upperBound') !== 1) { fragment += '.' + eContainer.get(eFeature.get('name')).indexOf(this); } } } return fragment; }
javascript
function() { var eContainer = this.eContainer, eClass = this.eClass, iD = eClass.get('eIDAttribute'), eFeature, contents, fragment; // Must be at least contain in a Resource or EObject. if (!eContainer) return null; // Use ID has fragment if (iD) return this.get(iD.get('name')); if (this._id) return this._id; // ModelElement uses names except for roots if (this.isKindOf('EModelElement')) { if (!eContainer) { return '/'; } else if (eContainer.isKindOf('Resource')) { contents = eContainer.get('contents'); return contents.size() > 1 ? '/' + contents.indexOf(this) : '/'; } else { return eContainer.fragment() + '/' + this.get('name'); } } // Default fragments if (eContainer.isKindOf('Resource')) { contents = eContainer.get('contents'); fragment = contents.size() > 1 ? '/' + contents.indexOf(this) : '/'; } else { eFeature = this.eContainingFeature; if (eFeature) { fragment = eContainer.fragment() + '/@' + eFeature.get('name'); if (eFeature.get('upperBound') !== 1) { fragment += '.' + eContainer.get(eFeature.get('name')).indexOf(this); } } } return fragment; }
[ "function", "(", ")", "{", "var", "eContainer", "=", "this", ".", "eContainer", ",", "eClass", "=", "this", ".", "eClass", ",", "iD", "=", "eClass", ".", "get", "(", "'eIDAttribute'", ")", ",", "eFeature", ",", "contents", ",", "fragment", ";", "if", "(", "!", "eContainer", ")", "return", "null", ";", "if", "(", "iD", ")", "return", "this", ".", "get", "(", "iD", ".", "get", "(", "'name'", ")", ")", ";", "if", "(", "this", ".", "_id", ")", "return", "this", ".", "_id", ";", "if", "(", "this", ".", "isKindOf", "(", "'EModelElement'", ")", ")", "{", "if", "(", "!", "eContainer", ")", "{", "return", "'/'", ";", "}", "else", "if", "(", "eContainer", ".", "isKindOf", "(", "'Resource'", ")", ")", "{", "contents", "=", "eContainer", ".", "get", "(", "'contents'", ")", ";", "return", "contents", ".", "size", "(", ")", ">", "1", "?", "'/'", "+", "contents", ".", "indexOf", "(", "this", ")", ":", "'/'", ";", "}", "else", "{", "return", "eContainer", ".", "fragment", "(", ")", "+", "'/'", "+", "this", ".", "get", "(", "'name'", ")", ";", "}", "}", "if", "(", "eContainer", ".", "isKindOf", "(", "'Resource'", ")", ")", "{", "contents", "=", "eContainer", ".", "get", "(", "'contents'", ")", ";", "fragment", "=", "contents", ".", "size", "(", ")", ">", "1", "?", "'/'", "+", "contents", ".", "indexOf", "(", "this", ")", ":", "'/'", ";", "}", "else", "{", "eFeature", "=", "this", ".", "eContainingFeature", ";", "if", "(", "eFeature", ")", "{", "fragment", "=", "eContainer", ".", "fragment", "(", ")", "+", "'/@'", "+", "eFeature", ".", "get", "(", "'name'", ")", ";", "if", "(", "eFeature", ".", "get", "(", "'upperBound'", ")", "!==", "1", ")", "{", "fragment", "+=", "'.'", "+", "eContainer", ".", "get", "(", "eFeature", ".", "get", "(", "'name'", ")", ")", ".", "indexOf", "(", "this", ")", ";", "}", "}", "}", "return", "fragment", ";", "}" ]
Returns the fragment identifier of the EObject. @return {String}
[ "Returns", "the", "fragment", "identifier", "of", "the", "EObject", "." ]
c039974fc08389b153b4765764c97e66f051dc1c
https://github.com/emfjson/ecore.js/blob/c039974fc08389b153b4765764c97e66f051dc1c/src/ecore.js#L579-L622
train
emfjson/ecore.js
src/ecore.js
function(eObject) { if (!eObject || !eObject instanceof EObject) return this; if (this._isContainment) { eObject.eContainingFeature = this._feature; eObject.eContainer = this._owner; } this._size++; this._internal.push(eObject); var eResource = this._owner.eResource(), eve = 'add'; if (this._feature) eve += ':' + this._feature.get('name'); this._owner.trigger(eve, eObject); if (eResource) eResource.trigger('add', this); return this; }
javascript
function(eObject) { if (!eObject || !eObject instanceof EObject) return this; if (this._isContainment) { eObject.eContainingFeature = this._feature; eObject.eContainer = this._owner; } this._size++; this._internal.push(eObject); var eResource = this._owner.eResource(), eve = 'add'; if (this._feature) eve += ':' + this._feature.get('name'); this._owner.trigger(eve, eObject); if (eResource) eResource.trigger('add', this); return this; }
[ "function", "(", "eObject", ")", "{", "if", "(", "!", "eObject", "||", "!", "eObject", "instanceof", "EObject", ")", "return", "this", ";", "if", "(", "this", ".", "_isContainment", ")", "{", "eObject", ".", "eContainingFeature", "=", "this", ".", "_feature", ";", "eObject", ".", "eContainer", "=", "this", ".", "_owner", ";", "}", "this", ".", "_size", "++", ";", "this", ".", "_internal", ".", "push", "(", "eObject", ")", ";", "var", "eResource", "=", "this", ".", "_owner", ".", "eResource", "(", ")", ",", "eve", "=", "'add'", ";", "if", "(", "this", ".", "_feature", ")", "eve", "+=", "':'", "+", "this", ".", "_feature", ".", "get", "(", "'name'", ")", ";", "this", ".", "_owner", ".", "trigger", "(", "eve", ",", "eObject", ")", ";", "if", "(", "eResource", ")", "eResource", ".", "trigger", "(", "'add'", ",", "this", ")", ";", "return", "this", ";", "}" ]
Adds an EObject. @method add @public @param {EObject} eObject
[ "Adds", "an", "EObject", "." ]
c039974fc08389b153b4765764c97e66f051dc1c
https://github.com/emfjson/ecore.js/blob/c039974fc08389b153b4765764c97e66f051dc1c/src/ecore.js#L667-L686
train
emfjson/ecore.js
src/ecore.js
function(eObject) { var eve = 'remove', eResource = this._owner.eResource(); this._internal = _.without(this._internal, eObject); this._size = this._size - 1; if (this._feature) eve += ':' + this._feature.get('name'); this._owner.trigger(eve, eObject); if (eResource) eResource.trigger('remove', this); return this; }
javascript
function(eObject) { var eve = 'remove', eResource = this._owner.eResource(); this._internal = _.without(this._internal, eObject); this._size = this._size - 1; if (this._feature) eve += ':' + this._feature.get('name'); this._owner.trigger(eve, eObject); if (eResource) eResource.trigger('remove', this); return this; }
[ "function", "(", "eObject", ")", "{", "var", "eve", "=", "'remove'", ",", "eResource", "=", "this", ".", "_owner", ".", "eResource", "(", ")", ";", "this", ".", "_internal", "=", "_", ".", "without", "(", "this", ".", "_internal", ",", "eObject", ")", ";", "this", ".", "_size", "=", "this", ".", "_size", "-", "1", ";", "if", "(", "this", ".", "_feature", ")", "eve", "+=", "':'", "+", "this", ".", "_feature", ".", "get", "(", "'name'", ")", ";", "this", ".", "_owner", ".", "trigger", "(", "eve", ",", "eObject", ")", ";", "if", "(", "eResource", ")", "eResource", ".", "trigger", "(", "'remove'", ",", "this", ")", ";", "return", "this", ";", "}" ]
Removes given element from the EList @public @param {EObject}
[ "Removes", "given", "element", "from", "the", "EList" ]
c039974fc08389b153b4765764c97e66f051dc1c
https://github.com/emfjson/ecore.js/blob/c039974fc08389b153b4765764c97e66f051dc1c/src/ecore.js#L706-L717
train
preciousforever/SVG-Cleaner
lib/svg-cleaner.js
searchForComment
function searchForComment(node) { if(node.type == 'comment') { commentNodes.push(node); } if(!_(node.children).isUndefined()) { _.each(node.children, searchForComment); } }
javascript
function searchForComment(node) { if(node.type == 'comment') { commentNodes.push(node); } if(!_(node.children).isUndefined()) { _.each(node.children, searchForComment); } }
[ "function", "searchForComment", "(", "node", ")", "{", "if", "(", "node", ".", "type", "==", "'comment'", ")", "{", "commentNodes", ".", "push", "(", "node", ")", ";", "}", "if", "(", "!", "_", "(", "node", ".", "children", ")", ".", "isUndefined", "(", ")", ")", "{", "_", ".", "each", "(", "node", ".", "children", ",", "searchForComment", ")", ";", "}", "}" ]
process on NODE level
[ "process", "on", "NODE", "level" ]
0efe0486f878f2fb396b00ae1823b517c19c0fac
https://github.com/preciousforever/SVG-Cleaner/blob/0efe0486f878f2fb396b00ae1823b517c19c0fac/lib/svg-cleaner.js#L467-L474
train
preciousforever/SVG-Cleaner
lib/svg-cleaner.js
removeStyleProperties
function removeStyleProperties(styles, properties) { _(styles).each(function(value, key) { if(_(properties).include(key)) { delete styles[key] } }); return styles; }
javascript
function removeStyleProperties(styles, properties) { _(styles).each(function(value, key) { if(_(properties).include(key)) { delete styles[key] } }); return styles; }
[ "function", "removeStyleProperties", "(", "styles", ",", "properties", ")", "{", "_", "(", "styles", ")", ".", "each", "(", "function", "(", "value", ",", "key", ")", "{", "if", "(", "_", "(", "properties", ")", ".", "include", "(", "key", ")", ")", "{", "delete", "styles", "[", "key", "]", "}", "}", ")", ";", "return", "styles", ";", "}" ]
removes properties, by a given list of keys
[ "removes", "properties", "by", "a", "given", "list", "of", "keys" ]
0efe0486f878f2fb396b00ae1823b517c19c0fac
https://github.com/preciousforever/SVG-Cleaner/blob/0efe0486f878f2fb396b00ae1823b517c19c0fac/lib/svg-cleaner.js#L515-L522
train
emfjson/ecore.js
src/resource.js
buildIndex
function buildIndex(model) { var index = {}, contents = model.get('contents').array(); if (contents.length) { var build = function(object, idx) { var eContents = object.eContents(); index[idx] = object; _.each(eContents, function(e) { build(e, e.fragment()); }); }; var root, iD; if (contents.length === 1) { root = contents[0]; if (root._id) { build(root, root._id); } else { iD = root.eClass.get('eIDAttribute') || null; if (iD) { build(root, root.get(iD.get('name'))); } else { build(root, '/'); } } } else { for (var i = 0; i < contents.length; i++) { root = contents[i]; if (root._id) { build(root, root._id); } else { iD = root.eClass.get('eIDAttribute') || null; if (iD) { build(root, root.get(iD.get('name'))); } else { build(root, '/' + i); } } } } } return index; }
javascript
function buildIndex(model) { var index = {}, contents = model.get('contents').array(); if (contents.length) { var build = function(object, idx) { var eContents = object.eContents(); index[idx] = object; _.each(eContents, function(e) { build(e, e.fragment()); }); }; var root, iD; if (contents.length === 1) { root = contents[0]; if (root._id) { build(root, root._id); } else { iD = root.eClass.get('eIDAttribute') || null; if (iD) { build(root, root.get(iD.get('name'))); } else { build(root, '/'); } } } else { for (var i = 0; i < contents.length; i++) { root = contents[i]; if (root._id) { build(root, root._id); } else { iD = root.eClass.get('eIDAttribute') || null; if (iD) { build(root, root.get(iD.get('name'))); } else { build(root, '/' + i); } } } } } return index; }
[ "function", "buildIndex", "(", "model", ")", "{", "var", "index", "=", "{", "}", ",", "contents", "=", "model", ".", "get", "(", "'contents'", ")", ".", "array", "(", ")", ";", "if", "(", "contents", ".", "length", ")", "{", "var", "build", "=", "function", "(", "object", ",", "idx", ")", "{", "var", "eContents", "=", "object", ".", "eContents", "(", ")", ";", "index", "[", "idx", "]", "=", "object", ";", "_", ".", "each", "(", "eContents", ",", "function", "(", "e", ")", "{", "build", "(", "e", ",", "e", ".", "fragment", "(", ")", ")", ";", "}", ")", ";", "}", ";", "var", "root", ",", "iD", ";", "if", "(", "contents", ".", "length", "===", "1", ")", "{", "root", "=", "contents", "[", "0", "]", ";", "if", "(", "root", ".", "_id", ")", "{", "build", "(", "root", ",", "root", ".", "_id", ")", ";", "}", "else", "{", "iD", "=", "root", ".", "eClass", ".", "get", "(", "'eIDAttribute'", ")", "||", "null", ";", "if", "(", "iD", ")", "{", "build", "(", "root", ",", "root", ".", "get", "(", "iD", ".", "get", "(", "'name'", ")", ")", ")", ";", "}", "else", "{", "build", "(", "root", ",", "'/'", ")", ";", "}", "}", "}", "else", "{", "for", "(", "var", "i", "=", "0", ";", "i", "<", "contents", ".", "length", ";", "i", "++", ")", "{", "root", "=", "contents", "[", "i", "]", ";", "if", "(", "root", ".", "_id", ")", "{", "build", "(", "root", ",", "root", ".", "_id", ")", ";", "}", "else", "{", "iD", "=", "root", ".", "eClass", ".", "get", "(", "'eIDAttribute'", ")", "||", "null", ";", "if", "(", "iD", ")", "{", "build", "(", "root", ",", "root", ".", "get", "(", "iD", ".", "get", "(", "'name'", ")", ")", ")", ";", "}", "else", "{", "build", "(", "root", ",", "'/'", "+", "i", ")", ";", "}", "}", "}", "}", "}", "return", "index", ";", "}" ]
Build index of EObjects contained in a Resource. The index keys are the EObject's fragment identifier, the values are the EObjects.
[ "Build", "index", "of", "EObjects", "contained", "in", "a", "Resource", ".", "The", "index", "keys", "are", "the", "EObject", "s", "fragment", "identifier", "the", "values", "are", "the", "EObjects", "." ]
c039974fc08389b153b4765764c97e66f051dc1c
https://github.com/emfjson/ecore.js/blob/c039974fc08389b153b4765764c97e66f051dc1c/src/resource.js#L648-L691
train
mixmaxhq/rollup-plugin-root-import
lib/index.js
strArray
function strArray(array) { if (Array.isArray(array)) { array = array.filter(isString); return array.length ? array : null; } return isString(array) ? [array] : null; }
javascript
function strArray(array) { if (Array.isArray(array)) { array = array.filter(isString); return array.length ? array : null; } return isString(array) ? [array] : null; }
[ "function", "strArray", "(", "array", ")", "{", "if", "(", "Array", ".", "isArray", "(", "array", ")", ")", "{", "array", "=", "array", ".", "filter", "(", "isString", ")", ";", "return", "array", ".", "length", "?", "array", ":", "null", ";", "}", "return", "isString", "(", "array", ")", "?", "[", "array", "]", ":", "null", ";", "}" ]
Coerce the input to an array of strings. If the input is a string, wrap it in an array. If the input is a string, filter out all the non-string elements. If we end up with an empty array, return null. @param {*} array @return {?Array<String>} The output array.
[ "Coerce", "the", "input", "to", "an", "array", "of", "strings", ".", "If", "the", "input", "is", "a", "string", "wrap", "it", "in", "an", "array", ".", "If", "the", "input", "is", "a", "string", "filter", "out", "all", "the", "non", "-", "string", "elements", ".", "If", "we", "end", "up", "with", "an", "empty", "array", "return", "null", "." ]
1d53189f000b8ea46cc5c2c614e27276860a53ce
https://github.com/mixmaxhq/rollup-plugin-root-import/blob/1d53189f000b8ea46cc5c2c614e27276860a53ce/lib/index.js#L20-L26
train
mixmaxhq/rollup-plugin-root-import
lib/index.js
firstOf
function firstOf(items, evaluate) { return new Promise((accept, reject) => { (function next(i) { if (i >= items.length) { accept(null); return; } setImmediate(() => evaluate(items[i], (err, value) => { if (err) reject(err); else if (value) accept(value); else next(i + 1); })); })(0); }); }
javascript
function firstOf(items, evaluate) { return new Promise((accept, reject) => { (function next(i) { if (i >= items.length) { accept(null); return; } setImmediate(() => evaluate(items[i], (err, value) => { if (err) reject(err); else if (value) accept(value); else next(i + 1); })); })(0); }); }
[ "function", "firstOf", "(", "items", ",", "evaluate", ")", "{", "return", "new", "Promise", "(", "(", "accept", ",", "reject", ")", "=>", "{", "(", "function", "next", "(", "i", ")", "{", "if", "(", "i", ">=", "items", ".", "length", ")", "{", "accept", "(", "null", ")", ";", "return", ";", "}", "setImmediate", "(", "(", ")", "=>", "evaluate", "(", "items", "[", "i", "]", ",", "(", "err", ",", "value", ")", "=>", "{", "if", "(", "err", ")", "reject", "(", "err", ")", ";", "else", "if", "(", "value", ")", "accept", "(", "value", ")", ";", "else", "next", "(", "i", "+", "1", ")", ";", "}", ")", ")", ";", "}", ")", "(", "0", ")", ";", "}", ")", ";", "}" ]
Call the evaluate function asynchronously on each item in the items array, and return a promise that will fail on the first error evaluate produces, or resolve to the first truthy value which evaluate produces. If all items evaluate to falsy values, and evaluate never produces an error, the promise will resolve to null. @param {Array<*>} items An array of opaque items. @param {Function(*, Function(?Error=, *=))} evaluate @return {Promise<*>}
[ "Call", "the", "evaluate", "function", "asynchronously", "on", "each", "item", "in", "the", "items", "array", "and", "return", "a", "promise", "that", "will", "fail", "on", "the", "first", "error", "evaluate", "produces", "or", "resolve", "to", "the", "first", "truthy", "value", "which", "evaluate", "produces", ".", "If", "all", "items", "evaluate", "to", "falsy", "values", "and", "evaluate", "never", "produces", "an", "error", "the", "promise", "will", "resolve", "to", "null", "." ]
1d53189f000b8ea46cc5c2c614e27276860a53ce
https://github.com/mixmaxhq/rollup-plugin-root-import/blob/1d53189f000b8ea46cc5c2c614e27276860a53ce/lib/index.js#L39-L54
train
mixmaxhq/rollup-plugin-root-import
lib/index.js
resolve
function resolve(importee, imports) { return firstOf(imports, ({root, extension}, done) => { const file = path.join(root, importee + extension); fs.stat(file, (err, stats) => { if (!err && stats.isFile()) done(null, file); else done(null, null); }); }); }
javascript
function resolve(importee, imports) { return firstOf(imports, ({root, extension}, done) => { const file = path.join(root, importee + extension); fs.stat(file, (err, stats) => { if (!err && stats.isFile()) done(null, file); else done(null, null); }); }); }
[ "function", "resolve", "(", "importee", ",", "imports", ")", "{", "return", "firstOf", "(", "imports", ",", "(", "{", "root", ",", "extension", "}", ",", "done", ")", "=>", "{", "const", "file", "=", "path", ".", "join", "(", "root", ",", "importee", "+", "extension", ")", ";", "fs", ".", "stat", "(", "file", ",", "(", "err", ",", "stats", ")", "=>", "{", "if", "(", "!", "err", "&&", "stats", ".", "isFile", "(", ")", ")", "done", "(", "null", ",", "file", ")", ";", "else", "done", "(", "null", ",", "null", ")", ";", "}", ")", ";", "}", ")", ";", "}" ]
Asynchronously resolve a module to an absolute path given a set of places to look. @param {String} importee The id of the module, relative to one of the specified imports. @param {Array<Import>} imports The import objects. @return {Promise<?String>} The resolved module.
[ "Asynchronously", "resolve", "a", "module", "to", "an", "absolute", "path", "given", "a", "set", "of", "places", "to", "look", "." ]
1d53189f000b8ea46cc5c2c614e27276860a53ce
https://github.com/mixmaxhq/rollup-plugin-root-import/blob/1d53189f000b8ea46cc5c2c614e27276860a53ce/lib/index.js#L65-L73
train
stackgl/gl-vec2
rotate.js
rotate
function rotate(out, a, angle) { var c = Math.cos(angle), s = Math.sin(angle) var x = a[0], y = a[1] out[0] = x * c - y * s out[1] = x * s + y * c return out }
javascript
function rotate(out, a, angle) { var c = Math.cos(angle), s = Math.sin(angle) var x = a[0], y = a[1] out[0] = x * c - y * s out[1] = x * s + y * c return out }
[ "function", "rotate", "(", "out", ",", "a", ",", "angle", ")", "{", "var", "c", "=", "Math", ".", "cos", "(", "angle", ")", ",", "s", "=", "Math", ".", "sin", "(", "angle", ")", "var", "x", "=", "a", "[", "0", "]", ",", "y", "=", "a", "[", "1", "]", "out", "[", "0", "]", "=", "x", "*", "c", "-", "y", "*", "s", "out", "[", "1", "]", "=", "x", "*", "s", "+", "y", "*", "c", "return", "out", "}" ]
Rotates a vec2 by an angle @param {vec2} out the receiving vector @param {vec2} a the vector to rotate @param {Number} angle the angle of rotation (in radians) @returns {vec2} out
[ "Rotates", "a", "vec2", "by", "an", "angle" ]
a139f9eddbb1b8de7b1d3294d7a9b203e549e724
https://github.com/stackgl/gl-vec2/blob/a139f9eddbb1b8de7b1d3294d7a9b203e549e724/rotate.js#L11-L21
train
brianvoe/vue-build
bin/init.js
addPackageFile
function addPackageFile (devDependency = false, extraOptions = null) { var packageJSON = { name: 'app', description: 'Vue Build Application', version: '0.1.0', dependencies: { 'vue-build': '^' + require('../package').version } } if (devDependency) { packageJSON.devDependencies = { 'vue-build': packageJSON.dependencies['vue-build'] } delete packageJSON.dependencies['vue-build'] } if (extraOptions) { packageJSON = Object.assign({}, packageJSON, extraOptions) } fs.writeFileSync( path.join(projectRoot, 'package.json'), JSON.stringify(packageJSON, null, 2) ) }
javascript
function addPackageFile (devDependency = false, extraOptions = null) { var packageJSON = { name: 'app', description: 'Vue Build Application', version: '0.1.0', dependencies: { 'vue-build': '^' + require('../package').version } } if (devDependency) { packageJSON.devDependencies = { 'vue-build': packageJSON.dependencies['vue-build'] } delete packageJSON.dependencies['vue-build'] } if (extraOptions) { packageJSON = Object.assign({}, packageJSON, extraOptions) } fs.writeFileSync( path.join(projectRoot, 'package.json'), JSON.stringify(packageJSON, null, 2) ) }
[ "function", "addPackageFile", "(", "devDependency", "=", "false", ",", "extraOptions", "=", "null", ")", "{", "var", "packageJSON", "=", "{", "name", ":", "'app'", ",", "description", ":", "'Vue Build Application'", ",", "version", ":", "'0.1.0'", ",", "dependencies", ":", "{", "'vue-build'", ":", "'^'", "+", "require", "(", "'../package'", ")", ".", "version", "}", "}", "if", "(", "devDependency", ")", "{", "packageJSON", ".", "devDependencies", "=", "{", "'vue-build'", ":", "packageJSON", ".", "dependencies", "[", "'vue-build'", "]", "}", "delete", "packageJSON", ".", "dependencies", "[", "'vue-build'", "]", "}", "if", "(", "extraOptions", ")", "{", "packageJSON", "=", "Object", ".", "assign", "(", "{", "}", ",", "packageJSON", ",", "extraOptions", ")", "}", "fs", ".", "writeFileSync", "(", "path", ".", "join", "(", "projectRoot", ",", "'package.json'", ")", ",", "JSON", ".", "stringify", "(", "packageJSON", ",", "null", ",", "2", ")", ")", "}" ]
Add package.json file
[ "Add", "package", ".", "json", "file" ]
6709c67964e750c1d980d2d26b472665b10c8671
https://github.com/brianvoe/vue-build/blob/6709c67964e750c1d980d2d26b472665b10c8671/bin/init.js#L32-L57
train
kevinoid/swagger-spec-validator
bin/swagger-spec-validator.js
getMessages
function getMessages(result) { let messages = []; if (result.messages) { messages = messages.concat(result.messages); } if (result.schemaValidationMessages) { messages = messages.concat( result.schemaValidationMessages.map((m) => `${m.level}: ${m.message}`) ); } return messages; }
javascript
function getMessages(result) { let messages = []; if (result.messages) { messages = messages.concat(result.messages); } if (result.schemaValidationMessages) { messages = messages.concat( result.schemaValidationMessages.map((m) => `${m.level}: ${m.message}`) ); } return messages; }
[ "function", "getMessages", "(", "result", ")", "{", "let", "messages", "=", "[", "]", ";", "if", "(", "result", ".", "messages", ")", "{", "messages", "=", "messages", ".", "concat", "(", "result", ".", "messages", ")", ";", "}", "if", "(", "result", ".", "schemaValidationMessages", ")", "{", "messages", "=", "messages", ".", "concat", "(", "result", ".", "schemaValidationMessages", ".", "map", "(", "(", "m", ")", "=>", "`", "${", "m", ".", "level", "}", "${", "m", ".", "message", "}", "`", ")", ")", ";", "}", "return", "messages", ";", "}" ]
Gets validation messages from a validation response object. @private
[ "Gets", "validation", "messages", "from", "a", "validation", "response", "object", "." ]
e97804e04ff45bea3d23c1e0b3fc8b2c998809e2
https://github.com/kevinoid/swagger-spec-validator/blob/e97804e04ff45bea3d23c1e0b3fc8b2c998809e2/bin/swagger-spec-validator.js#L70-L81
train
stackgl/gl-vec2
divide.js
divide
function divide(out, a, b) { out[0] = a[0] / b[0] out[1] = a[1] / b[1] return out }
javascript
function divide(out, a, b) { out[0] = a[0] / b[0] out[1] = a[1] / b[1] return out }
[ "function", "divide", "(", "out", ",", "a", ",", "b", ")", "{", "out", "[", "0", "]", "=", "a", "[", "0", "]", "/", "b", "[", "0", "]", "out", "[", "1", "]", "=", "a", "[", "1", "]", "/", "b", "[", "1", "]", "return", "out", "}" ]
Divides two vec2's @param {vec2} out the receiving vector @param {vec2} a the first operand @param {vec2} b the second operand @returns {vec2} out
[ "Divides", "two", "vec2", "s" ]
a139f9eddbb1b8de7b1d3294d7a9b203e549e724
https://github.com/stackgl/gl-vec2/blob/a139f9eddbb1b8de7b1d3294d7a9b203e549e724/divide.js#L11-L15
train
brianvoe/vue-build
bin/config/karma.conf.js
function (args, config, logger, helper) { console.log(chalk.blue('Running server on http://localhost:' + port + '.....PID:' + process.pid)) var express = require('express') var expressApp = express() // require server path and pass express expressApp to it require(pathToServer)(expressApp) expressApp.listen(port) }
javascript
function (args, config, logger, helper) { console.log(chalk.blue('Running server on http://localhost:' + port + '.....PID:' + process.pid)) var express = require('express') var expressApp = express() // require server path and pass express expressApp to it require(pathToServer)(expressApp) expressApp.listen(port) }
[ "function", "(", "args", ",", "config", ",", "logger", ",", "helper", ")", "{", "console", ".", "log", "(", "chalk", ".", "blue", "(", "'Running server on http://localhost:'", "+", "port", "+", "'.....PID:'", "+", "process", ".", "pid", ")", ")", "var", "express", "=", "require", "(", "'express'", ")", "var", "expressApp", "=", "express", "(", ")", "require", "(", "pathToServer", ")", "(", "expressApp", ")", "expressApp", ".", "listen", "(", "port", ")", "}" ]
If statsSync is successfull push plugin and run express server
[ "If", "statsSync", "is", "successfull", "push", "plugin", "and", "run", "express", "server" ]
6709c67964e750c1d980d2d26b472665b10c8671
https://github.com/brianvoe/vue-build/blob/6709c67964e750c1d980d2d26b472665b10c8671/bin/config/karma.conf.js#L141-L151
train
brianvoe/vue-build
bin/dev.js
function (appServer) { appServer.use(function (req, res, next) { if (process.env.ENVIRONMENT === 'development') { // Lets not console log for status polling or webpack hot module reloading if ( !req.url.includes('/status') && !req.url.includes('/__webpack_hmr') ) { console.log('Using middleware for ' + req.url) } } next() }) // Add webpack hot middleware to use for error overlay // Quiet is set to true because well let WebpackDevServer handle console logging appServer.use(webpackHotMiddleware(compiler)) // If there is a server.js file load it and pass appServer to it if (pathToServer) { require(pathToServer)(appServer) } }
javascript
function (appServer) { appServer.use(function (req, res, next) { if (process.env.ENVIRONMENT === 'development') { // Lets not console log for status polling or webpack hot module reloading if ( !req.url.includes('/status') && !req.url.includes('/__webpack_hmr') ) { console.log('Using middleware for ' + req.url) } } next() }) // Add webpack hot middleware to use for error overlay // Quiet is set to true because well let WebpackDevServer handle console logging appServer.use(webpackHotMiddleware(compiler)) // If there is a server.js file load it and pass appServer to it if (pathToServer) { require(pathToServer)(appServer) } }
[ "function", "(", "appServer", ")", "{", "appServer", ".", "use", "(", "function", "(", "req", ",", "res", ",", "next", ")", "{", "if", "(", "process", ".", "env", ".", "ENVIRONMENT", "===", "'development'", ")", "{", "if", "(", "!", "req", ".", "url", ".", "includes", "(", "'/status'", ")", "&&", "!", "req", ".", "url", ".", "includes", "(", "'/__webpack_hmr'", ")", ")", "{", "console", ".", "log", "(", "'Using middleware for '", "+", "req", ".", "url", ")", "}", "}", "next", "(", ")", "}", ")", "appServer", ".", "use", "(", "webpackHotMiddleware", "(", "compiler", ")", ")", "if", "(", "pathToServer", ")", "{", "require", "(", "pathToServer", ")", "(", "appServer", ")", "}", "}" ]
express server setup extension
[ "express", "server", "setup", "extension" ]
6709c67964e750c1d980d2d26b472665b10c8671
https://github.com/brianvoe/vue-build/blob/6709c67964e750c1d980d2d26b472665b10c8671/bin/dev.js#L70-L92
train
stackgl/gl-vec2
fromValues.js
fromValues
function fromValues(x, y) { var out = new Float32Array(2) out[0] = x out[1] = y return out }
javascript
function fromValues(x, y) { var out = new Float32Array(2) out[0] = x out[1] = y return out }
[ "function", "fromValues", "(", "x", ",", "y", ")", "{", "var", "out", "=", "new", "Float32Array", "(", "2", ")", "out", "[", "0", "]", "=", "x", "out", "[", "1", "]", "=", "y", "return", "out", "}" ]
Creates a new vec2 initialized with the given values @param {Number} x X component @param {Number} y Y component @returns {vec2} a new 2D vector
[ "Creates", "a", "new", "vec2", "initialized", "with", "the", "given", "values" ]
a139f9eddbb1b8de7b1d3294d7a9b203e549e724
https://github.com/stackgl/gl-vec2/blob/a139f9eddbb1b8de7b1d3294d7a9b203e549e724/fromValues.js#L10-L15
train
stackgl/gl-vec2
limit.js
limit
function limit(out, a, max) { var mSq = a[0] * a[0] + a[1] * a[1]; if (mSq > max * max) { var n = Math.sqrt(mSq); out[0] = a[0] / n * max; out[1] = a[1] / n * max; } else { out[0] = a[0]; out[1] = a[1]; } return out; }
javascript
function limit(out, a, max) { var mSq = a[0] * a[0] + a[1] * a[1]; if (mSq > max * max) { var n = Math.sqrt(mSq); out[0] = a[0] / n * max; out[1] = a[1] / n * max; } else { out[0] = a[0]; out[1] = a[1]; } return out; }
[ "function", "limit", "(", "out", ",", "a", ",", "max", ")", "{", "var", "mSq", "=", "a", "[", "0", "]", "*", "a", "[", "0", "]", "+", "a", "[", "1", "]", "*", "a", "[", "1", "]", ";", "if", "(", "mSq", ">", "max", "*", "max", ")", "{", "var", "n", "=", "Math", ".", "sqrt", "(", "mSq", ")", ";", "out", "[", "0", "]", "=", "a", "[", "0", "]", "/", "n", "*", "max", ";", "out", "[", "1", "]", "=", "a", "[", "1", "]", "/", "n", "*", "max", ";", "}", "else", "{", "out", "[", "0", "]", "=", "a", "[", "0", "]", ";", "out", "[", "1", "]", "=", "a", "[", "1", "]", ";", "}", "return", "out", ";", "}" ]
Limit the magnitude of this vector to the value used for the `max` parameter. @param {vec2} the vector to limit @param {Number} max the maximum magnitude for the vector @returns {vec2} out
[ "Limit", "the", "magnitude", "of", "this", "vector", "to", "the", "value", "used", "for", "the", "max", "parameter", "." ]
a139f9eddbb1b8de7b1d3294d7a9b203e549e724
https://github.com/stackgl/gl-vec2/blob/a139f9eddbb1b8de7b1d3294d7a9b203e549e724/limit.js#L11-L24
train
kevinoid/swagger-spec-validator
index.js
combineHeaders
function combineHeaders(...args) { const combinedLower = {}; const combined = {}; args.reverse(); args.forEach((headers) => { if (headers) { Object.keys(headers).forEach((name) => { const nameLower = name.toLowerCase(); if (!hasOwnProperty.call(combinedLower, nameLower)) { combinedLower[nameLower] = true; combined[name] = headers[name]; } }); } }); return combined; }
javascript
function combineHeaders(...args) { const combinedLower = {}; const combined = {}; args.reverse(); args.forEach((headers) => { if (headers) { Object.keys(headers).forEach((name) => { const nameLower = name.toLowerCase(); if (!hasOwnProperty.call(combinedLower, nameLower)) { combinedLower[nameLower] = true; combined[name] = headers[name]; } }); } }); return combined; }
[ "function", "combineHeaders", "(", "...", "args", ")", "{", "const", "combinedLower", "=", "{", "}", ";", "const", "combined", "=", "{", "}", ";", "args", ".", "reverse", "(", ")", ";", "args", ".", "forEach", "(", "(", "headers", ")", "=>", "{", "if", "(", "headers", ")", "{", "Object", ".", "keys", "(", "headers", ")", ".", "forEach", "(", "(", "name", ")", "=>", "{", "const", "nameLower", "=", "name", ".", "toLowerCase", "(", ")", ";", "if", "(", "!", "hasOwnProperty", ".", "call", "(", "combinedLower", ",", "nameLower", ")", ")", "{", "combinedLower", "[", "nameLower", "]", "=", "true", ";", "combined", "[", "name", "]", "=", "headers", "[", "name", "]", ";", "}", "}", ")", ";", "}", "}", ")", ";", "return", "combined", ";", "}" ]
Combines HTTP headers objects. With the capitalization and value of the last occurrence. @private
[ "Combines", "HTTP", "headers", "objects", ".", "With", "the", "capitalization", "and", "value", "of", "the", "last", "occurrence", "." ]
e97804e04ff45bea3d23c1e0b3fc8b2c998809e2
https://github.com/kevinoid/swagger-spec-validator/blob/e97804e04ff45bea3d23c1e0b3fc8b2c998809e2/index.js#L90-L106
train
znerol/node-xmlshim
domparser.js
flushData
function flushData() { if (currentCharacters) { currentElement.appendChild( doc.createTextNode(currentCharacters)); currentCharacters = ''; } else if (currentCdata) { currentElement.appendChild( doc.createCDATASection(currentCdata)); currentCdata = ''; } }
javascript
function flushData() { if (currentCharacters) { currentElement.appendChild( doc.createTextNode(currentCharacters)); currentCharacters = ''; } else if (currentCdata) { currentElement.appendChild( doc.createCDATASection(currentCdata)); currentCdata = ''; } }
[ "function", "flushData", "(", ")", "{", "if", "(", "currentCharacters", ")", "{", "currentElement", ".", "appendChild", "(", "doc", ".", "createTextNode", "(", "currentCharacters", ")", ")", ";", "currentCharacters", "=", "''", ";", "}", "else", "if", "(", "currentCdata", ")", "{", "currentElement", ".", "appendChild", "(", "doc", ".", "createCDATASection", "(", "currentCdata", ")", ")", ";", "currentCdata", "=", "''", ";", "}", "}" ]
Add text node or CDATA section before starting or ending an element
[ "Add", "text", "node", "or", "CDATA", "section", "before", "starting", "or", "ending", "an", "element" ]
d52ec24aa2ef0a22f18f9d293a043f88470ea21c
https://github.com/znerol/node-xmlshim/blob/d52ec24aa2ef0a22f18f9d293a043f88470ea21c/domparser.js#L33-L44
train
boughtbymany/mutt-forms
src/index.js
Mutt
function Mutt(schema, options = {}, debug = false) { if (debug) { this.config.setSetting("debug", true) } if (schema === undefined) { throw new Error("You must specify a Schema!") } // Setup a new form instance if called directly return new MuttForm(schema, options) }
javascript
function Mutt(schema, options = {}, debug = false) { if (debug) { this.config.setSetting("debug", true) } if (schema === undefined) { throw new Error("You must specify a Schema!") } // Setup a new form instance if called directly return new MuttForm(schema, options) }
[ "function", "Mutt", "(", "schema", ",", "options", "=", "{", "}", ",", "debug", "=", "false", ")", "{", "if", "(", "debug", ")", "{", "this", ".", "config", ".", "setSetting", "(", "\"debug\"", ",", "true", ")", "}", "if", "(", "schema", "===", "undefined", ")", "{", "throw", "new", "Error", "(", "\"You must specify a Schema!\"", ")", "}", "return", "new", "MuttForm", "(", "schema", ",", "options", ")", "}" ]
Main Mutt API. @returns {MuttForm} Returns an instance of a MuttForm @example let form = new Mutt({ name: { type: 'string' } })
[ "Main", "Mutt", "API", "." ]
9e6cb0482dafa75d48400f118e896082b4ebcc7b
https://github.com/boughtbymany/mutt-forms/blob/9e6cb0482dafa75d48400f118e896082b4ebcc7b/src/index.js#L24-L35
train
boughtbymany/mutt-forms
src/index.js
initApi
function initApi(Mutt) { // Setup the config const config = new MuttConfig() Mutt.config = config // Setup plugin interface Mutt.use = function(plugins) { if (!Array.isArray(plugins)) { plugins = [plugins] } for (const plugin of plugins) { Mutt.config.use(plugin) } } // Setup Utilities Mutt.logger = logger Mutt.mixin = mixin // Add in hooks for fields, widgets & validators Mutt.fields = fields Mutt.widgets = widgets Mutt.validators = validators Mutt.serializers = serializers }
javascript
function initApi(Mutt) { // Setup the config const config = new MuttConfig() Mutt.config = config // Setup plugin interface Mutt.use = function(plugins) { if (!Array.isArray(plugins)) { plugins = [plugins] } for (const plugin of plugins) { Mutt.config.use(plugin) } } // Setup Utilities Mutt.logger = logger Mutt.mixin = mixin // Add in hooks for fields, widgets & validators Mutt.fields = fields Mutt.widgets = widgets Mutt.validators = validators Mutt.serializers = serializers }
[ "function", "initApi", "(", "Mutt", ")", "{", "const", "config", "=", "new", "MuttConfig", "(", ")", "Mutt", ".", "config", "=", "config", "Mutt", ".", "use", "=", "function", "(", "plugins", ")", "{", "if", "(", "!", "Array", ".", "isArray", "(", "plugins", ")", ")", "{", "plugins", "=", "[", "plugins", "]", "}", "for", "(", "const", "plugin", "of", "plugins", ")", "{", "Mutt", ".", "config", ".", "use", "(", "plugin", ")", "}", "}", "Mutt", ".", "logger", "=", "logger", "Mutt", ".", "mixin", "=", "mixin", "Mutt", ".", "fields", "=", "fields", "Mutt", ".", "widgets", "=", "widgets", "Mutt", ".", "validators", "=", "validators", "Mutt", ".", "serializers", "=", "serializers", "}" ]
Internal setup for Mutt API @private
[ "Internal", "setup", "for", "Mutt", "API" ]
9e6cb0482dafa75d48400f118e896082b4ebcc7b
https://github.com/boughtbymany/mutt-forms/blob/9e6cb0482dafa75d48400f118e896082b4ebcc7b/src/index.js#L41-L66
train
nodeGame/nodegame-server
conf/loggers.js
configure
function configure(loggers, logDir) { var msgLogger; var logLevel; logLevel = winston.level; // ServerNode. loggers.add('servernode', { console: { level: logLevel, colorize: true }, file: { level: logLevel, timestamp: true, filename: path.join(logDir, 'servernode.log'), maxsize: 1000000, maxFiles: 10 } }); // Channel. loggers.add('channel', { console: { level: logLevel, colorize: true, }, file: { level: logLevel, timestamp: true, filename: path.join(logDir, 'channels.log'), maxsize: 1000000, maxFiles: 10 } }); // Messages. // Make custom levels and only File transports for messages. msgLogger = loggers.add('messages'); msgLogger.remove(winston.transports.Console); msgLogger.add(winston.transports.File, { timestamp: true, maxsize: 1000000, filename: path.join(logDir, 'messages.log') }); // Do not change, or logging might be affected. // Logger.js hardcodes the values for speed. msgLogger.setLevels({ // Log none. none: 0, // All DATA msgs. data: 1, // All SET and DATA msgs. set: 3, // All SET, GET and DATA msgs. get: 5, // All SETUP, SET, GET and DATA msgs. setup: 7, // All messages, but **not** PLAYER_UPDATE, SERVERCOMMAND and ALERT. game: 9, // All messages. all: 11 }); // Set default logging level for messages. msgLogger.level = 'all'; // Clients. loggers.add('clients', { console: { level: logLevel, colorize: true, }, file: { level: 'silly', timestamp: true, filename: path.join(logDir, 'clients.log') } }); return true; }
javascript
function configure(loggers, logDir) { var msgLogger; var logLevel; logLevel = winston.level; // ServerNode. loggers.add('servernode', { console: { level: logLevel, colorize: true }, file: { level: logLevel, timestamp: true, filename: path.join(logDir, 'servernode.log'), maxsize: 1000000, maxFiles: 10 } }); // Channel. loggers.add('channel', { console: { level: logLevel, colorize: true, }, file: { level: logLevel, timestamp: true, filename: path.join(logDir, 'channels.log'), maxsize: 1000000, maxFiles: 10 } }); // Messages. // Make custom levels and only File transports for messages. msgLogger = loggers.add('messages'); msgLogger.remove(winston.transports.Console); msgLogger.add(winston.transports.File, { timestamp: true, maxsize: 1000000, filename: path.join(logDir, 'messages.log') }); // Do not change, or logging might be affected. // Logger.js hardcodes the values for speed. msgLogger.setLevels({ // Log none. none: 0, // All DATA msgs. data: 1, // All SET and DATA msgs. set: 3, // All SET, GET and DATA msgs. get: 5, // All SETUP, SET, GET and DATA msgs. setup: 7, // All messages, but **not** PLAYER_UPDATE, SERVERCOMMAND and ALERT. game: 9, // All messages. all: 11 }); // Set default logging level for messages. msgLogger.level = 'all'; // Clients. loggers.add('clients', { console: { level: logLevel, colorize: true, }, file: { level: 'silly', timestamp: true, filename: path.join(logDir, 'clients.log') } }); return true; }
[ "function", "configure", "(", "loggers", ",", "logDir", ")", "{", "var", "msgLogger", ";", "var", "logLevel", ";", "logLevel", "=", "winston", ".", "level", ";", "loggers", ".", "add", "(", "'servernode'", ",", "{", "console", ":", "{", "level", ":", "logLevel", ",", "colorize", ":", "true", "}", ",", "file", ":", "{", "level", ":", "logLevel", ",", "timestamp", ":", "true", ",", "filename", ":", "path", ".", "join", "(", "logDir", ",", "'servernode.log'", ")", ",", "maxsize", ":", "1000000", ",", "maxFiles", ":", "10", "}", "}", ")", ";", "loggers", ".", "add", "(", "'channel'", ",", "{", "console", ":", "{", "level", ":", "logLevel", ",", "colorize", ":", "true", ",", "}", ",", "file", ":", "{", "level", ":", "logLevel", ",", "timestamp", ":", "true", ",", "filename", ":", "path", ".", "join", "(", "logDir", ",", "'channels.log'", ")", ",", "maxsize", ":", "1000000", ",", "maxFiles", ":", "10", "}", "}", ")", ";", "msgLogger", "=", "loggers", ".", "add", "(", "'messages'", ")", ";", "msgLogger", ".", "remove", "(", "winston", ".", "transports", ".", "Console", ")", ";", "msgLogger", ".", "add", "(", "winston", ".", "transports", ".", "File", ",", "{", "timestamp", ":", "true", ",", "maxsize", ":", "1000000", ",", "filename", ":", "path", ".", "join", "(", "logDir", ",", "'messages.log'", ")", "}", ")", ";", "msgLogger", ".", "setLevels", "(", "{", "none", ":", "0", ",", "data", ":", "1", ",", "set", ":", "3", ",", "get", ":", "5", ",", "setup", ":", "7", ",", "game", ":", "9", ",", "all", ":", "11", "}", ")", ";", "msgLogger", ".", "level", "=", "'all'", ";", "loggers", ".", "add", "(", "'clients'", ",", "{", "console", ":", "{", "level", ":", "logLevel", ",", "colorize", ":", "true", ",", "}", ",", "file", ":", "{", "level", ":", "'silly'", ",", "timestamp", ":", "true", ",", "filename", ":", "path", ".", "join", "(", "logDir", ",", "'clients.log'", ")", "}", "}", ")", ";", "return", "true", ";", "}" ]
Variable loggers is winston.loggers.
[ "Variable", "loggers", "is", "winston", ".", "loggers", "." ]
e59952399e7db8ca2cb600036867b2a543baf826
https://github.com/nodeGame/nodegame-server/blob/e59952399e7db8ca2cb600036867b2a543baf826/conf/loggers.js#L15-L96
train
nodeGame/nodegame-server
public/javascripts/nodegame-full.js
generalLike
function generalLike(d, value, comparator, sensitive) { var regex; RegExp.escape = function(str) { return str.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; regex = RegExp.escape(value); regex = regex.replace(/%/g, '.*').replace(/_/g, '.'); regex = new RegExp('^' + regex + '$', sensitive); if ('object' === typeof d) { return function(elem) { var i, len; len = d.length; for (i = 0; i < len; i++) { if ('undefined' !== typeof elem[d[i]]) { if (regex.test(elem[d[i]])) { return elem; } } } }; } else if (d === '*') { return function(elem) { var d; for (d in elem) { if ('undefined' !== typeof elem[d]) { if (regex.test(elem[d])) { return elem; } } } }; } else { return function(elem) { if ('undefined' !== typeof elem[d]) { if (regex.test(elem[d])) { return elem; } } }; } }
javascript
function generalLike(d, value, comparator, sensitive) { var regex; RegExp.escape = function(str) { return str.replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1'); }; regex = RegExp.escape(value); regex = regex.replace(/%/g, '.*').replace(/_/g, '.'); regex = new RegExp('^' + regex + '$', sensitive); if ('object' === typeof d) { return function(elem) { var i, len; len = d.length; for (i = 0; i < len; i++) { if ('undefined' !== typeof elem[d[i]]) { if (regex.test(elem[d[i]])) { return elem; } } } }; } else if (d === '*') { return function(elem) { var d; for (d in elem) { if ('undefined' !== typeof elem[d]) { if (regex.test(elem[d])) { return elem; } } } }; } else { return function(elem) { if ('undefined' !== typeof elem[d]) { if (regex.test(elem[d])) { return elem; } } }; } }
[ "function", "generalLike", "(", "d", ",", "value", ",", "comparator", ",", "sensitive", ")", "{", "var", "regex", ";", "RegExp", ".", "escape", "=", "function", "(", "str", ")", "{", "return", "str", ".", "replace", "(", "/", "([.*+?^=!:${}()|[\\]\\/\\\\])", "/", "g", ",", "'\\\\$1'", ")", ";", "}", ";", "\\\\", "regex", "=", "RegExp", ".", "escape", "(", "value", ")", ";", "regex", "=", "regex", ".", "replace", "(", "/", "%", "/", "g", ",", "'.*'", ")", ".", "replace", "(", "/", "_", "/", "g", ",", "'.'", ")", ";", "regex", "=", "new", "RegExp", "(", "'^'", "+", "regex", "+", "'$'", ",", "sensitive", ")", ";", "}" ]
Supports `_` and `%` wildcards.
[ "Supports", "_", "and", "%", "wildcards", "." ]
e59952399e7db8ca2cb600036867b2a543baf826
https://github.com/nodeGame/nodegame-server/blob/e59952399e7db8ca2cb600036867b2a543baf826/public/javascripts/nodegame-full.js#L6301-L6346
train
nodeGame/nodegame-server
public/javascripts/nodegame-full.js
logSecureParseError
function logSecureParseError(text, e) { var error; text = text || 'generic error while parsing a game message.'; error = (e) ? text + ": " + e : text; this.node.err('Socket.secureParse: ' + error); return false; }
javascript
function logSecureParseError(text, e) { var error; text = text || 'generic error while parsing a game message.'; error = (e) ? text + ": " + e : text; this.node.err('Socket.secureParse: ' + error); return false; }
[ "function", "logSecureParseError", "(", "text", ",", "e", ")", "{", "var", "error", ";", "text", "=", "text", "||", "'generic error while parsing a game message.'", ";", "error", "=", "(", "e", ")", "?", "text", "+", "\": \"", "+", "e", ":", "text", ";", "this", ".", "node", ".", "err", "(", "'Socket.secureParse: '", "+", "error", ")", ";", "return", "false", ";", "}" ]
Helper methods.
[ "Helper", "methods", "." ]
e59952399e7db8ca2cb600036867b2a543baf826
https://github.com/nodeGame/nodegame-server/blob/e59952399e7db8ca2cb600036867b2a543baf826/public/javascripts/nodegame-full.js#L19998-L20004
train