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 |
---|---|---|---|---|---|---|---|---|---|---|---|
postmanlabs/sails-mysql-transactions | lib/transactions.js | function () {
var connection = this.connection();
// if a connection is defined, get the ID from connection
if (connection) {
if (!connection.transactionId) {
throw new AdapterError(AdapterError.TRANSACTION_NOT_ASSOCIATED);
}
return (this._id = connection.transactionId); // save it just in case, during return
}
// at this point if we do not have an id, we know that we will need to return a dummy one
return this._id || (this._id = util.uid());
} | javascript | function () {
var connection = this.connection();
// if a connection is defined, get the ID from connection
if (connection) {
if (!connection.transactionId) {
throw new AdapterError(AdapterError.TRANSACTION_NOT_ASSOCIATED);
}
return (this._id = connection.transactionId); // save it just in case, during return
}
// at this point if we do not have an id, we know that we will need to return a dummy one
return this._id || (this._id = util.uid());
} | [
"function",
"(",
")",
"{",
"var",
"connection",
"=",
"this",
".",
"connection",
"(",
")",
";",
"if",
"(",
"connection",
")",
"{",
"if",
"(",
"!",
"connection",
".",
"transactionId",
")",
"{",
"throw",
"new",
"AdapterError",
"(",
"AdapterError",
".",
"TRANSACTION_NOT_ASSOCIATED",
")",
";",
"}",
"return",
"(",
"this",
".",
"_id",
"=",
"connection",
".",
"transactionId",
")",
";",
"}",
"return",
"this",
".",
"_id",
"||",
"(",
"this",
".",
"_id",
"=",
"util",
".",
"uid",
"(",
")",
")",
";",
"}"
]
| Returns the transaction id associated with this transaction instance. If the transaction is not connected,
it creates a new ID and caches it if things are not connected
@returns {string}
@note that this function caches the id in `this._id` and that is directly used in constructor and the
rollback and commit methods. | [
"Returns",
"the",
"transaction",
"id",
"associated",
"with",
"this",
"transaction",
"instance",
".",
"If",
"the",
"transaction",
"is",
"not",
"connected",
"it",
"creates",
"a",
"new",
"ID",
"and",
"caches",
"it",
"if",
"things",
"are",
"not",
"connected"
]
| 4c8bae4d428afb942860a51d4deb66aa5b9cd405 | https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L198-L212 | train |
|
postmanlabs/sails-mysql-transactions | lib/transactions.js | function (connectionName, callback) {
var self = this,
_db = Transaction.databases[connectionName],
transactionId;
// validate db setup prior to every connection. this ensures nothing goes forward post teardown
if (!_db) {
callback(new AdapterError(AdapterError.TRANSACTION_NOT_SETUP));
}
// validate connection name
if (!connectionName) {
callback(new AdapterError(AdapterError.TRANSACTION_NOT_IDENTIFIED));
}
// if this transaction is already connected, then continue
if (self.connection()) {
// @todo implement error check when multi-db conn is attempted
// // callback with error if connection name and current connection mismatch
// if (connectionName !== self.connection().identity) {
// callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED));
// }
callback(undefined, self.connection());
return;
}
// at this point, it seems like the connection has not been setup yet, so we setup one and then move forward
transactionId = self.id(); // this will return and cache a new transaction ID if not already present
// set the actual connection name
self._connectionName = connectionName;
_db.getConnection(function (error, conn) {
if (!error) {
self._connection = conn; // save reference
Transaction.associateConnection(conn, transactionId, _db.transactionConfig); // @note disassociate on dc
}
callback(error, self._connection);
});
} | javascript | function (connectionName, callback) {
var self = this,
_db = Transaction.databases[connectionName],
transactionId;
// validate db setup prior to every connection. this ensures nothing goes forward post teardown
if (!_db) {
callback(new AdapterError(AdapterError.TRANSACTION_NOT_SETUP));
}
// validate connection name
if (!connectionName) {
callback(new AdapterError(AdapterError.TRANSACTION_NOT_IDENTIFIED));
}
// if this transaction is already connected, then continue
if (self.connection()) {
// @todo implement error check when multi-db conn is attempted
// // callback with error if connection name and current connection mismatch
// if (connectionName !== self.connection().identity) {
// callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED));
// }
callback(undefined, self.connection());
return;
}
// at this point, it seems like the connection has not been setup yet, so we setup one and then move forward
transactionId = self.id(); // this will return and cache a new transaction ID if not already present
// set the actual connection name
self._connectionName = connectionName;
_db.getConnection(function (error, conn) {
if (!error) {
self._connection = conn; // save reference
Transaction.associateConnection(conn, transactionId, _db.transactionConfig); // @note disassociate on dc
}
callback(error, self._connection);
});
} | [
"function",
"(",
"connectionName",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
",",
"_db",
"=",
"Transaction",
".",
"databases",
"[",
"connectionName",
"]",
",",
"transactionId",
";",
"if",
"(",
"!",
"_db",
")",
"{",
"callback",
"(",
"new",
"AdapterError",
"(",
"AdapterError",
".",
"TRANSACTION_NOT_SETUP",
")",
")",
";",
"}",
"if",
"(",
"!",
"connectionName",
")",
"{",
"callback",
"(",
"new",
"AdapterError",
"(",
"AdapterError",
".",
"TRANSACTION_NOT_IDENTIFIED",
")",
")",
";",
"}",
"if",
"(",
"self",
".",
"connection",
"(",
")",
")",
"{",
"callback",
"(",
"undefined",
",",
"self",
".",
"connection",
"(",
")",
")",
";",
"return",
";",
"}",
"transactionId",
"=",
"self",
".",
"id",
"(",
")",
";",
"self",
".",
"_connectionName",
"=",
"connectionName",
";",
"_db",
".",
"getConnection",
"(",
"function",
"(",
"error",
",",
"conn",
")",
"{",
"if",
"(",
"!",
"error",
")",
"{",
"self",
".",
"_connection",
"=",
"conn",
";",
"Transaction",
".",
"associateConnection",
"(",
"conn",
",",
"transactionId",
",",
"_db",
".",
"transactionConfig",
")",
";",
"}",
"callback",
"(",
"error",
",",
"self",
".",
"_connection",
")",
";",
"}",
")",
";",
"}"
]
| Creates a connection if not already connected.
@private
@returns {mysql.Connection} | [
"Creates",
"a",
"connection",
"if",
"not",
"already",
"connected",
"."
]
| 4c8bae4d428afb942860a51d4deb66aa5b9cd405 | https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L232-L272 | train |
|
postmanlabs/sails-mysql-transactions | lib/transactions.js | function (connectionName, callback) {
var self = this,
conn = self.connection();
// if not yet connected, spawn new connection and initiate transaction
if (!conn) {
self.connect(connectionName, function (error, conn) {
if (error) {
callback(error, conn);
return;
}
// now that we have the connection, we initiate transaction. note that this sql_start is part of the new
// connection branch. it is always highly likely that this would be the program flow. in a very unlikely
// case the alternate flow will kick in, which is the `conn.query` right after this if-block.
conn.beginTransaction(function (error) {
callback(error, self);
});
});
return; // do not proceed with sql_start if connection wasn't initially present.
}
// if transaction is attempted across multiple connections, return an error
if (connectionName !== self._connectionName) {
return callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED));
}
conn.beginTransaction(function (error) {
// if callback mode is used, then execute it and send self as a parameter to match the new Constructor API.
callback(error, self);
});
} | javascript | function (connectionName, callback) {
var self = this,
conn = self.connection();
// if not yet connected, spawn new connection and initiate transaction
if (!conn) {
self.connect(connectionName, function (error, conn) {
if (error) {
callback(error, conn);
return;
}
// now that we have the connection, we initiate transaction. note that this sql_start is part of the new
// connection branch. it is always highly likely that this would be the program flow. in a very unlikely
// case the alternate flow will kick in, which is the `conn.query` right after this if-block.
conn.beginTransaction(function (error) {
callback(error, self);
});
});
return; // do not proceed with sql_start if connection wasn't initially present.
}
// if transaction is attempted across multiple connections, return an error
if (connectionName !== self._connectionName) {
return callback(new AdapterError(AdapterError.TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED));
}
conn.beginTransaction(function (error) {
// if callback mode is used, then execute it and send self as a parameter to match the new Constructor API.
callback(error, self);
});
} | [
"function",
"(",
"connectionName",
",",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
",",
"conn",
"=",
"self",
".",
"connection",
"(",
")",
";",
"if",
"(",
"!",
"conn",
")",
"{",
"self",
".",
"connect",
"(",
"connectionName",
",",
"function",
"(",
"error",
",",
"conn",
")",
"{",
"if",
"(",
"error",
")",
"{",
"callback",
"(",
"error",
",",
"conn",
")",
";",
"return",
";",
"}",
"conn",
".",
"beginTransaction",
"(",
"function",
"(",
"error",
")",
"{",
"callback",
"(",
"error",
",",
"self",
")",
";",
"}",
")",
";",
"}",
")",
";",
"return",
";",
"}",
"if",
"(",
"connectionName",
"!==",
"self",
".",
"_connectionName",
")",
"{",
"return",
"callback",
"(",
"new",
"AdapterError",
"(",
"AdapterError",
".",
"TRANSACTION_MULTI_DB_CONNECTION_ATTEMPTED",
")",
")",
";",
"}",
"conn",
".",
"beginTransaction",
"(",
"function",
"(",
"error",
")",
"{",
"callback",
"(",
"error",
",",
"self",
")",
";",
"}",
")",
";",
"}"
]
| Start a new transaction.
@param connectionName
@param callback | [
"Start",
"a",
"new",
"transaction",
"."
]
| 4c8bae4d428afb942860a51d4deb66aa5b9cd405 | https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L291-L322 | train |
|
postmanlabs/sails-mysql-transactions | lib/transactions.js | function (callback) {
var conn = this.connection(),
id = this._id; // use the raw ID object
// prevent new transactions from using this connection.
this.disconnect();
// if commit was called with no active conn, it implies, no transact action
// was called. as such it is an error.
if (!conn) {
// allow one pseudo commit even without connection, so that programmatic call of repeated commits or
// rollbacks can be trapped.
// note that the absence of `_id` indicates that a `.disconnect` was called.
return callback && callback(id ? null : new AdapterError(AdapterError.TRANSACTION_UNINITIATED_COMM));
}
// we commit the connection and then release from hash
conn.commit(function (error) {
// try releasing the connection.
// if that fails then treat it as a major error.
try {
conn.release();
}
// if there was an error during release, set that as the main error.
catch (err) {
!error && (error = err);
}
// if failure to issue commit or release, then rollback
if (error && conn.transactionConfig.rollbackOnError) {
return conn.rollback(function () {
// disassociate the connection from transaction and execute callback
Transaction.disassociateConnection(conn);
callback && callback(error);
});
}
// disassociate the connection from transaction and execute callback
Transaction.disassociateConnection(conn);
callback && callback(error);
});
} | javascript | function (callback) {
var conn = this.connection(),
id = this._id; // use the raw ID object
// prevent new transactions from using this connection.
this.disconnect();
// if commit was called with no active conn, it implies, no transact action
// was called. as such it is an error.
if (!conn) {
// allow one pseudo commit even without connection, so that programmatic call of repeated commits or
// rollbacks can be trapped.
// note that the absence of `_id` indicates that a `.disconnect` was called.
return callback && callback(id ? null : new AdapterError(AdapterError.TRANSACTION_UNINITIATED_COMM));
}
// we commit the connection and then release from hash
conn.commit(function (error) {
// try releasing the connection.
// if that fails then treat it as a major error.
try {
conn.release();
}
// if there was an error during release, set that as the main error.
catch (err) {
!error && (error = err);
}
// if failure to issue commit or release, then rollback
if (error && conn.transactionConfig.rollbackOnError) {
return conn.rollback(function () {
// disassociate the connection from transaction and execute callback
Transaction.disassociateConnection(conn);
callback && callback(error);
});
}
// disassociate the connection from transaction and execute callback
Transaction.disassociateConnection(conn);
callback && callback(error);
});
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"conn",
"=",
"this",
".",
"connection",
"(",
")",
",",
"id",
"=",
"this",
".",
"_id",
";",
"this",
".",
"disconnect",
"(",
")",
";",
"if",
"(",
"!",
"conn",
")",
"{",
"return",
"callback",
"&&",
"callback",
"(",
"id",
"?",
"null",
":",
"new",
"AdapterError",
"(",
"AdapterError",
".",
"TRANSACTION_UNINITIATED_COMM",
")",
")",
";",
"}",
"conn",
".",
"commit",
"(",
"function",
"(",
"error",
")",
"{",
"try",
"{",
"conn",
".",
"release",
"(",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"!",
"error",
"&&",
"(",
"error",
"=",
"err",
")",
";",
"}",
"if",
"(",
"error",
"&&",
"conn",
".",
"transactionConfig",
".",
"rollbackOnError",
")",
"{",
"return",
"conn",
".",
"rollback",
"(",
"function",
"(",
")",
"{",
"Transaction",
".",
"disassociateConnection",
"(",
"conn",
")",
";",
"callback",
"&&",
"callback",
"(",
"error",
")",
";",
"}",
")",
";",
"}",
"Transaction",
".",
"disassociateConnection",
"(",
"conn",
")",
";",
"callback",
"&&",
"callback",
"(",
"error",
")",
";",
"}",
")",
";",
"}"
]
| Commit the transaction
@param {function} callback - receives `error` | [
"Commit",
"the",
"transaction"
]
| 4c8bae4d428afb942860a51d4deb66aa5b9cd405 | https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L338-L379 | train |
|
postmanlabs/sails-mysql-transactions | lib/transactions.js | function (callback) {
var conn = this.connection(),
id = this._id; // use the raw ID object
// prevent new transactions from using this connection.
this.disconnect();
// if commit was called with no active conn, it implies, no transact action
// was called. as such it is an error.
if (!conn) {
// allow one pseudo commit even without connection, so that programmatic call of repeated commits or
// rollbacks can be trapped.
// note that the absence of `_id` indicates that a `.disconnect` was called.
return callback && callback(id ? null : new AdapterError(AdapterError.TRANSACTION_UNINITIATED_ROLL));
}
conn.rollback(function (error) {
// try releasing the connection.
// if that fails then treat it as a major error.
try {
conn.release();
}
// if there was an error during release, set that as the main error.
catch (err) {
!error && (error = err);
}
// disassociate the connection from transaction and execute callback
Transaction.disassociateConnection(conn);
callback && callback(error);
});
} | javascript | function (callback) {
var conn = this.connection(),
id = this._id; // use the raw ID object
// prevent new transactions from using this connection.
this.disconnect();
// if commit was called with no active conn, it implies, no transact action
// was called. as such it is an error.
if (!conn) {
// allow one pseudo commit even without connection, so that programmatic call of repeated commits or
// rollbacks can be trapped.
// note that the absence of `_id` indicates that a `.disconnect` was called.
return callback && callback(id ? null : new AdapterError(AdapterError.TRANSACTION_UNINITIATED_ROLL));
}
conn.rollback(function (error) {
// try releasing the connection.
// if that fails then treat it as a major error.
try {
conn.release();
}
// if there was an error during release, set that as the main error.
catch (err) {
!error && (error = err);
}
// disassociate the connection from transaction and execute callback
Transaction.disassociateConnection(conn);
callback && callback(error);
});
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"conn",
"=",
"this",
".",
"connection",
"(",
")",
",",
"id",
"=",
"this",
".",
"_id",
";",
"this",
".",
"disconnect",
"(",
")",
";",
"if",
"(",
"!",
"conn",
")",
"{",
"return",
"callback",
"&&",
"callback",
"(",
"id",
"?",
"null",
":",
"new",
"AdapterError",
"(",
"AdapterError",
".",
"TRANSACTION_UNINITIATED_ROLL",
")",
")",
";",
"}",
"conn",
".",
"rollback",
"(",
"function",
"(",
"error",
")",
"{",
"try",
"{",
"conn",
".",
"release",
"(",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"!",
"error",
"&&",
"(",
"error",
"=",
"err",
")",
";",
"}",
"Transaction",
".",
"disassociateConnection",
"(",
"conn",
")",
";",
"callback",
"&&",
"callback",
"(",
"error",
")",
";",
"}",
")",
";",
"}"
]
| Rollback the transaction
@param {function} callback - receives `error` | [
"Rollback",
"the",
"transaction"
]
| 4c8bae4d428afb942860a51d4deb66aa5b9cd405 | https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/transactions.js#L385-L416 | train |
|
postmanlabs/sails-mysql-transactions | lib/multiplexer.js | function (config) {
if (!config) { return; }
var replConfig,
peerNames,
sanitisePeerConfig,
source = this.sources[config.identity]; // fn
// at this stage, the source should not be there
if (source) {
source.end(); // in case sources exist (almost unlikely, end them)
console.log('Warn: duplicate setup of connection found in replication setup for ' + config.identity);
}
// set default for configuration objects and also clone them
// ---------------------------------------------------------
// clone and set defaults for the configuration variables.
config = util.clone(config); // clone config. do it here to clone replication config too
replConfig = util.fill(config.replication || {
enabled: false // blank config means replication disabled
}, DEFAULT_REPL_SOURCE_CFG); // extract repl config from main config
!replConfig.sources && (replConfig.sources = {}); // set default to no source if none specified
delete config.replication; // we remove the recursive config from main config clone.
// setup a dumb source as a precaution and since we should fall back to original connection if setup fails
source = this.sources[config.identity] = db.oneDumbSource();
// replication explicitly disabled or no peers defined. we do this after ending any ongoing sources
source._replication = !!replConfig.enabled;
if (source._replication === false) {
return;
}
// create default connection parameters for cluster
// ------------------------------------------------
// get the list of peer names defined in sources and setup the config defaults for peer sources
peerNames = _.filter(Object.keys(replConfig.sources) || [], function (peer) { // remove all disabled peers
return (peer = replConfig.sources[peer]) && (peer.enabled !== false);
});
sanitisePeerConfig = function (peerConfig) {
return util.fill(util.extend(peerConfig, {
database: peerConfig._database || config.database, // force db name to be same
pool: true,
waitForConnections: true,
multipleStatements: true
}), (replConfig.inheritMaster === true) && config);
};
// depending upon the number of peers defined, create simple connection or clustered connection
// --------------------------------------------------------------------------------------------
// nothing much to do, if there are no replication source defined
if (peerNames.length === 0) {
sails && sails.log.info('smt is re-using master as readonly source');
// if it is marked to inherit master in replication, we simply create a new source out of the master config
if (replConfig.inheritMaster === true) {
this.sources[config.identity] = db.createSource(sanitisePeerConfig({}));
}
return;
}
// for a single peer, the configuration is simple, we do not need a cluster but a simple pool
if (peerNames.length === 1) {
sails && sails.log.info('smt is using 1 "' + config.identity + '" readonly source - ' + peerNames[0]);
// ensure that the single source's config is taken care of by setting the default and if needed inheriting
// from master
this.sources[config.identity] = db.createSource(sanitisePeerConfig(replConfig.sources[peerNames[0]]));
return;
}
// iterate over all sources and normalise and validate their configuration
util.each(replConfig.sources, sanitisePeerConfig);
sails && sails.log.info('smt is using ' + peerNames.length + ' "' + config.identity + '" readonly sources - ' +
peerNames.join(', '));
// create connections for read-replicas and add it to the peering list
this.sources[config.identity] = db.createCluster(replConfig);
} | javascript | function (config) {
if (!config) { return; }
var replConfig,
peerNames,
sanitisePeerConfig,
source = this.sources[config.identity]; // fn
// at this stage, the source should not be there
if (source) {
source.end(); // in case sources exist (almost unlikely, end them)
console.log('Warn: duplicate setup of connection found in replication setup for ' + config.identity);
}
// set default for configuration objects and also clone them
// ---------------------------------------------------------
// clone and set defaults for the configuration variables.
config = util.clone(config); // clone config. do it here to clone replication config too
replConfig = util.fill(config.replication || {
enabled: false // blank config means replication disabled
}, DEFAULT_REPL_SOURCE_CFG); // extract repl config from main config
!replConfig.sources && (replConfig.sources = {}); // set default to no source if none specified
delete config.replication; // we remove the recursive config from main config clone.
// setup a dumb source as a precaution and since we should fall back to original connection if setup fails
source = this.sources[config.identity] = db.oneDumbSource();
// replication explicitly disabled or no peers defined. we do this after ending any ongoing sources
source._replication = !!replConfig.enabled;
if (source._replication === false) {
return;
}
// create default connection parameters for cluster
// ------------------------------------------------
// get the list of peer names defined in sources and setup the config defaults for peer sources
peerNames = _.filter(Object.keys(replConfig.sources) || [], function (peer) { // remove all disabled peers
return (peer = replConfig.sources[peer]) && (peer.enabled !== false);
});
sanitisePeerConfig = function (peerConfig) {
return util.fill(util.extend(peerConfig, {
database: peerConfig._database || config.database, // force db name to be same
pool: true,
waitForConnections: true,
multipleStatements: true
}), (replConfig.inheritMaster === true) && config);
};
// depending upon the number of peers defined, create simple connection or clustered connection
// --------------------------------------------------------------------------------------------
// nothing much to do, if there are no replication source defined
if (peerNames.length === 0) {
sails && sails.log.info('smt is re-using master as readonly source');
// if it is marked to inherit master in replication, we simply create a new source out of the master config
if (replConfig.inheritMaster === true) {
this.sources[config.identity] = db.createSource(sanitisePeerConfig({}));
}
return;
}
// for a single peer, the configuration is simple, we do not need a cluster but a simple pool
if (peerNames.length === 1) {
sails && sails.log.info('smt is using 1 "' + config.identity + '" readonly source - ' + peerNames[0]);
// ensure that the single source's config is taken care of by setting the default and if needed inheriting
// from master
this.sources[config.identity] = db.createSource(sanitisePeerConfig(replConfig.sources[peerNames[0]]));
return;
}
// iterate over all sources and normalise and validate their configuration
util.each(replConfig.sources, sanitisePeerConfig);
sails && sails.log.info('smt is using ' + peerNames.length + ' "' + config.identity + '" readonly sources - ' +
peerNames.join(', '));
// create connections for read-replicas and add it to the peering list
this.sources[config.identity] = db.createCluster(replConfig);
} | [
"function",
"(",
"config",
")",
"{",
"if",
"(",
"!",
"config",
")",
"{",
"return",
";",
"}",
"var",
"replConfig",
",",
"peerNames",
",",
"sanitisePeerConfig",
",",
"source",
"=",
"this",
".",
"sources",
"[",
"config",
".",
"identity",
"]",
";",
"if",
"(",
"source",
")",
"{",
"source",
".",
"end",
"(",
")",
";",
"console",
".",
"log",
"(",
"'Warn: duplicate setup of connection found in replication setup for '",
"+",
"config",
".",
"identity",
")",
";",
"}",
"config",
"=",
"util",
".",
"clone",
"(",
"config",
")",
";",
"replConfig",
"=",
"util",
".",
"fill",
"(",
"config",
".",
"replication",
"||",
"{",
"enabled",
":",
"false",
"}",
",",
"DEFAULT_REPL_SOURCE_CFG",
")",
";",
"!",
"replConfig",
".",
"sources",
"&&",
"(",
"replConfig",
".",
"sources",
"=",
"{",
"}",
")",
";",
"delete",
"config",
".",
"replication",
";",
"source",
"=",
"this",
".",
"sources",
"[",
"config",
".",
"identity",
"]",
"=",
"db",
".",
"oneDumbSource",
"(",
")",
";",
"source",
".",
"_replication",
"=",
"!",
"!",
"replConfig",
".",
"enabled",
";",
"if",
"(",
"source",
".",
"_replication",
"===",
"false",
")",
"{",
"return",
";",
"}",
"peerNames",
"=",
"_",
".",
"filter",
"(",
"Object",
".",
"keys",
"(",
"replConfig",
".",
"sources",
")",
"||",
"[",
"]",
",",
"function",
"(",
"peer",
")",
"{",
"return",
"(",
"peer",
"=",
"replConfig",
".",
"sources",
"[",
"peer",
"]",
")",
"&&",
"(",
"peer",
".",
"enabled",
"!==",
"false",
")",
";",
"}",
")",
";",
"sanitisePeerConfig",
"=",
"function",
"(",
"peerConfig",
")",
"{",
"return",
"util",
".",
"fill",
"(",
"util",
".",
"extend",
"(",
"peerConfig",
",",
"{",
"database",
":",
"peerConfig",
".",
"_database",
"||",
"config",
".",
"database",
",",
"pool",
":",
"true",
",",
"waitForConnections",
":",
"true",
",",
"multipleStatements",
":",
"true",
"}",
")",
",",
"(",
"replConfig",
".",
"inheritMaster",
"===",
"true",
")",
"&&",
"config",
")",
";",
"}",
";",
"if",
"(",
"peerNames",
".",
"length",
"===",
"0",
")",
"{",
"sails",
"&&",
"sails",
".",
"log",
".",
"info",
"(",
"'smt is re-using master as readonly source'",
")",
";",
"if",
"(",
"replConfig",
".",
"inheritMaster",
"===",
"true",
")",
"{",
"this",
".",
"sources",
"[",
"config",
".",
"identity",
"]",
"=",
"db",
".",
"createSource",
"(",
"sanitisePeerConfig",
"(",
"{",
"}",
")",
")",
";",
"}",
"return",
";",
"}",
"if",
"(",
"peerNames",
".",
"length",
"===",
"1",
")",
"{",
"sails",
"&&",
"sails",
".",
"log",
".",
"info",
"(",
"'smt is using 1 \"'",
"+",
"config",
".",
"identity",
"+",
"'\" readonly source - '",
"+",
"peerNames",
"[",
"0",
"]",
")",
";",
"this",
".",
"sources",
"[",
"config",
".",
"identity",
"]",
"=",
"db",
".",
"createSource",
"(",
"sanitisePeerConfig",
"(",
"replConfig",
".",
"sources",
"[",
"peerNames",
"[",
"0",
"]",
"]",
")",
")",
";",
"return",
";",
"}",
"util",
".",
"each",
"(",
"replConfig",
".",
"sources",
",",
"sanitisePeerConfig",
")",
";",
"sails",
"&&",
"sails",
".",
"log",
".",
"info",
"(",
"'smt is using '",
"+",
"peerNames",
".",
"length",
"+",
"' \"'",
"+",
"config",
".",
"identity",
"+",
"'\" readonly sources - '",
"+",
"peerNames",
".",
"join",
"(",
"', '",
")",
")",
";",
"this",
".",
"sources",
"[",
"config",
".",
"identity",
"]",
"=",
"db",
".",
"createCluster",
"(",
"replConfig",
")",
";",
"}"
]
| Creates ORM setup sequencing for all replica set pools.
@param {object} config | [
"Creates",
"ORM",
"setup",
"sequencing",
"for",
"all",
"replica",
"set",
"pools",
"."
]
| 4c8bae4d428afb942860a51d4deb66aa5b9cd405 | https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/multiplexer.js#L78-L160 | train |
|
postmanlabs/sails-mysql-transactions | lib/multiplexer.js | function () {
// release all pending connections
util.each(this.connections, function (connection, threadId, connections) {
try {
connection.release();
}
catch (e) { } // nothing to do with error
delete connections[threadId];
});
// execute end on the db. will end pool if pool, or otherwise will execute whatever `end` that has been
// exposed by db.js
util.each(this.sources, function (source, identity, sources) {
try {
source && source.end();
}
catch (e) { } // nothing to do with error
delete sources[identity];
});
} | javascript | function () {
// release all pending connections
util.each(this.connections, function (connection, threadId, connections) {
try {
connection.release();
}
catch (e) { } // nothing to do with error
delete connections[threadId];
});
// execute end on the db. will end pool if pool, or otherwise will execute whatever `end` that has been
// exposed by db.js
util.each(this.sources, function (source, identity, sources) {
try {
source && source.end();
}
catch (e) { } // nothing to do with error
delete sources[identity];
});
} | [
"function",
"(",
")",
"{",
"util",
".",
"each",
"(",
"this",
".",
"connections",
",",
"function",
"(",
"connection",
",",
"threadId",
",",
"connections",
")",
"{",
"try",
"{",
"connection",
".",
"release",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"delete",
"connections",
"[",
"threadId",
"]",
";",
"}",
")",
";",
"util",
".",
"each",
"(",
"this",
".",
"sources",
",",
"function",
"(",
"source",
",",
"identity",
",",
"sources",
")",
"{",
"try",
"{",
"source",
"&&",
"source",
".",
"end",
"(",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"}",
"delete",
"sources",
"[",
"identity",
"]",
";",
"}",
")",
";",
"}"
]
| ORM teardown sequencing for all replica set pools | [
"ORM",
"teardown",
"sequencing",
"for",
"all",
"replica",
"set",
"pools"
]
| 4c8bae4d428afb942860a51d4deb66aa5b9cd405 | https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/multiplexer.js#L165-L184 | train |
|
postmanlabs/sails-mysql-transactions | lib/multiplexer.js | function (callback) {
var self = this;
if (!Multiplexer.sources[self._connectionName]) {
return callback(new AdapterError(AdapterError.UNKNOWN_CONNECTION));
}
Multiplexer.sources[self._connectionName].getConnection(function (error, connection) {
if (error) { return callback(error); }
// give a unique id to the connection and store it if not already
self._threadId = util.uid();
Multiplexer.connections[self._threadId] = connection;
callback(null, self._threadId, connection);
});
} | javascript | function (callback) {
var self = this;
if (!Multiplexer.sources[self._connectionName]) {
return callback(new AdapterError(AdapterError.UNKNOWN_CONNECTION));
}
Multiplexer.sources[self._connectionName].getConnection(function (error, connection) {
if (error) { return callback(error); }
// give a unique id to the connection and store it if not already
self._threadId = util.uid();
Multiplexer.connections[self._threadId] = connection;
callback(null, self._threadId, connection);
});
} | [
"function",
"(",
"callback",
")",
"{",
"var",
"self",
"=",
"this",
";",
"if",
"(",
"!",
"Multiplexer",
".",
"sources",
"[",
"self",
".",
"_connectionName",
"]",
")",
"{",
"return",
"callback",
"(",
"new",
"AdapterError",
"(",
"AdapterError",
".",
"UNKNOWN_CONNECTION",
")",
")",
";",
"}",
"Multiplexer",
".",
"sources",
"[",
"self",
".",
"_connectionName",
"]",
".",
"getConnection",
"(",
"function",
"(",
"error",
",",
"connection",
")",
"{",
"if",
"(",
"error",
")",
"{",
"return",
"callback",
"(",
"error",
")",
";",
"}",
"self",
".",
"_threadId",
"=",
"util",
".",
"uid",
"(",
")",
";",
"Multiplexer",
".",
"connections",
"[",
"self",
".",
"_threadId",
"]",
"=",
"connection",
";",
"callback",
"(",
"null",
",",
"self",
".",
"_threadId",
",",
"connection",
")",
";",
"}",
")",
";",
"}"
]
| Retrieves a new connection for initialising queries from the pool specified as parameter.
@param {function} callback receives `error`, `threadId`, `connection` as parameter | [
"Retrieves",
"a",
"new",
"connection",
"for",
"initialising",
"queries",
"from",
"the",
"pool",
"specified",
"as",
"parameter",
"."
]
| 4c8bae4d428afb942860a51d4deb66aa5b9cd405 | https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/multiplexer.js#L203-L219 | train |
|
postmanlabs/sails-mysql-transactions | lib/multiplexer.js | function (threadId) {
Multiplexer.connections[threadId] && Multiplexer.connections[threadId].release();
delete Multiplexer.connections[threadId];
} | javascript | function (threadId) {
Multiplexer.connections[threadId] && Multiplexer.connections[threadId].release();
delete Multiplexer.connections[threadId];
} | [
"function",
"(",
"threadId",
")",
"{",
"Multiplexer",
".",
"connections",
"[",
"threadId",
"]",
"&&",
"Multiplexer",
".",
"connections",
"[",
"threadId",
"]",
".",
"release",
"(",
")",
";",
"delete",
"Multiplexer",
".",
"connections",
"[",
"threadId",
"]",
";",
"}"
]
| Release the connection associated with this multiplexer
@param {string} threadId | [
"Release",
"the",
"connection",
"associated",
"with",
"this",
"multiplexer"
]
| 4c8bae4d428afb942860a51d4deb66aa5b9cd405 | https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/multiplexer.js#L225-L228 | train |
|
postmanlabs/sails-mysql-transactions | lib/adapter.js | function (connectionName, collectionName, obj, cb) {
if (_.isObject(obj)) {
try {
var modelInstance = new this._model(obj);
return cb(null, modelInstance);
}
catch (err) {
return cb(err, null);
}
}
} | javascript | function (connectionName, collectionName, obj, cb) {
if (_.isObject(obj)) {
try {
var modelInstance = new this._model(obj);
return cb(null, modelInstance);
}
catch (err) {
return cb(err, null);
}
}
} | [
"function",
"(",
"connectionName",
",",
"collectionName",
",",
"obj",
",",
"cb",
")",
"{",
"if",
"(",
"_",
".",
"isObject",
"(",
"obj",
")",
")",
"{",
"try",
"{",
"var",
"modelInstance",
"=",
"new",
"this",
".",
"_model",
"(",
"obj",
")",
";",
"return",
"cb",
"(",
"null",
",",
"modelInstance",
")",
";",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"cb",
"(",
"err",
",",
"null",
")",
";",
"}",
"}",
"}"
]
| This allows one to create a model instance.
@param {string} connectionName
@param {string} collectionName
@param {Object} obj
@param {Function} cb
@returns {Object} Model Instance | [
"This",
"allows",
"one",
"to",
"create",
"a",
"model",
"instance",
"."
]
| 4c8bae4d428afb942860a51d4deb66aa5b9cd405 | https://github.com/postmanlabs/sails-mysql-transactions/blob/4c8bae4d428afb942860a51d4deb66aa5b9cd405/lib/adapter.js#L203-L213 | train |
|
dmachat/angular-datamaps | dist/angular-datamaps.js | mapOptions | function mapOptions() {
return {
element: element[0],
scope: 'usa',
height: scope.height,
width: scope.width,
fills: { defaultFill: '#b9b9b9' },
data: {},
done: function (datamap) {
function redraw() {
datamap.svg.selectAll('g').attr('transform', 'translate(' + d3.event.translate + ')scale(' + d3.event.scale + ')');
}
if (angular.isDefined(attrs.onClick)) {
datamap.svg.selectAll('.datamaps-subunit').on('click', function (geography) {
scope.onClick()(geography);
});
}
if (angular.isDefined(attrs.zoomable)) {
datamap.svg.call(d3.behavior.zoom().on('zoom', redraw));
}
}
};
} | javascript | function mapOptions() {
return {
element: element[0],
scope: 'usa',
height: scope.height,
width: scope.width,
fills: { defaultFill: '#b9b9b9' },
data: {},
done: function (datamap) {
function redraw() {
datamap.svg.selectAll('g').attr('transform', 'translate(' + d3.event.translate + ')scale(' + d3.event.scale + ')');
}
if (angular.isDefined(attrs.onClick)) {
datamap.svg.selectAll('.datamaps-subunit').on('click', function (geography) {
scope.onClick()(geography);
});
}
if (angular.isDefined(attrs.zoomable)) {
datamap.svg.call(d3.behavior.zoom().on('zoom', redraw));
}
}
};
} | [
"function",
"mapOptions",
"(",
")",
"{",
"return",
"{",
"element",
":",
"element",
"[",
"0",
"]",
",",
"scope",
":",
"'usa'",
",",
"height",
":",
"scope",
".",
"height",
",",
"width",
":",
"scope",
".",
"width",
",",
"fills",
":",
"{",
"defaultFill",
":",
"'#b9b9b9'",
"}",
",",
"data",
":",
"{",
"}",
",",
"done",
":",
"function",
"(",
"datamap",
")",
"{",
"function",
"redraw",
"(",
")",
"{",
"datamap",
".",
"svg",
".",
"selectAll",
"(",
"'g'",
")",
".",
"attr",
"(",
"'transform'",
",",
"'translate('",
"+",
"d3",
".",
"event",
".",
"translate",
"+",
"')scale('",
"+",
"d3",
".",
"event",
".",
"scale",
"+",
"')'",
")",
";",
"}",
"if",
"(",
"angular",
".",
"isDefined",
"(",
"attrs",
".",
"onClick",
")",
")",
"{",
"datamap",
".",
"svg",
".",
"selectAll",
"(",
"'.datamaps-subunit'",
")",
".",
"on",
"(",
"'click'",
",",
"function",
"(",
"geography",
")",
"{",
"scope",
".",
"onClick",
"(",
")",
"(",
"geography",
")",
";",
"}",
")",
";",
"}",
"if",
"(",
"angular",
".",
"isDefined",
"(",
"attrs",
".",
"zoomable",
")",
")",
"{",
"datamap",
".",
"svg",
".",
"call",
"(",
"d3",
".",
"behavior",
".",
"zoom",
"(",
")",
".",
"on",
"(",
"'zoom'",
",",
"redraw",
")",
")",
";",
"}",
"}",
"}",
";",
"}"
]
| Generate base map options | [
"Generate",
"base",
"map",
"options"
]
| 1813d387a7d32bf59c353455c06b1b2ff62f06e1 | https://github.com/dmachat/angular-datamaps/blob/1813d387a7d32bf59c353455c06b1b2ff62f06e1/dist/angular-datamaps.js#L18-L40 | train |
hugs/node-castro | castro.js | function(path) {
// TODO: Does file exist at the file location path? If so, do something about it...
//var defaultManager = $.NSFileManager('alloc')('init')
//if (defaultManager('fileExistsAtPath',NSlocation)) {
// console.log("File already exists!")
//}
if (!path){
// Default Destination: e.g. "/Users/hugs/Desktop/Castro_uul3di.mov"
var homeDir = $.NSHomeDirectory();
var desktopDir = homeDir.toString() + '/Desktop/';
var randomString = (Math.random() + 1).toString(36).substring(12);
var filename = 'Castro_' + randomString + '.mp4';
this.location = desktopDir + filename;
} else {
// TODO: Make sure path is legit.
this.location = path;
}
this.NSlocation = $.NSString('stringWithUTF8String', this.location);
this.NSlocationURL = $.NSURL('fileURLWithPath', this.NSlocation);
} | javascript | function(path) {
// TODO: Does file exist at the file location path? If so, do something about it...
//var defaultManager = $.NSFileManager('alloc')('init')
//if (defaultManager('fileExistsAtPath',NSlocation)) {
// console.log("File already exists!")
//}
if (!path){
// Default Destination: e.g. "/Users/hugs/Desktop/Castro_uul3di.mov"
var homeDir = $.NSHomeDirectory();
var desktopDir = homeDir.toString() + '/Desktop/';
var randomString = (Math.random() + 1).toString(36).substring(12);
var filename = 'Castro_' + randomString + '.mp4';
this.location = desktopDir + filename;
} else {
// TODO: Make sure path is legit.
this.location = path;
}
this.NSlocation = $.NSString('stringWithUTF8String', this.location);
this.NSlocationURL = $.NSURL('fileURLWithPath', this.NSlocation);
} | [
"function",
"(",
"path",
")",
"{",
"if",
"(",
"!",
"path",
")",
"{",
"var",
"homeDir",
"=",
"$",
".",
"NSHomeDirectory",
"(",
")",
";",
"var",
"desktopDir",
"=",
"homeDir",
".",
"toString",
"(",
")",
"+",
"'/Desktop/'",
";",
"var",
"randomString",
"=",
"(",
"Math",
".",
"random",
"(",
")",
"+",
"1",
")",
".",
"toString",
"(",
"36",
")",
".",
"substring",
"(",
"12",
")",
";",
"var",
"filename",
"=",
"'Castro_'",
"+",
"randomString",
"+",
"'.mp4'",
";",
"this",
".",
"location",
"=",
"desktopDir",
"+",
"filename",
";",
"}",
"else",
"{",
"this",
".",
"location",
"=",
"path",
";",
"}",
"this",
".",
"NSlocation",
"=",
"$",
".",
"NSString",
"(",
"'stringWithUTF8String'",
",",
"this",
".",
"location",
")",
";",
"this",
".",
"NSlocationURL",
"=",
"$",
".",
"NSURL",
"(",
"'fileURLWithPath'",
",",
"this",
".",
"NSlocation",
")",
";",
"}"
]
| Set recording file location | [
"Set",
"recording",
"file",
"location"
]
| a1499ec73dcb2517fcb7ddb5b8ccc359c5740462 | https://github.com/hugs/node-castro/blob/a1499ec73dcb2517fcb7ddb5b8ccc359c5740462/castro.js#L41-L61 | train |
|
neurospeech/web-atoms.js | plugins/videojs/video.dev.js | function(player, options, ready){
this.player_ = player;
// Make a copy of prototype.options_ to protect against overriding global defaults
this.options_ = vjs.obj.copy(this.options_);
// Updated options with supplied options
options = this.options(options);
// Get ID from options, element, or create using player ID and unique ID
this.id_ = options['id'] || ((options['el'] && options['el']['id']) ? options['el']['id'] : player.id() + '_component_' + vjs.guid++ );
this.name_ = options['name'] || null;
// Create element if one wasn't provided in options
this.el_ = options['el'] || this.createEl();
this.children_ = [];
this.childIndex_ = {};
this.childNameIndex_ = {};
// Add any child components in options
this.initChildren();
this.ready(ready);
// Don't want to trigger ready here or it will before init is actually
// finished for all children that run this constructor
if (options.reportTouchActivity !== false) {
this.enableTouchActivity();
}
} | javascript | function(player, options, ready){
this.player_ = player;
// Make a copy of prototype.options_ to protect against overriding global defaults
this.options_ = vjs.obj.copy(this.options_);
// Updated options with supplied options
options = this.options(options);
// Get ID from options, element, or create using player ID and unique ID
this.id_ = options['id'] || ((options['el'] && options['el']['id']) ? options['el']['id'] : player.id() + '_component_' + vjs.guid++ );
this.name_ = options['name'] || null;
// Create element if one wasn't provided in options
this.el_ = options['el'] || this.createEl();
this.children_ = [];
this.childIndex_ = {};
this.childNameIndex_ = {};
// Add any child components in options
this.initChildren();
this.ready(ready);
// Don't want to trigger ready here or it will before init is actually
// finished for all children that run this constructor
if (options.reportTouchActivity !== false) {
this.enableTouchActivity();
}
} | [
"function",
"(",
"player",
",",
"options",
",",
"ready",
")",
"{",
"this",
".",
"player_",
"=",
"player",
";",
"this",
".",
"options_",
"=",
"vjs",
".",
"obj",
".",
"copy",
"(",
"this",
".",
"options_",
")",
";",
"options",
"=",
"this",
".",
"options",
"(",
"options",
")",
";",
"this",
".",
"id_",
"=",
"options",
"[",
"'id'",
"]",
"||",
"(",
"(",
"options",
"[",
"'el'",
"]",
"&&",
"options",
"[",
"'el'",
"]",
"[",
"'id'",
"]",
")",
"?",
"options",
"[",
"'el'",
"]",
"[",
"'id'",
"]",
":",
"player",
".",
"id",
"(",
")",
"+",
"'_component_'",
"+",
"vjs",
".",
"guid",
"++",
")",
";",
"this",
".",
"name_",
"=",
"options",
"[",
"'name'",
"]",
"||",
"null",
";",
"this",
".",
"el_",
"=",
"options",
"[",
"'el'",
"]",
"||",
"this",
".",
"createEl",
"(",
")",
";",
"this",
".",
"children_",
"=",
"[",
"]",
";",
"this",
".",
"childIndex_",
"=",
"{",
"}",
";",
"this",
".",
"childNameIndex_",
"=",
"{",
"}",
";",
"this",
".",
"initChildren",
"(",
")",
";",
"this",
".",
"ready",
"(",
"ready",
")",
";",
"if",
"(",
"options",
".",
"reportTouchActivity",
"!==",
"false",
")",
"{",
"this",
".",
"enableTouchActivity",
"(",
")",
";",
"}",
"}"
]
| the constructor function for the class
@constructor | [
"the",
"constructor",
"function",
"for",
"the",
"class"
]
| 136a2d0987ef9fe492e99badf8ff177e9a2cc6ba | https://github.com/neurospeech/web-atoms.js/blob/136a2d0987ef9fe492e99badf8ff177e9a2cc6ba/plugins/videojs/video.dev.js#L1395-L1426 | train |
|
neurospeech/web-atoms.js | plugins/videojs/video.dev.js | function(tag, options, ready){
this.tag = tag; // Store the original tag used to set options
// Make sure tag ID exists
tag.id = tag.id || 'vjs_video_' + vjs.guid++;
// Set Options
// The options argument overrides options set in the video tag
// which overrides globally set options.
// This latter part coincides with the load order
// (tag must exist before Player)
options = vjs.obj.merge(this.getTagSettings(tag), options);
// Cache for video property values.
this.cache_ = {};
// Set poster
this.poster_ = options['poster'];
// Set controls
this.controls_ = options['controls'];
// Original tag settings stored in options
// now remove immediately so native controls don't flash.
// May be turned back on by HTML5 tech if nativeControlsForTouch is true
tag.controls = false;
// we don't want the player to report touch activity on itself
// see enableTouchActivity in Component
options.reportTouchActivity = false;
// Run base component initializing with new options.
// Builds the element through createEl()
// Inits and embeds any child components in opts
vjs.Component.call(this, this, options, ready);
// Update controls className. Can't do this when the controls are initially
// set because the element doesn't exist yet.
if (this.controls()) {
this.addClass('vjs-controls-enabled');
} else {
this.addClass('vjs-controls-disabled');
}
// TODO: Make this smarter. Toggle user state between touching/mousing
// using events, since devices can have both touch and mouse events.
// if (vjs.TOUCH_ENABLED) {
// this.addClass('vjs-touch-enabled');
// }
// Firstplay event implimentation. Not sold on the event yet.
// Could probably just check currentTime==0?
this.one('play', function(e){
var fpEvent = { type: 'firstplay', target: this.el_ };
// Using vjs.trigger so we can check if default was prevented
var keepGoing = vjs.trigger(this.el_, fpEvent);
if (!keepGoing) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
}
});
this.on('ended', this.onEnded);
this.on('play', this.onPlay);
this.on('firstplay', this.onFirstPlay);
this.on('pause', this.onPause);
this.on('progress', this.onProgress);
this.on('durationchange', this.onDurationChange);
this.on('error', this.onError);
this.on('fullscreenchange', this.onFullscreenChange);
// Make player easily findable by ID
vjs.players[this.id_] = this;
if (options['plugins']) {
vjs.obj.each(options['plugins'], function(key, val){
this[key](val);
}, this);
}
this.listenForUserActivity();
} | javascript | function(tag, options, ready){
this.tag = tag; // Store the original tag used to set options
// Make sure tag ID exists
tag.id = tag.id || 'vjs_video_' + vjs.guid++;
// Set Options
// The options argument overrides options set in the video tag
// which overrides globally set options.
// This latter part coincides with the load order
// (tag must exist before Player)
options = vjs.obj.merge(this.getTagSettings(tag), options);
// Cache for video property values.
this.cache_ = {};
// Set poster
this.poster_ = options['poster'];
// Set controls
this.controls_ = options['controls'];
// Original tag settings stored in options
// now remove immediately so native controls don't flash.
// May be turned back on by HTML5 tech if nativeControlsForTouch is true
tag.controls = false;
// we don't want the player to report touch activity on itself
// see enableTouchActivity in Component
options.reportTouchActivity = false;
// Run base component initializing with new options.
// Builds the element through createEl()
// Inits and embeds any child components in opts
vjs.Component.call(this, this, options, ready);
// Update controls className. Can't do this when the controls are initially
// set because the element doesn't exist yet.
if (this.controls()) {
this.addClass('vjs-controls-enabled');
} else {
this.addClass('vjs-controls-disabled');
}
// TODO: Make this smarter. Toggle user state between touching/mousing
// using events, since devices can have both touch and mouse events.
// if (vjs.TOUCH_ENABLED) {
// this.addClass('vjs-touch-enabled');
// }
// Firstplay event implimentation. Not sold on the event yet.
// Could probably just check currentTime==0?
this.one('play', function(e){
var fpEvent = { type: 'firstplay', target: this.el_ };
// Using vjs.trigger so we can check if default was prevented
var keepGoing = vjs.trigger(this.el_, fpEvent);
if (!keepGoing) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
}
});
this.on('ended', this.onEnded);
this.on('play', this.onPlay);
this.on('firstplay', this.onFirstPlay);
this.on('pause', this.onPause);
this.on('progress', this.onProgress);
this.on('durationchange', this.onDurationChange);
this.on('error', this.onError);
this.on('fullscreenchange', this.onFullscreenChange);
// Make player easily findable by ID
vjs.players[this.id_] = this;
if (options['plugins']) {
vjs.obj.each(options['plugins'], function(key, val){
this[key](val);
}, this);
}
this.listenForUserActivity();
} | [
"function",
"(",
"tag",
",",
"options",
",",
"ready",
")",
"{",
"this",
".",
"tag",
"=",
"tag",
";",
"tag",
".",
"id",
"=",
"tag",
".",
"id",
"||",
"'vjs_video_'",
"+",
"vjs",
".",
"guid",
"++",
";",
"options",
"=",
"vjs",
".",
"obj",
".",
"merge",
"(",
"this",
".",
"getTagSettings",
"(",
"tag",
")",
",",
"options",
")",
";",
"this",
".",
"cache_",
"=",
"{",
"}",
";",
"this",
".",
"poster_",
"=",
"options",
"[",
"'poster'",
"]",
";",
"this",
".",
"controls_",
"=",
"options",
"[",
"'controls'",
"]",
";",
"tag",
".",
"controls",
"=",
"false",
";",
"options",
".",
"reportTouchActivity",
"=",
"false",
";",
"vjs",
".",
"Component",
".",
"call",
"(",
"this",
",",
"this",
",",
"options",
",",
"ready",
")",
";",
"if",
"(",
"this",
".",
"controls",
"(",
")",
")",
"{",
"this",
".",
"addClass",
"(",
"'vjs-controls-enabled'",
")",
";",
"}",
"else",
"{",
"this",
".",
"addClass",
"(",
"'vjs-controls-disabled'",
")",
";",
"}",
"this",
".",
"one",
"(",
"'play'",
",",
"function",
"(",
"e",
")",
"{",
"var",
"fpEvent",
"=",
"{",
"type",
":",
"'firstplay'",
",",
"target",
":",
"this",
".",
"el_",
"}",
";",
"var",
"keepGoing",
"=",
"vjs",
".",
"trigger",
"(",
"this",
".",
"el_",
",",
"fpEvent",
")",
";",
"if",
"(",
"!",
"keepGoing",
")",
"{",
"e",
".",
"preventDefault",
"(",
")",
";",
"e",
".",
"stopPropagation",
"(",
")",
";",
"e",
".",
"stopImmediatePropagation",
"(",
")",
";",
"}",
"}",
")",
";",
"this",
".",
"on",
"(",
"'ended'",
",",
"this",
".",
"onEnded",
")",
";",
"this",
".",
"on",
"(",
"'play'",
",",
"this",
".",
"onPlay",
")",
";",
"this",
".",
"on",
"(",
"'firstplay'",
",",
"this",
".",
"onFirstPlay",
")",
";",
"this",
".",
"on",
"(",
"'pause'",
",",
"this",
".",
"onPause",
")",
";",
"this",
".",
"on",
"(",
"'progress'",
",",
"this",
".",
"onProgress",
")",
";",
"this",
".",
"on",
"(",
"'durationchange'",
",",
"this",
".",
"onDurationChange",
")",
";",
"this",
".",
"on",
"(",
"'error'",
",",
"this",
".",
"onError",
")",
";",
"this",
".",
"on",
"(",
"'fullscreenchange'",
",",
"this",
".",
"onFullscreenChange",
")",
";",
"vjs",
".",
"players",
"[",
"this",
".",
"id_",
"]",
"=",
"this",
";",
"if",
"(",
"options",
"[",
"'plugins'",
"]",
")",
"{",
"vjs",
".",
"obj",
".",
"each",
"(",
"options",
"[",
"'plugins'",
"]",
",",
"function",
"(",
"key",
",",
"val",
")",
"{",
"this",
"[",
"key",
"]",
"(",
"val",
")",
";",
"}",
",",
"this",
")",
";",
"}",
"this",
".",
"listenForUserActivity",
"(",
")",
";",
"}"
]
| player's constructor function
@constructs
@method init
@param {Element} tag The original video tag used for configuring options
@param {Object=} options Player options
@param {Function=} ready Ready callback function | [
"player",
"s",
"constructor",
"function"
]
| 136a2d0987ef9fe492e99badf8ff177e9a2cc6ba | https://github.com/neurospeech/web-atoms.js/blob/136a2d0987ef9fe492e99badf8ff177e9a2cc6ba/plugins/videojs/video.dev.js#L2836-L2917 | train |
|
lastboy/package-script | utils/Logger.js | function (data) {
if (!isLog()) {
return undefined;
}
try {
_fs.appendFileSync("pkgscript.log", (_utils.now() + " " + data + "\n"), "utf8");
} catch (e) {
console.error(_utils.now + " [package-script] Package Script, ERROR:", e);
}
} | javascript | function (data) {
if (!isLog()) {
return undefined;
}
try {
_fs.appendFileSync("pkgscript.log", (_utils.now() + " " + data + "\n"), "utf8");
} catch (e) {
console.error(_utils.now + " [package-script] Package Script, ERROR:", e);
}
} | [
"function",
"(",
"data",
")",
"{",
"if",
"(",
"!",
"isLog",
"(",
")",
")",
"{",
"return",
"undefined",
";",
"}",
"try",
"{",
"_fs",
".",
"appendFileSync",
"(",
"\"pkgscript.log\"",
",",
"(",
"_utils",
".",
"now",
"(",
")",
"+",
"\" \"",
"+",
"data",
"+",
"\"\\n\"",
")",
",",
"\\n",
")",
";",
"}",
"\"utf8\"",
"}"
]
| Print the given data to a file
@param data The data to be write | [
"Print",
"the",
"given",
"data",
"to",
"a",
"file"
]
| f0be6bdfc7b4e6689f9040ebe034407f907cabd5 | https://github.com/lastboy/package-script/blob/f0be6bdfc7b4e6689f9040ebe034407f907cabd5/utils/Logger.js#L22-L34 | train |
|
lastboy/package-script | utils/Logger.js | function (msg) {
if (!isLog()) {
return undefined;
}
if (msg) {
console.log(_utils.now() + " " + msg);
this.log2file(msg);
}
} | javascript | function (msg) {
if (!isLog()) {
return undefined;
}
if (msg) {
console.log(_utils.now() + " " + msg);
this.log2file(msg);
}
} | [
"function",
"(",
"msg",
")",
"{",
"if",
"(",
"!",
"isLog",
"(",
")",
")",
"{",
"return",
"undefined",
";",
"}",
"if",
"(",
"msg",
")",
"{",
"console",
".",
"log",
"(",
"_utils",
".",
"now",
"(",
")",
"+",
"\" \"",
"+",
"msg",
")",
";",
"this",
".",
"log2file",
"(",
"msg",
")",
";",
"}",
"}"
]
| Log a message to the console and to a file.
@param msg | [
"Log",
"a",
"message",
"to",
"the",
"console",
"and",
"to",
"a",
"file",
"."
]
| f0be6bdfc7b4e6689f9040ebe034407f907cabd5 | https://github.com/lastboy/package-script/blob/f0be6bdfc7b4e6689f9040ebe034407f907cabd5/utils/Logger.js#L41-L51 | train |
|
lastboy/package-script | pkgscript.js | setSpawnObject | function setSpawnObject(admin) {
admin = ((admin === undefined) ? getDefaultAdmin() : admin);
if (isLinux && admin) {
spawn = sudoarg;
} else {
spawn = cparg.spawn;
}
return admin;
} | javascript | function setSpawnObject(admin) {
admin = ((admin === undefined) ? getDefaultAdmin() : admin);
if (isLinux && admin) {
spawn = sudoarg;
} else {
spawn = cparg.spawn;
}
return admin;
} | [
"function",
"setSpawnObject",
"(",
"admin",
")",
"{",
"admin",
"=",
"(",
"(",
"admin",
"===",
"undefined",
")",
"?",
"getDefaultAdmin",
"(",
")",
":",
"admin",
")",
";",
"if",
"(",
"isLinux",
"&&",
"admin",
")",
"{",
"spawn",
"=",
"sudoarg",
";",
"}",
"else",
"{",
"spawn",
"=",
"cparg",
".",
"spawn",
";",
"}",
"return",
"admin",
";",
"}"
]
| Set the current spawn object.
Can be sudo for getting the admin prompt or child_process
@param admin | [
"Set",
"the",
"current",
"spawn",
"object",
".",
"Can",
"be",
"sudo",
"for",
"getting",
"the",
"admin",
"prompt",
"or",
"child_process"
]
| f0be6bdfc7b4e6689f9040ebe034407f907cabd5 | https://github.com/lastboy/package-script/blob/f0be6bdfc7b4e6689f9040ebe034407f907cabd5/pkgscript.js#L49-L57 | train |
lastboy/package-script | pkgscript.js | install | function install(items, callback) {
var item = items[next],
command = item.command,
args = item.args,
admin = item.admin,
spawnopt = (item.spawnopt || {}),
print;
// set the spawn object according to the passed admin argument
admin = setSpawnObject(admin);
// run the command
if (isLinux) {
if (admin) {
// use sudo
args.unshift(command);
print = args.join(" ");
logger.console.log("[package-script] Running Installer command: " + print);
sudoopt.spawnOptions = {};
jsutils.Object.copy(spawnopt, sudoopt.spawnOptions);
cprocess = spawn(args, sudoopt);
} else {
//use child_process
print = args.join(" ");
logger.console.log("[package-script] Running Installer command: " + command + " " + print);
cprocess = spawn(command, args, spawnopt);
}
} else {
args.unshift(command);
args.unshift("/c");
command = "cmd";
print = [command, args.join(" ")].join(" ");
logger.console.log("[package-script] Running Installer command: " + print);
cprocess = spawn(command, args, spawnopt);
}
// -- Spawn Listeners
cprocess.stdout.on('data', function (data) {
var log = 'CAT Installer: ' + data;
logger.logall(log);
});
cprocess.stderr.on('data', function (data) {
if (data && (new String(data)).indexOf("npm ERR") != -1) {
logger.logall('Package Script : ' + data);
} else {
logger.log2file('Package Script : ' + data);
}
});
cprocess.on('close', function (code) {
logger.log2file('Package Script Complete ' + code);
next++;
if (next < size) {
install(items, callback);
} else {
// callback
if (callback && _.isFunction(callback)) {
callback.call(this, code);
}
}
});
} | javascript | function install(items, callback) {
var item = items[next],
command = item.command,
args = item.args,
admin = item.admin,
spawnopt = (item.spawnopt || {}),
print;
// set the spawn object according to the passed admin argument
admin = setSpawnObject(admin);
// run the command
if (isLinux) {
if (admin) {
// use sudo
args.unshift(command);
print = args.join(" ");
logger.console.log("[package-script] Running Installer command: " + print);
sudoopt.spawnOptions = {};
jsutils.Object.copy(spawnopt, sudoopt.spawnOptions);
cprocess = spawn(args, sudoopt);
} else {
//use child_process
print = args.join(" ");
logger.console.log("[package-script] Running Installer command: " + command + " " + print);
cprocess = spawn(command, args, spawnopt);
}
} else {
args.unshift(command);
args.unshift("/c");
command = "cmd";
print = [command, args.join(" ")].join(" ");
logger.console.log("[package-script] Running Installer command: " + print);
cprocess = spawn(command, args, spawnopt);
}
// -- Spawn Listeners
cprocess.stdout.on('data', function (data) {
var log = 'CAT Installer: ' + data;
logger.logall(log);
});
cprocess.stderr.on('data', function (data) {
if (data && (new String(data)).indexOf("npm ERR") != -1) {
logger.logall('Package Script : ' + data);
} else {
logger.log2file('Package Script : ' + data);
}
});
cprocess.on('close', function (code) {
logger.log2file('Package Script Complete ' + code);
next++;
if (next < size) {
install(items, callback);
} else {
// callback
if (callback && _.isFunction(callback)) {
callback.call(this, code);
}
}
});
} | [
"function",
"install",
"(",
"items",
",",
"callback",
")",
"{",
"var",
"item",
"=",
"items",
"[",
"next",
"]",
",",
"command",
"=",
"item",
".",
"command",
",",
"args",
"=",
"item",
".",
"args",
",",
"admin",
"=",
"item",
".",
"admin",
",",
"spawnopt",
"=",
"(",
"item",
".",
"spawnopt",
"||",
"{",
"}",
")",
",",
"print",
";",
"admin",
"=",
"setSpawnObject",
"(",
"admin",
")",
";",
"if",
"(",
"isLinux",
")",
"{",
"if",
"(",
"admin",
")",
"{",
"args",
".",
"unshift",
"(",
"command",
")",
";",
"print",
"=",
"args",
".",
"join",
"(",
"\" \"",
")",
";",
"logger",
".",
"console",
".",
"log",
"(",
"\"[package-script] Running Installer command: \"",
"+",
"print",
")",
";",
"sudoopt",
".",
"spawnOptions",
"=",
"{",
"}",
";",
"jsutils",
".",
"Object",
".",
"copy",
"(",
"spawnopt",
",",
"sudoopt",
".",
"spawnOptions",
")",
";",
"cprocess",
"=",
"spawn",
"(",
"args",
",",
"sudoopt",
")",
";",
"}",
"else",
"{",
"print",
"=",
"args",
".",
"join",
"(",
"\" \"",
")",
";",
"logger",
".",
"console",
".",
"log",
"(",
"\"[package-script] Running Installer command: \"",
"+",
"command",
"+",
"\" \"",
"+",
"print",
")",
";",
"cprocess",
"=",
"spawn",
"(",
"command",
",",
"args",
",",
"spawnopt",
")",
";",
"}",
"}",
"else",
"{",
"args",
".",
"unshift",
"(",
"command",
")",
";",
"args",
".",
"unshift",
"(",
"\"/c\"",
")",
";",
"command",
"=",
"\"cmd\"",
";",
"print",
"=",
"[",
"command",
",",
"args",
".",
"join",
"(",
"\" \"",
")",
"]",
".",
"join",
"(",
"\" \"",
")",
";",
"logger",
".",
"console",
".",
"log",
"(",
"\"[package-script] Running Installer command: \"",
"+",
"print",
")",
";",
"cprocess",
"=",
"spawn",
"(",
"command",
",",
"args",
",",
"spawnopt",
")",
";",
"}",
"cprocess",
".",
"stdout",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"var",
"log",
"=",
"'CAT Installer: '",
"+",
"data",
";",
"logger",
".",
"logall",
"(",
"log",
")",
";",
"}",
")",
";",
"cprocess",
".",
"stderr",
".",
"on",
"(",
"'data'",
",",
"function",
"(",
"data",
")",
"{",
"if",
"(",
"data",
"&&",
"(",
"new",
"String",
"(",
"data",
")",
")",
".",
"indexOf",
"(",
"\"npm ERR\"",
")",
"!=",
"-",
"1",
")",
"{",
"logger",
".",
"logall",
"(",
"'Package Script : '",
"+",
"data",
")",
";",
"}",
"else",
"{",
"logger",
".",
"log2file",
"(",
"'Package Script : '",
"+",
"data",
")",
";",
"}",
"}",
")",
";",
"cprocess",
".",
"on",
"(",
"'close'",
",",
"function",
"(",
"code",
")",
"{",
"logger",
".",
"log2file",
"(",
"'Package Script Complete '",
"+",
"code",
")",
";",
"next",
"++",
";",
"if",
"(",
"next",
"<",
"size",
")",
"{",
"install",
"(",
"items",
",",
"callback",
")",
";",
"}",
"else",
"{",
"if",
"(",
"callback",
"&&",
"_",
".",
"isFunction",
"(",
"callback",
")",
")",
"{",
"callback",
".",
"call",
"(",
"this",
",",
"code",
")",
";",
"}",
"}",
"}",
")",
";",
"}"
]
| Run a single spawn operation according to the given configuration
@param items The passed configuration items
@param callback The functionality to be called on complete | [
"Run",
"a",
"single",
"spawn",
"operation",
"according",
"to",
"the",
"given",
"configuration"
]
| f0be6bdfc7b4e6689f9040ebe034407f907cabd5 | https://github.com/lastboy/package-script/blob/f0be6bdfc7b4e6689f9040ebe034407f907cabd5/pkgscript.js#L76-L144 | train |
lastboy/package-script | pkgscript.js | function(config, init, callback) {
var me = this;
// first initialize
if (init) {
this.init(init);
}
logger.log2file("\n\n************ Package Script ************************************* process id: " + process.pid);
if (config && _.isArray(config)) {
commands = commands.concat(config);
size = commands.length;
if (size > 0) {
install(commands, function() {
logger.logall("[package-script] process completed, see pkgscript.log for more information");
if (callback) {
callback.call(me);
}
});
}
} else {
logger.logall("[package-script] No valid configuration for 'install' function, see the docs for more information ");
}
} | javascript | function(config, init, callback) {
var me = this;
// first initialize
if (init) {
this.init(init);
}
logger.log2file("\n\n************ Package Script ************************************* process id: " + process.pid);
if (config && _.isArray(config)) {
commands = commands.concat(config);
size = commands.length;
if (size > 0) {
install(commands, function() {
logger.logall("[package-script] process completed, see pkgscript.log for more information");
if (callback) {
callback.call(me);
}
});
}
} else {
logger.logall("[package-script] No valid configuration for 'install' function, see the docs for more information ");
}
} | [
"function",
"(",
"config",
",",
"init",
",",
"callback",
")",
"{",
"var",
"me",
"=",
"this",
";",
"if",
"(",
"init",
")",
"{",
"this",
".",
"init",
"(",
"init",
")",
";",
"}",
"logger",
".",
"log2file",
"(",
"\"\\n\\n************ Package Script ************************************* process id: \"",
"+",
"\\n",
")",
";",
"\\n",
"}"
]
| spawn additional command according to the config
@param config The configuration for the spawn
e.g. [{
admin: true, [optional (for now, linux support only)],
spawnopt: {cwd: '.'} [optional] (see child_process spawn docs)
command: 'npm',
args: ["--version"]
}]
@param init The initial configuration, can be set in separate method (see 'init')
@param callback The callback functionality | [
"spawn",
"additional",
"command",
"according",
"to",
"the",
"config"
]
| f0be6bdfc7b4e6689f9040ebe034407f907cabd5 | https://github.com/lastboy/package-script/blob/f0be6bdfc7b4e6689f9040ebe034407f907cabd5/pkgscript.js#L277-L303 | train |
|
eladnava/koa-mysql | wrapper.js | wrapQueryMethod | function wrapQueryMethod(fn, ctx) {
return function() {
// Obtain function arguments
var args = [].slice.call(arguments);
// Return a thunkified function that receives a done callback
return function(done) {
// Add a custom callback to provided args
args.push(function(err, result) {
// Query failed?
if (err) {
return done(err);
}
// Query succeeded
done(null, result);
});
// Execute the query
fn.apply(ctx, args);
};
};
} | javascript | function wrapQueryMethod(fn, ctx) {
return function() {
// Obtain function arguments
var args = [].slice.call(arguments);
// Return a thunkified function that receives a done callback
return function(done) {
// Add a custom callback to provided args
args.push(function(err, result) {
// Query failed?
if (err) {
return done(err);
}
// Query succeeded
done(null, result);
});
// Execute the query
fn.apply(ctx, args);
};
};
} | [
"function",
"wrapQueryMethod",
"(",
"fn",
",",
"ctx",
")",
"{",
"return",
"function",
"(",
")",
"{",
"var",
"args",
"=",
"[",
"]",
".",
"slice",
".",
"call",
"(",
"arguments",
")",
";",
"return",
"function",
"(",
"done",
")",
"{",
"args",
".",
"push",
"(",
"function",
"(",
"err",
",",
"result",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"done",
"(",
"err",
")",
";",
"}",
"done",
"(",
"null",
",",
"result",
")",
";",
"}",
")",
";",
"fn",
".",
"apply",
"(",
"ctx",
",",
"args",
")",
";",
"}",
";",
"}",
";",
"}"
]
| Thunkify query methods | [
"Thunkify",
"query",
"methods"
]
| 3d5aac1646ed5084466cebf689d412c81d8d12e2 | https://github.com/eladnava/koa-mysql/blob/3d5aac1646ed5084466cebf689d412c81d8d12e2/wrapper.js#L4-L26 | train |
eladnava/koa-mysql | wrapper.js | wrapConnection | function wrapConnection(conn) {
// Already wrapped this function?
if (conn._coWrapped) {
return conn;
}
// Set flag to avoid re-wrapping
conn._coWrapped = true;
// Functions to thunkify
var queryMethods = [
'query',
'execute'
];
// Traverse query methods list
queryMethods.forEach(function(name) {
// Thunkify the method
conn[name] = wrapQueryMethod(conn[name], conn);
});
// Return co-friendly connection
return conn;
} | javascript | function wrapConnection(conn) {
// Already wrapped this function?
if (conn._coWrapped) {
return conn;
}
// Set flag to avoid re-wrapping
conn._coWrapped = true;
// Functions to thunkify
var queryMethods = [
'query',
'execute'
];
// Traverse query methods list
queryMethods.forEach(function(name) {
// Thunkify the method
conn[name] = wrapQueryMethod(conn[name], conn);
});
// Return co-friendly connection
return conn;
} | [
"function",
"wrapConnection",
"(",
"conn",
")",
"{",
"if",
"(",
"conn",
".",
"_coWrapped",
")",
"{",
"return",
"conn",
";",
"}",
"conn",
".",
"_coWrapped",
"=",
"true",
";",
"var",
"queryMethods",
"=",
"[",
"'query'",
",",
"'execute'",
"]",
";",
"queryMethods",
".",
"forEach",
"(",
"function",
"(",
"name",
")",
"{",
"conn",
"[",
"name",
"]",
"=",
"wrapQueryMethod",
"(",
"conn",
"[",
"name",
"]",
",",
"conn",
")",
";",
"}",
")",
";",
"return",
"conn",
";",
"}"
]
| Wrap a MySQL connection object's query methods | [
"Wrap",
"a",
"MySQL",
"connection",
"object",
"s",
"query",
"methods"
]
| 3d5aac1646ed5084466cebf689d412c81d8d12e2 | https://github.com/eladnava/koa-mysql/blob/3d5aac1646ed5084466cebf689d412c81d8d12e2/wrapper.js#L29-L52 | train |
thlorenz/phe | phe.js | evaluateCardCodes | function evaluateCardCodes(codes) {
const len = codes.length
if (len === 5) return evaluate5cards.apply(null, codes)
if (len === 6) return evaluate6cards.apply(null, codes)
if (len === 7) return evaluate7cards.apply(null, codes)
throw new Error(`Can only evaluate 5, 6 or 7 cards, you gave me ${len}`)
} | javascript | function evaluateCardCodes(codes) {
const len = codes.length
if (len === 5) return evaluate5cards.apply(null, codes)
if (len === 6) return evaluate6cards.apply(null, codes)
if (len === 7) return evaluate7cards.apply(null, codes)
throw new Error(`Can only evaluate 5, 6 or 7 cards, you gave me ${len}`)
} | [
"function",
"evaluateCardCodes",
"(",
"codes",
")",
"{",
"const",
"len",
"=",
"codes",
".",
"length",
"if",
"(",
"len",
"===",
"5",
")",
"return",
"evaluate5cards",
".",
"apply",
"(",
"null",
",",
"codes",
")",
"if",
"(",
"len",
"===",
"6",
")",
"return",
"evaluate6cards",
".",
"apply",
"(",
"null",
",",
"codes",
")",
"if",
"(",
"len",
"===",
"7",
")",
"return",
"evaluate7cards",
".",
"apply",
"(",
"null",
",",
"codes",
")",
"throw",
"new",
"Error",
"(",
"`",
"${",
"len",
"}",
"`",
")",
"}"
]
| Evaluates the 5 - 7 card codes to arrive at a number representing the hand
strength, smaller is better.
@name evaluateCardCodes
@function
@param {Array.<Number>} cards the cards, i.e. `[ 49, 36, 4, 48, 41 ]`
@return {Number} the strength of the hand comprised by the card codes | [
"Evaluates",
"the",
"5",
"-",
"7",
"card",
"codes",
"to",
"arrive",
"at",
"a",
"number",
"representing",
"the",
"hand",
"strength",
"smaller",
"is",
"better",
"."
]
| 6cfea3703b050fda8dfc8d934ceeb4d3df331d6d | https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/phe.js#L41-L47 | train |
thlorenz/phe | phe.js | evaluateBoard | function evaluateBoard(board) {
if (typeof board !== 'string') throw new Error('board needs to be a string')
const cards = board.trim().split(/ /)
return evaluateCardsFast(cards)
} | javascript | function evaluateBoard(board) {
if (typeof board !== 'string') throw new Error('board needs to be a string')
const cards = board.trim().split(/ /)
return evaluateCardsFast(cards)
} | [
"function",
"evaluateBoard",
"(",
"board",
")",
"{",
"if",
"(",
"typeof",
"board",
"!==",
"'string'",
")",
"throw",
"new",
"Error",
"(",
"'board needs to be a string'",
")",
"const",
"cards",
"=",
"board",
".",
"trim",
"(",
")",
".",
"split",
"(",
"/",
" ",
"/",
")",
"return",
"evaluateCardsFast",
"(",
"cards",
")",
"}"
]
| Evaluates the given board of 5 to 7 cards provided as part of the board to
arrive at a number representing the hand strength, smaller is better.
@name evaluateBoard
@function
@param {String} board the board, i.e. `'Ah Ks Td 3c Ad'`
@return {Number} the strength of the hand comprised by the cards of the board | [
"Evaluates",
"the",
"given",
"board",
"of",
"5",
"to",
"7",
"cards",
"provided",
"as",
"part",
"of",
"the",
"board",
"to",
"arrive",
"at",
"a",
"number",
"representing",
"the",
"hand",
"strength",
"smaller",
"is",
"better",
"."
]
| 6cfea3703b050fda8dfc8d934ceeb4d3df331d6d | https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/phe.js#L83-L87 | train |
thlorenz/phe | phe.js | setCardCodes | function setCardCodes(set) {
const codeSet = new Set()
for (const v of set) codeSet.add(cardCode(v))
return codeSet
} | javascript | function setCardCodes(set) {
const codeSet = new Set()
for (const v of set) codeSet.add(cardCode(v))
return codeSet
} | [
"function",
"setCardCodes",
"(",
"set",
")",
"{",
"const",
"codeSet",
"=",
"new",
"Set",
"(",
")",
"for",
"(",
"const",
"v",
"of",
"set",
")",
"codeSet",
".",
"add",
"(",
"cardCode",
"(",
"v",
")",
")",
"return",
"codeSet",
"}"
]
| Converts a set of cards to card codes.
@name setCardCodes
@function
@param {Set.<String>} set card strings set, i.e. `Set({'Ah', 'Ks', 'Td', '3c, 'Ad'})`
@return {Set.<Number>} card code set | [
"Converts",
"a",
"set",
"of",
"cards",
"to",
"card",
"codes",
"."
]
| 6cfea3703b050fda8dfc8d934ceeb4d3df331d6d | https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/phe.js#L145-L149 | train |
thlorenz/phe | phe.js | setStringifyCardCodes | function setStringifyCardCodes(set) {
const stringSet = new Set()
for (const v of set) stringSet.add(stringifyCardCode(v))
return stringSet
} | javascript | function setStringifyCardCodes(set) {
const stringSet = new Set()
for (const v of set) stringSet.add(stringifyCardCode(v))
return stringSet
} | [
"function",
"setStringifyCardCodes",
"(",
"set",
")",
"{",
"const",
"stringSet",
"=",
"new",
"Set",
"(",
")",
"for",
"(",
"const",
"v",
"of",
"set",
")",
"stringSet",
".",
"add",
"(",
"stringifyCardCode",
"(",
"v",
")",
")",
"return",
"stringSet",
"}"
]
| Converts a set of card codes to their string representations.
@name setStringifyCardCodes
@function
@param {Set.<Number>} set card code set
@return {Set.<String>} set with string representations of the card codes,
i.e. `Set({'Ah', 'Ks', 'Td', '3c, 'Ad'})` | [
"Converts",
"a",
"set",
"of",
"card",
"codes",
"to",
"their",
"string",
"representations",
"."
]
| 6cfea3703b050fda8dfc8d934ceeb4d3df331d6d | https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/phe.js#L160-L164 | train |
thlorenz/phe | lib/hash.js | hash_binary | function hash_binary(q, len, k) {
var sum = 0
for (var i = 0; i < len; i++) {
if (q[i]) {
if (len - i - 1 >= k) {
sum += choose[len - i - 1][k]
}
k--
if (k === 0) break
}
}
return sum
} | javascript | function hash_binary(q, len, k) {
var sum = 0
for (var i = 0; i < len; i++) {
if (q[i]) {
if (len - i - 1 >= k) {
sum += choose[len - i - 1][k]
}
k--
if (k === 0) break
}
}
return sum
} | [
"function",
"hash_binary",
"(",
"q",
",",
"len",
",",
"k",
")",
"{",
"var",
"sum",
"=",
"0",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"len",
";",
"i",
"++",
")",
"{",
"if",
"(",
"q",
"[",
"i",
"]",
")",
"{",
"if",
"(",
"len",
"-",
"i",
"-",
"1",
">=",
"k",
")",
"{",
"sum",
"+=",
"choose",
"[",
"len",
"-",
"i",
"-",
"1",
"]",
"[",
"k",
"]",
"}",
"k",
"--",
"if",
"(",
"k",
"===",
"0",
")",
"break",
"}",
"}",
"return",
"sum",
"}"
]
| Calculates the binary hash using the choose table.
@name hash_binary
@function
@private
@param {Array} q array with an element for each rank, usually total of 13
@param {Number} len number of ranks, usually 13
@param {Number} k number of cards that make up the hand, 5, 6 or 7
@return {Number} hash sum | [
"Calculates",
"the",
"binary",
"hash",
"using",
"the",
"choose",
"table",
"."
]
| 6cfea3703b050fda8dfc8d934ceeb4d3df331d6d | https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/lib/hash.js#L43-L58 | train |
vihanb/babel-plugin-loop-optimizer | src/index.js | Handle_forEach | function Handle_forEach(t, path, aggressive_optimization, possible_undefined) {
var arrayName = path.scope.generateUidIdentifier("a"),
funcName = path.scope.generateUidIdentifier("f"),
iterator = path.scope.generateUidIdentifier("i"),
call = t.expressionStatement (
t.callExpression(funcName, [
t.memberExpression (
arrayName,
iterator,
true
),
iterator,
arrayName
])
)
path.getStatementParent().insertBefore ([
t.variableDeclaration("let", [
t.variableDeclarator (
arrayName,
path.node.callee.object
)
]),
t.variableDeclaration("let", [
t.variableDeclarator (
funcName,
path.node.arguments[0]
)
]),
aggressive_optimization
? t.forStatement (
t.variableDeclaration("let", [
t.variableDeclarator (
iterator,
t.memberExpression (
arrayName,
t.identifier("length")
)
)
]),
possible_undefined
? t.logicalExpression (
"&&",
t.updateExpression("--", iterator),
t.binaryExpression (
"!==",
t.memberExpression (
arrayName,
iterator,
true
),
t.identifier("undefined")
)
)
: t.updateExpression("--", iterator),
null,
call
)
: t.forStatement (
t.variableDeclaration("let", [
t.variableDeclarator (
iterator,
t.numericLiteral(0)
)
]),
possible_undefined
? t.logicalExpression (
"&&",
t.binaryExpression (
"<",
iterator,
t.memberExpression (
arrayName,
t.identifier("length")
)
),
t.binaryExpression (
"!==",
t.memberExpression (
arrayName,
iterator,
true
),
t.identifier("undefined")
)
)
: t.updateExpression("--", iterator),
t.updateExpression("++", iterator),
call
)
])
path.remove()
} | javascript | function Handle_forEach(t, path, aggressive_optimization, possible_undefined) {
var arrayName = path.scope.generateUidIdentifier("a"),
funcName = path.scope.generateUidIdentifier("f"),
iterator = path.scope.generateUidIdentifier("i"),
call = t.expressionStatement (
t.callExpression(funcName, [
t.memberExpression (
arrayName,
iterator,
true
),
iterator,
arrayName
])
)
path.getStatementParent().insertBefore ([
t.variableDeclaration("let", [
t.variableDeclarator (
arrayName,
path.node.callee.object
)
]),
t.variableDeclaration("let", [
t.variableDeclarator (
funcName,
path.node.arguments[0]
)
]),
aggressive_optimization
? t.forStatement (
t.variableDeclaration("let", [
t.variableDeclarator (
iterator,
t.memberExpression (
arrayName,
t.identifier("length")
)
)
]),
possible_undefined
? t.logicalExpression (
"&&",
t.updateExpression("--", iterator),
t.binaryExpression (
"!==",
t.memberExpression (
arrayName,
iterator,
true
),
t.identifier("undefined")
)
)
: t.updateExpression("--", iterator),
null,
call
)
: t.forStatement (
t.variableDeclaration("let", [
t.variableDeclarator (
iterator,
t.numericLiteral(0)
)
]),
possible_undefined
? t.logicalExpression (
"&&",
t.binaryExpression (
"<",
iterator,
t.memberExpression (
arrayName,
t.identifier("length")
)
),
t.binaryExpression (
"!==",
t.memberExpression (
arrayName,
iterator,
true
),
t.identifier("undefined")
)
)
: t.updateExpression("--", iterator),
t.updateExpression("++", iterator),
call
)
])
path.remove()
} | [
"function",
"Handle_forEach",
"(",
"t",
",",
"path",
",",
"aggressive_optimization",
",",
"possible_undefined",
")",
"{",
"var",
"arrayName",
"=",
"path",
".",
"scope",
".",
"generateUidIdentifier",
"(",
"\"a\"",
")",
",",
"funcName",
"=",
"path",
".",
"scope",
".",
"generateUidIdentifier",
"(",
"\"f\"",
")",
",",
"iterator",
"=",
"path",
".",
"scope",
".",
"generateUidIdentifier",
"(",
"\"i\"",
")",
",",
"call",
"=",
"t",
".",
"expressionStatement",
"(",
"t",
".",
"callExpression",
"(",
"funcName",
",",
"[",
"t",
".",
"memberExpression",
"(",
"arrayName",
",",
"iterator",
",",
"true",
")",
",",
"iterator",
",",
"arrayName",
"]",
")",
")",
"path",
".",
"getStatementParent",
"(",
")",
".",
"insertBefore",
"(",
"[",
"t",
".",
"variableDeclaration",
"(",
"\"let\"",
",",
"[",
"t",
".",
"variableDeclarator",
"(",
"arrayName",
",",
"path",
".",
"node",
".",
"callee",
".",
"object",
")",
"]",
")",
",",
"t",
".",
"variableDeclaration",
"(",
"\"let\"",
",",
"[",
"t",
".",
"variableDeclarator",
"(",
"funcName",
",",
"path",
".",
"node",
".",
"arguments",
"[",
"0",
"]",
")",
"]",
")",
",",
"aggressive_optimization",
"?",
"t",
".",
"forStatement",
"(",
"t",
".",
"variableDeclaration",
"(",
"\"let\"",
",",
"[",
"t",
".",
"variableDeclarator",
"(",
"iterator",
",",
"t",
".",
"memberExpression",
"(",
"arrayName",
",",
"t",
".",
"identifier",
"(",
"\"length\"",
")",
")",
")",
"]",
")",
",",
"possible_undefined",
"?",
"t",
".",
"logicalExpression",
"(",
"\"&&\"",
",",
"t",
".",
"updateExpression",
"(",
"\"--\"",
",",
"iterator",
")",
",",
"t",
".",
"binaryExpression",
"(",
"\"!==\"",
",",
"t",
".",
"memberExpression",
"(",
"arrayName",
",",
"iterator",
",",
"true",
")",
",",
"t",
".",
"identifier",
"(",
"\"undefined\"",
")",
")",
")",
":",
"t",
".",
"updateExpression",
"(",
"\"--\"",
",",
"iterator",
")",
",",
"null",
",",
"call",
")",
":",
"t",
".",
"forStatement",
"(",
"t",
".",
"variableDeclaration",
"(",
"\"let\"",
",",
"[",
"t",
".",
"variableDeclarator",
"(",
"iterator",
",",
"t",
".",
"numericLiteral",
"(",
"0",
")",
")",
"]",
")",
",",
"possible_undefined",
"?",
"t",
".",
"logicalExpression",
"(",
"\"&&\"",
",",
"t",
".",
"binaryExpression",
"(",
"\"<\"",
",",
"iterator",
",",
"t",
".",
"memberExpression",
"(",
"arrayName",
",",
"t",
".",
"identifier",
"(",
"\"length\"",
")",
")",
")",
",",
"t",
".",
"binaryExpression",
"(",
"\"!==\"",
",",
"t",
".",
"memberExpression",
"(",
"arrayName",
",",
"iterator",
",",
"true",
")",
",",
"t",
".",
"identifier",
"(",
"\"undefined\"",
")",
")",
")",
":",
"t",
".",
"updateExpression",
"(",
"\"--\"",
",",
"iterator",
")",
",",
"t",
".",
"updateExpression",
"(",
"\"++\"",
",",
"iterator",
")",
",",
"call",
")",
"]",
")",
"path",
".",
"remove",
"(",
")",
"}"
]
| NON-RETURNING | [
"NON",
"-",
"RETURNING"
]
| a87652cb3b939ee04acc28a5c13f72458a41fef1 | https://github.com/vihanb/babel-plugin-loop-optimizer/blob/a87652cb3b939ee04acc28a5c13f72458a41fef1/src/index.js#L2-L97 | train |
thlorenz/phe | lib/hand-code.js | stringifyCardCode | function stringifyCardCode(code) {
const rank = code & 0b111100
const suit = code & 0b000011
return rankCodeStrings[rank] + suitCodeStrings[suit]
} | javascript | function stringifyCardCode(code) {
const rank = code & 0b111100
const suit = code & 0b000011
return rankCodeStrings[rank] + suitCodeStrings[suit]
} | [
"function",
"stringifyCardCode",
"(",
"code",
")",
"{",
"const",
"rank",
"=",
"code",
"&",
"0b111100",
"const",
"suit",
"=",
"code",
"&",
"0b000011",
"return",
"rankCodeStrings",
"[",
"rank",
"]",
"+",
"suitCodeStrings",
"[",
"suit",
"]",
"}"
]
| Converts the given card code into a string presentation.
@name stringifyCardCode
@function
@param {Number} code the card code, i.e. obtained via `cardCode(rank, suit)`.
@return {String} a string representation of the card in question, i.e. `Ah` | [
"Converts",
"the",
"given",
"card",
"code",
"into",
"a",
"string",
"presentation",
"."
]
| 6cfea3703b050fda8dfc8d934ceeb4d3df331d6d | https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/lib/hand-code.js#L97-L101 | train |
thlorenz/phe | lib/hand-rank.js | handRank | function handRank(val) {
if (val > 6185) return HIGH_CARD // 1277 high card
if (val > 3325) return ONE_PAIR // 2860 one pair
if (val > 2467) return TWO_PAIR // 858 two pair
if (val > 1609) return THREE_OF_A_KIND // 858 three-kind
if (val > 1599) return STRAIGHT // 10 straights
if (val > 322) return FLUSH // 1277 flushes
if (val > 166) return FULL_HOUSE // 156 full house
if (val > 10) return FOUR_OF_A_KIND // 156 four-kind
return STRAIGHT_FLUSH // 10 straight-flushes
} | javascript | function handRank(val) {
if (val > 6185) return HIGH_CARD // 1277 high card
if (val > 3325) return ONE_PAIR // 2860 one pair
if (val > 2467) return TWO_PAIR // 858 two pair
if (val > 1609) return THREE_OF_A_KIND // 858 three-kind
if (val > 1599) return STRAIGHT // 10 straights
if (val > 322) return FLUSH // 1277 flushes
if (val > 166) return FULL_HOUSE // 156 full house
if (val > 10) return FOUR_OF_A_KIND // 156 four-kind
return STRAIGHT_FLUSH // 10 straight-flushes
} | [
"function",
"handRank",
"(",
"val",
")",
"{",
"if",
"(",
"val",
">",
"6185",
")",
"return",
"HIGH_CARD",
"if",
"(",
"val",
">",
"3325",
")",
"return",
"ONE_PAIR",
"if",
"(",
"val",
">",
"2467",
")",
"return",
"TWO_PAIR",
"if",
"(",
"val",
">",
"1609",
")",
"return",
"THREE_OF_A_KIND",
"if",
"(",
"val",
">",
"1599",
")",
"return",
"STRAIGHT",
"if",
"(",
"val",
">",
"322",
")",
"return",
"FLUSH",
"if",
"(",
"val",
">",
"166",
")",
"return",
"FULL_HOUSE",
"if",
"(",
"val",
">",
"10",
")",
"return",
"FOUR_OF_A_KIND",
"return",
"STRAIGHT_FLUSH",
"}"
]
| Converts a hand strength number into a hand rank number
`0 - 8` for `STRAIGHT_FLUSH - HIGH_CARD`.
@name handRank
@function
@param {Number} val hand strength (result of an `evaluate` function)
@return {Number} the hand rank | [
"Converts",
"a",
"hand",
"strength",
"number",
"into",
"a",
"hand",
"rank",
"number",
"0",
"-",
"8",
"for",
"STRAIGHT_FLUSH",
"-",
"HIGH_CARD",
"."
]
| 6cfea3703b050fda8dfc8d934ceeb4d3df331d6d | https://github.com/thlorenz/phe/blob/6cfea3703b050fda8dfc8d934ceeb4d3df331d6d/lib/hand-rank.js#L43-L53 | train |
senecajs/seneca-web-adapter-express | seneca-web-adapter-express.js | handleRoute | function handleRoute(seneca, options, request, reply, route, next) {
if (options.parseBody) {
return ReadBody(request, finish)
}
finish(null, request.body || {})
// Express requires a body parser to work in production
// This util creates a body obj without neededing a parser
// but doesn't impact loading one in.
function finish(err, body) {
if (err) {
return next(err)
}
// This is what the seneca handler will get
// Note! request$ and response$ will be stripped
// if the message is sent over transport.
const payload = {
request$: request,
response$: reply,
args: {
body: body,
route: route,
params: request.params,
query: request.query,
user: request.user || null
}
}
// Call the seneca action specified in the config
seneca.act(route.pattern, payload, (err, response) => {
if (err) {
return next(err)
}
// Redirect or reply depending on config.
if (route.redirect) {
return reply.redirect(route.redirect)
}
if (route.autoreply) {
return reply.send(response)
}
})
}
} | javascript | function handleRoute(seneca, options, request, reply, route, next) {
if (options.parseBody) {
return ReadBody(request, finish)
}
finish(null, request.body || {})
// Express requires a body parser to work in production
// This util creates a body obj without neededing a parser
// but doesn't impact loading one in.
function finish(err, body) {
if (err) {
return next(err)
}
// This is what the seneca handler will get
// Note! request$ and response$ will be stripped
// if the message is sent over transport.
const payload = {
request$: request,
response$: reply,
args: {
body: body,
route: route,
params: request.params,
query: request.query,
user: request.user || null
}
}
// Call the seneca action specified in the config
seneca.act(route.pattern, payload, (err, response) => {
if (err) {
return next(err)
}
// Redirect or reply depending on config.
if (route.redirect) {
return reply.redirect(route.redirect)
}
if (route.autoreply) {
return reply.send(response)
}
})
}
} | [
"function",
"handleRoute",
"(",
"seneca",
",",
"options",
",",
"request",
",",
"reply",
",",
"route",
",",
"next",
")",
"{",
"if",
"(",
"options",
".",
"parseBody",
")",
"{",
"return",
"ReadBody",
"(",
"request",
",",
"finish",
")",
"}",
"finish",
"(",
"null",
",",
"request",
".",
"body",
"||",
"{",
"}",
")",
"function",
"finish",
"(",
"err",
",",
"body",
")",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
"}",
"const",
"payload",
"=",
"{",
"request$",
":",
"request",
",",
"response$",
":",
"reply",
",",
"args",
":",
"{",
"body",
":",
"body",
",",
"route",
":",
"route",
",",
"params",
":",
"request",
".",
"params",
",",
"query",
":",
"request",
".",
"query",
",",
"user",
":",
"request",
".",
"user",
"||",
"null",
"}",
"}",
"seneca",
".",
"act",
"(",
"route",
".",
"pattern",
",",
"payload",
",",
"(",
"err",
",",
"response",
")",
"=>",
"{",
"if",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
"}",
"if",
"(",
"route",
".",
"redirect",
")",
"{",
"return",
"reply",
".",
"redirect",
"(",
"route",
".",
"redirect",
")",
"}",
"if",
"(",
"route",
".",
"autoreply",
")",
"{",
"return",
"reply",
".",
"send",
"(",
"response",
")",
"}",
"}",
")",
"}",
"}"
]
| All routes ultimately get handled by this handler if they have not already be redirected or responded. | [
"All",
"routes",
"ultimately",
"get",
"handled",
"by",
"this",
"handler",
"if",
"they",
"have",
"not",
"already",
"be",
"redirected",
"or",
"responded",
"."
]
| 9b43f4c80b3310f2494750c8af200b768bd47bdf | https://github.com/senecajs/seneca-web-adapter-express/blob/9b43f4c80b3310f2494750c8af200b768bd47bdf/seneca-web-adapter-express.js#L65-L109 | train |
senecajs/seneca-web-adapter-express | seneca-web-adapter-express.js | unsecuredRoute | function unsecuredRoute(seneca, options, context, method, middleware, route) {
const routeArgs = [route.path].concat(middleware).concat([
(request, reply, next) => {
handleRoute(seneca, options, request, reply, route, next)
}
])
context[method].apply(context, routeArgs)
} | javascript | function unsecuredRoute(seneca, options, context, method, middleware, route) {
const routeArgs = [route.path].concat(middleware).concat([
(request, reply, next) => {
handleRoute(seneca, options, request, reply, route, next)
}
])
context[method].apply(context, routeArgs)
} | [
"function",
"unsecuredRoute",
"(",
"seneca",
",",
"options",
",",
"context",
",",
"method",
",",
"middleware",
",",
"route",
")",
"{",
"const",
"routeArgs",
"=",
"[",
"route",
".",
"path",
"]",
".",
"concat",
"(",
"middleware",
")",
".",
"concat",
"(",
"[",
"(",
"request",
",",
"reply",
",",
"next",
")",
"=>",
"{",
"handleRoute",
"(",
"seneca",
",",
"options",
",",
"request",
",",
"reply",
",",
"route",
",",
"next",
")",
"}",
"]",
")",
"context",
"[",
"method",
"]",
".",
"apply",
"(",
"context",
",",
"routeArgs",
")",
"}"
]
| Unsecured routes just call the handler directly, no magic. | [
"Unsecured",
"routes",
"just",
"call",
"the",
"handler",
"directly",
"no",
"magic",
"."
]
| 9b43f4c80b3310f2494750c8af200b768bd47bdf | https://github.com/senecajs/seneca-web-adapter-express/blob/9b43f4c80b3310f2494750c8af200b768bd47bdf/seneca-web-adapter-express.js#L112-L120 | train |
senecajs/seneca-web-adapter-express | seneca-web-adapter-express.js | authRoute | function authRoute(seneca, options, context, method, route, middleware, auth) {
const opts = {
failureRedirect: route.auth.fail,
successRedirect: route.auth.pass
}
const routeArgs = [route.path]
.concat([auth.authenticate(route.auth.strategy, opts)])
.concat(middleware)
.concat([
(request, reply, next) => {
handleRoute(seneca, options, request, reply, route, next)
}
])
context[method].apply(context, routeArgs)
} | javascript | function authRoute(seneca, options, context, method, route, middleware, auth) {
const opts = {
failureRedirect: route.auth.fail,
successRedirect: route.auth.pass
}
const routeArgs = [route.path]
.concat([auth.authenticate(route.auth.strategy, opts)])
.concat(middleware)
.concat([
(request, reply, next) => {
handleRoute(seneca, options, request, reply, route, next)
}
])
context[method].apply(context, routeArgs)
} | [
"function",
"authRoute",
"(",
"seneca",
",",
"options",
",",
"context",
",",
"method",
",",
"route",
",",
"middleware",
",",
"auth",
")",
"{",
"const",
"opts",
"=",
"{",
"failureRedirect",
":",
"route",
".",
"auth",
".",
"fail",
",",
"successRedirect",
":",
"route",
".",
"auth",
".",
"pass",
"}",
"const",
"routeArgs",
"=",
"[",
"route",
".",
"path",
"]",
".",
"concat",
"(",
"[",
"auth",
".",
"authenticate",
"(",
"route",
".",
"auth",
".",
"strategy",
",",
"opts",
")",
"]",
")",
".",
"concat",
"(",
"middleware",
")",
".",
"concat",
"(",
"[",
"(",
"request",
",",
"reply",
",",
"next",
")",
"=>",
"{",
"handleRoute",
"(",
"seneca",
",",
"options",
",",
"request",
",",
"reply",
",",
"route",
",",
"next",
")",
"}",
"]",
")",
"context",
"[",
"method",
"]",
".",
"apply",
"(",
"context",
",",
"routeArgs",
")",
"}"
]
| Auth routes call passport.authenticate and can and do redirect depending on pass or failure. Generally this means you don't need a seneca handler set as the redirects happend instead. | [
"Auth",
"routes",
"call",
"passport",
".",
"authenticate",
"and",
"can",
"and",
"do",
"redirect",
"depending",
"on",
"pass",
"or",
"failure",
".",
"Generally",
"this",
"means",
"you",
"don",
"t",
"need",
"a",
"seneca",
"handler",
"set",
"as",
"the",
"redirects",
"happend",
"instead",
"."
]
| 9b43f4c80b3310f2494750c8af200b768bd47bdf | https://github.com/senecajs/seneca-web-adapter-express/blob/9b43f4c80b3310f2494750c8af200b768bd47bdf/seneca-web-adapter-express.js#L125-L141 | train |
vangj/jsbayes | jsbayes.js | initCpt | function initCpt(numValues) {
var cpt = [];
var sum = 0;
for(var i=0; i < numValues; i++) {
cpt[i] = Math.random();
sum += cpt[i];
}
for(var i=0; i < numValues; i++) {
cpt[i] = cpt[i] / sum;
}
return cpt;
} | javascript | function initCpt(numValues) {
var cpt = [];
var sum = 0;
for(var i=0; i < numValues; i++) {
cpt[i] = Math.random();
sum += cpt[i];
}
for(var i=0; i < numValues; i++) {
cpt[i] = cpt[i] / sum;
}
return cpt;
} | [
"function",
"initCpt",
"(",
"numValues",
")",
"{",
"var",
"cpt",
"=",
"[",
"]",
";",
"var",
"sum",
"=",
"0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"numValues",
";",
"i",
"++",
")",
"{",
"cpt",
"[",
"i",
"]",
"=",
"Math",
".",
"random",
"(",
")",
";",
"sum",
"+=",
"cpt",
"[",
"i",
"]",
";",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"numValues",
";",
"i",
"++",
")",
"{",
"cpt",
"[",
"i",
"]",
"=",
"cpt",
"[",
"i",
"]",
"/",
"sum",
";",
"}",
"return",
"cpt",
";",
"}"
]
| Initializes a conditional probability table.
@param {Number} numValues Number of values.
@returns {Array} Array of doubles that sum to 1.0. | [
"Initializes",
"a",
"conditional",
"probability",
"table",
"."
]
| f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52 | https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L9-L20 | train |
vangj/jsbayes | jsbayes.js | initCptWithParents | function initCptWithParents(values, parents, paIndex) {
if(parents && parents.length > 0) {
if(parents.length === 1 || paIndex === parents.length - 1) {
var idx = parents.length === 1 ? 0 : paIndex;
var numPaVals = parents[idx].values.length;
var cpts = [];
for(var i=0; i < numPaVals; i++) {
var cpt = initCpt(values.length);
cpts.push(cpt);
}
return cpts;
} else {
var cpts = [];
var numPaVals = parents[paIndex].values.length;
for(var i=0; i < numPaVals; i++) {
var cpt = initCptWithParents(values, parents, paIndex+1);
cpts.push(cpt);
}
return cpts;
}
} else {
return initCpt(values.length);
}
} | javascript | function initCptWithParents(values, parents, paIndex) {
if(parents && parents.length > 0) {
if(parents.length === 1 || paIndex === parents.length - 1) {
var idx = parents.length === 1 ? 0 : paIndex;
var numPaVals = parents[idx].values.length;
var cpts = [];
for(var i=0; i < numPaVals; i++) {
var cpt = initCpt(values.length);
cpts.push(cpt);
}
return cpts;
} else {
var cpts = [];
var numPaVals = parents[paIndex].values.length;
for(var i=0; i < numPaVals; i++) {
var cpt = initCptWithParents(values, parents, paIndex+1);
cpts.push(cpt);
}
return cpts;
}
} else {
return initCpt(values.length);
}
} | [
"function",
"initCptWithParents",
"(",
"values",
",",
"parents",
",",
"paIndex",
")",
"{",
"if",
"(",
"parents",
"&&",
"parents",
".",
"length",
">",
"0",
")",
"{",
"if",
"(",
"parents",
".",
"length",
"===",
"1",
"||",
"paIndex",
"===",
"parents",
".",
"length",
"-",
"1",
")",
"{",
"var",
"idx",
"=",
"parents",
".",
"length",
"===",
"1",
"?",
"0",
":",
"paIndex",
";",
"var",
"numPaVals",
"=",
"parents",
"[",
"idx",
"]",
".",
"values",
".",
"length",
";",
"var",
"cpts",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"numPaVals",
";",
"i",
"++",
")",
"{",
"var",
"cpt",
"=",
"initCpt",
"(",
"values",
".",
"length",
")",
";",
"cpts",
".",
"push",
"(",
"cpt",
")",
";",
"}",
"return",
"cpts",
";",
"}",
"else",
"{",
"var",
"cpts",
"=",
"[",
"]",
";",
"var",
"numPaVals",
"=",
"parents",
"[",
"paIndex",
"]",
".",
"values",
".",
"length",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"numPaVals",
";",
"i",
"++",
")",
"{",
"var",
"cpt",
"=",
"initCptWithParents",
"(",
"values",
",",
"parents",
",",
"paIndex",
"+",
"1",
")",
";",
"cpts",
".",
"push",
"(",
"cpt",
")",
";",
"}",
"return",
"cpts",
";",
"}",
"}",
"else",
"{",
"return",
"initCpt",
"(",
"values",
".",
"length",
")",
";",
"}",
"}"
]
| Initializes a CPT with fake and normalized values using recursion.
@param {Array} values Values of variables (array of values).
@param {Array} parents Array of JSON nodes that are parents of the variable.
@param {Number} paIndex The current parent index.
@returns {Array} An array of nested arrays representing the CPT. | [
"Initializes",
"a",
"CPT",
"with",
"fake",
"and",
"normalized",
"values",
"using",
"recursion",
"."
]
| f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52 | https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L29-L52 | train |
vangj/jsbayes | jsbayes.js | async | function async(f, args) {
return new Promise(
function(resolve, reject) {
try {
var r = f.apply(undefined, args);
resolve(r);
} catch(e) {
reject(e);
}
}
);
} | javascript | function async(f, args) {
return new Promise(
function(resolve, reject) {
try {
var r = f.apply(undefined, args);
resolve(r);
} catch(e) {
reject(e);
}
}
);
} | [
"function",
"async",
"(",
"f",
",",
"args",
")",
"{",
"return",
"new",
"Promise",
"(",
"function",
"(",
"resolve",
",",
"reject",
")",
"{",
"try",
"{",
"var",
"r",
"=",
"f",
".",
"apply",
"(",
"undefined",
",",
"args",
")",
";",
"resolve",
"(",
"r",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"reject",
"(",
"e",
")",
";",
"}",
"}",
")",
";",
"}"
]
| Creates a Promise.
@param {Object} f Function.
@param {Array} args List of arguments.
@returns {Promise} Promise. | [
"Creates",
"a",
"Promise",
"."
]
| f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52 | https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L60-L71 | train |
vangj/jsbayes | jsbayes.js | isArrayOfArray | function isArrayOfArray(o) {
if(isArray(o)) {
if(o.length > 0) {
if(isArray(o[0])) {
return true;
}
}
}
return false;
} | javascript | function isArrayOfArray(o) {
if(isArray(o)) {
if(o.length > 0) {
if(isArray(o[0])) {
return true;
}
}
}
return false;
} | [
"function",
"isArrayOfArray",
"(",
"o",
")",
"{",
"if",
"(",
"isArray",
"(",
"o",
")",
")",
"{",
"if",
"(",
"o",
".",
"length",
">",
"0",
")",
"{",
"if",
"(",
"isArray",
"(",
"o",
"[",
"0",
"]",
")",
")",
"{",
"return",
"true",
";",
"}",
"}",
"}",
"return",
"false",
";",
"}"
]
| Checks if an object is an array of arrays.
@param {*} o Object.
@returns {Boolean} A boolean to indicate if the object is array of arrays. | [
"Checks",
"if",
"an",
"object",
"is",
"an",
"array",
"of",
"arrays",
"."
]
| f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52 | https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L87-L96 | train |
vangj/jsbayes | jsbayes.js | setNodeCptProbs | function setNodeCptProbs(cpt, probs, index) {
if(!isArrayOfArray(cpt)) {
for(var i=0; i < cpt.length; i++) {
cpt[i] = probs[index][i];
}
var nextIndex = index + 1;
return nextIndex;
} else {
var next = index;
for(var i=0; i < cpt.length; i++) {
next = setNodeCptProbs(cpt[i], probs, next);
}
return next;
}
} | javascript | function setNodeCptProbs(cpt, probs, index) {
if(!isArrayOfArray(cpt)) {
for(var i=0; i < cpt.length; i++) {
cpt[i] = probs[index][i];
}
var nextIndex = index + 1;
return nextIndex;
} else {
var next = index;
for(var i=0; i < cpt.length; i++) {
next = setNodeCptProbs(cpt[i], probs, next);
}
return next;
}
} | [
"function",
"setNodeCptProbs",
"(",
"cpt",
",",
"probs",
",",
"index",
")",
"{",
"if",
"(",
"!",
"isArrayOfArray",
"(",
"cpt",
")",
")",
"{",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"cpt",
".",
"length",
";",
"i",
"++",
")",
"{",
"cpt",
"[",
"i",
"]",
"=",
"probs",
"[",
"index",
"]",
"[",
"i",
"]",
";",
"}",
"var",
"nextIndex",
"=",
"index",
"+",
"1",
";",
"return",
"nextIndex",
";",
"}",
"else",
"{",
"var",
"next",
"=",
"index",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"cpt",
".",
"length",
";",
"i",
"++",
")",
"{",
"next",
"=",
"setNodeCptProbs",
"(",
"cpt",
"[",
"i",
"]",
",",
"probs",
",",
"next",
")",
";",
"}",
"return",
"next",
";",
"}",
"}"
]
| Sets the CPT entries to the specified probabilities.
@param {Array} cpt Array of nested arrays representing a CPT.
@param {Array} probs Array of arrays of probabilities representing a CPT.
@param {Number} index The current index.
@returns {Number} The next index. | [
"Sets",
"the",
"CPT",
"entries",
"to",
"the",
"specified",
"probabilities",
"."
]
| f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52 | https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L105-L119 | train |
vangj/jsbayes | jsbayes.js | initNodeCpt | function initNodeCpt(values, parents, probs) {
var cpt = initCptWithParents(values, parents, 0);
setNodeCptProbs(cpt, probs, 0);
return cpt;
} | javascript | function initNodeCpt(values, parents, probs) {
var cpt = initCptWithParents(values, parents, 0);
setNodeCptProbs(cpt, probs, 0);
return cpt;
} | [
"function",
"initNodeCpt",
"(",
"values",
",",
"parents",
",",
"probs",
")",
"{",
"var",
"cpt",
"=",
"initCptWithParents",
"(",
"values",
",",
"parents",
",",
"0",
")",
";",
"setNodeCptProbs",
"(",
"cpt",
",",
"probs",
",",
"0",
")",
";",
"return",
"cpt",
";",
"}"
]
| Initializes a node's CPT.
@param {Array} values Array of values.
@param {Array} parents Array of parents.
@param {Array} probs Array of arrays of probabilities.
@returns {Array} Array of nested arrays representing a CPT. | [
"Initializes",
"a",
"node",
"s",
"CPT",
"."
]
| f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52 | https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L128-L132 | train |
vangj/jsbayes | jsbayes.js | normalizeProbs | function normalizeProbs(arr) {
var probs = [];
var sum = 0.0;
for (var i=0; i < arr.length; i++) {
probs[i] = arr[i] + 0.001
sum += probs[i]
}
for (var i=0; i < arr.length; i++) {
probs[i] = probs[i] / sum;
}
return probs;
} | javascript | function normalizeProbs(arr) {
var probs = [];
var sum = 0.0;
for (var i=0; i < arr.length; i++) {
probs[i] = arr[i] + 0.001
sum += probs[i]
}
for (var i=0; i < arr.length; i++) {
probs[i] = probs[i] / sum;
}
return probs;
} | [
"function",
"normalizeProbs",
"(",
"arr",
")",
"{",
"var",
"probs",
"=",
"[",
"]",
";",
"var",
"sum",
"=",
"0.0",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
";",
"i",
"++",
")",
"{",
"probs",
"[",
"i",
"]",
"=",
"arr",
"[",
"i",
"]",
"+",
"0.001",
"sum",
"+=",
"probs",
"[",
"i",
"]",
"}",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"arr",
".",
"length",
";",
"i",
"++",
")",
"{",
"probs",
"[",
"i",
"]",
"=",
"probs",
"[",
"i",
"]",
"/",
"sum",
";",
"}",
"return",
"probs",
";",
"}"
]
| Normalizes an array of values such that the elements sum to 1.0. Note that
0.001 is added to every value to avoid 0.0 probabilities. This adjustment
helps with visualization downstream.
@param {Array} arr Array of probabilities.
@returns {Array} Normalized probailities. | [
"Normalizes",
"an",
"array",
"of",
"values",
"such",
"that",
"the",
"elements",
"sum",
"to",
"1",
".",
"0",
".",
"Note",
"that",
"0",
".",
"001",
"is",
"added",
"to",
"every",
"value",
"to",
"avoid",
"0",
".",
"0",
"probabilities",
".",
"This",
"adjustment",
"helps",
"with",
"visualization",
"downstream",
"."
]
| f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52 | https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L141-L152 | train |
vangj/jsbayes | jsbayes.js | normalizeCpts | function normalizeCpts(cpts) {
var probs = []
for (var i=0; i < cpts.length; i++) {
probs.push(normalizeProbs(cpts[i]));
}
return probs;
} | javascript | function normalizeCpts(cpts) {
var probs = []
for (var i=0; i < cpts.length; i++) {
probs.push(normalizeProbs(cpts[i]));
}
return probs;
} | [
"function",
"normalizeCpts",
"(",
"cpts",
")",
"{",
"var",
"probs",
"=",
"[",
"]",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"cpts",
".",
"length",
";",
"i",
"++",
")",
"{",
"probs",
".",
"push",
"(",
"normalizeProbs",
"(",
"cpts",
"[",
"i",
"]",
")",
")",
";",
"}",
"return",
"probs",
";",
"}"
]
| Normalizes a CPT.
@param {Array} cpts Array of arrays (matrix) representing a CPT.
@returns {Array} Normalized CPT. | [
"Normalizes",
"a",
"CPT",
"."
]
| f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52 | https://github.com/vangj/jsbayes/blob/f8d1cddc0228a3d55c9cbd3ca0555c8b43f90d52/jsbayes.js#L159-L165 | train |
Alex-D/check-disk-space | index.js | check | function check(cmd, filter, mapping, coefficient = 1) {
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout) => {
if (error) {
reject(error)
}
try {
resolve(mapOutput(stdout, filter, mapping, coefficient))
} catch (err) {
reject(err)
}
})
})
} | javascript | function check(cmd, filter, mapping, coefficient = 1) {
return new Promise((resolve, reject) => {
exec(cmd, (error, stdout) => {
if (error) {
reject(error)
}
try {
resolve(mapOutput(stdout, filter, mapping, coefficient))
} catch (err) {
reject(err)
}
})
})
} | [
"function",
"check",
"(",
"cmd",
",",
"filter",
",",
"mapping",
",",
"coefficient",
"=",
"1",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"exec",
"(",
"cmd",
",",
"(",
"error",
",",
"stdout",
")",
"=>",
"{",
"if",
"(",
"error",
")",
"{",
"reject",
"(",
"error",
")",
"}",
"try",
"{",
"resolve",
"(",
"mapOutput",
"(",
"stdout",
",",
"filter",
",",
"mapping",
",",
"coefficient",
")",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"reject",
"(",
"err",
")",
"}",
"}",
")",
"}",
")",
"}"
]
| Run the command and do common things between win32 and unix
@param {String} cmd - The command to execute
@param {Function} filter - To filter drives (only used for win32)
@param {Object} mapping - Map between column index and normalized column name
@param {Number} coefficient - The size coefficient to get bytes instead of kB
@return {Promise} - | [
"Run",
"the",
"command",
"and",
"do",
"common",
"things",
"between",
"win32",
"and",
"unix"
]
| 510b32e2cab4b27a21cb523fea4b45be189ea348 | https://github.com/Alex-D/check-disk-space/blob/510b32e2cab4b27a21cb523fea4b45be189ea348/index.js#L60-L74 | train |
Alex-D/check-disk-space | index.js | checkWin32 | function checkWin32(directoryPath) {
if (directoryPath.charAt(1) !== ':') {
return new Promise((resolve, reject) => {
reject(new InvalidPathError(`The following path is invalid (should be X:\\...): ${directoryPath}`))
})
}
return check(
`wmic logicaldisk get size,freespace,caption`,
driveData => {
// Only get the drive which match the path
const driveLetter = driveData[0]
return directoryPath.startsWith(driveLetter)
},
{
diskPath: 0,
free: 1,
size: 2
}
)
} | javascript | function checkWin32(directoryPath) {
if (directoryPath.charAt(1) !== ':') {
return new Promise((resolve, reject) => {
reject(new InvalidPathError(`The following path is invalid (should be X:\\...): ${directoryPath}`))
})
}
return check(
`wmic logicaldisk get size,freespace,caption`,
driveData => {
// Only get the drive which match the path
const driveLetter = driveData[0]
return directoryPath.startsWith(driveLetter)
},
{
diskPath: 0,
free: 1,
size: 2
}
)
} | [
"function",
"checkWin32",
"(",
"directoryPath",
")",
"{",
"if",
"(",
"directoryPath",
".",
"charAt",
"(",
"1",
")",
"!==",
"':'",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"reject",
"(",
"new",
"InvalidPathError",
"(",
"`",
"\\\\",
"${",
"directoryPath",
"}",
"`",
")",
")",
"}",
")",
"}",
"return",
"check",
"(",
"`",
"`",
",",
"driveData",
"=>",
"{",
"const",
"driveLetter",
"=",
"driveData",
"[",
"0",
"]",
"return",
"directoryPath",
".",
"startsWith",
"(",
"driveLetter",
")",
"}",
",",
"{",
"diskPath",
":",
"0",
",",
"free",
":",
"1",
",",
"size",
":",
"2",
"}",
")",
"}"
]
| Build the check call for win32
@param {String} directoryPath - The file/folder path from where we want to know disk space
@return {Promise} - | [
"Build",
"the",
"check",
"call",
"for",
"win32"
]
| 510b32e2cab4b27a21cb523fea4b45be189ea348 | https://github.com/Alex-D/check-disk-space/blob/510b32e2cab4b27a21cb523fea4b45be189ea348/index.js#L82-L102 | train |
Alex-D/check-disk-space | index.js | checkUnix | function checkUnix(directoryPath) {
if (!path.normalize(directoryPath).startsWith(path.sep)) {
return new Promise((resolve, reject) => {
reject(new InvalidPathError(`The following path is invalid (should start by ${path.sep}): ${directoryPath}`))
})
}
return check(
`df -Pk "${module.exports.getFirstExistingParentPath(directoryPath)}"`,
() => true, // We should only get one line, so we did not need to filter
{
diskPath: 5,
free: 3,
size: 1
},
1024 // We get sizes in kB, we need to convert that to bytes
)
} | javascript | function checkUnix(directoryPath) {
if (!path.normalize(directoryPath).startsWith(path.sep)) {
return new Promise((resolve, reject) => {
reject(new InvalidPathError(`The following path is invalid (should start by ${path.sep}): ${directoryPath}`))
})
}
return check(
`df -Pk "${module.exports.getFirstExistingParentPath(directoryPath)}"`,
() => true, // We should only get one line, so we did not need to filter
{
diskPath: 5,
free: 3,
size: 1
},
1024 // We get sizes in kB, we need to convert that to bytes
)
} | [
"function",
"checkUnix",
"(",
"directoryPath",
")",
"{",
"if",
"(",
"!",
"path",
".",
"normalize",
"(",
"directoryPath",
")",
".",
"startsWith",
"(",
"path",
".",
"sep",
")",
")",
"{",
"return",
"new",
"Promise",
"(",
"(",
"resolve",
",",
"reject",
")",
"=>",
"{",
"reject",
"(",
"new",
"InvalidPathError",
"(",
"`",
"${",
"path",
".",
"sep",
"}",
"${",
"directoryPath",
"}",
"`",
")",
")",
"}",
")",
"}",
"return",
"check",
"(",
"`",
"${",
"module",
".",
"exports",
".",
"getFirstExistingParentPath",
"(",
"directoryPath",
")",
"}",
"`",
",",
"(",
")",
"=>",
"true",
",",
"{",
"diskPath",
":",
"5",
",",
"free",
":",
"3",
",",
"size",
":",
"1",
"}",
",",
"1024",
")",
"}"
]
| Build the check call for unix
@param {String} directoryPath - The file/folder path from where we want to know disk space
@return {Promise} - | [
"Build",
"the",
"check",
"call",
"for",
"unix"
]
| 510b32e2cab4b27a21cb523fea4b45be189ea348 | https://github.com/Alex-D/check-disk-space/blob/510b32e2cab4b27a21cb523fea4b45be189ea348/index.js#L110-L127 | train |
RemiAWE/ng-flat-datepicker | dist/ng-flat-datepicker.js | init | function init() {
element.wrap('<div class="ng-flat-datepicker-wrapper"></div>');
$compile(template)(scope);
element.after(template);
if (angular.isDefined(ngModel.$modelValue) && moment.isDate(ngModel.$modelValue)) {
scope.calendarCursor = ngModel.$modelValue;
}
} | javascript | function init() {
element.wrap('<div class="ng-flat-datepicker-wrapper"></div>');
$compile(template)(scope);
element.after(template);
if (angular.isDefined(ngModel.$modelValue) && moment.isDate(ngModel.$modelValue)) {
scope.calendarCursor = ngModel.$modelValue;
}
} | [
"function",
"init",
"(",
")",
"{",
"element",
".",
"wrap",
"(",
"'<div class=\"ng-flat-datepicker-wrapper\"></div>'",
")",
";",
"$compile",
"(",
"template",
")",
"(",
"scope",
")",
";",
"element",
".",
"after",
"(",
"template",
")",
";",
"if",
"(",
"angular",
".",
"isDefined",
"(",
"ngModel",
".",
"$modelValue",
")",
"&&",
"moment",
".",
"isDate",
"(",
"ngModel",
".",
"$modelValue",
")",
")",
"{",
"scope",
".",
"calendarCursor",
"=",
"ngModel",
".",
"$modelValue",
";",
"}",
"}"
]
| Init the directive
@return {} | [
"Init",
"the",
"directive"
]
| a349e5da015c714b01ca84d087d760fe31e473b5 | https://github.com/RemiAWE/ng-flat-datepicker/blob/a349e5da015c714b01ca84d087d760fe31e473b5/dist/ng-flat-datepicker.js#L137-L147 | train |
RemiAWE/ng-flat-datepicker | dist/ng-flat-datepicker.js | getWeeks | function getWeeks (date) {
var weeks = [];
var date = moment.utc(date);
var firstDayOfMonth = moment(date).date(1);
var lastDayOfMonth = moment(date).date(date.daysInMonth());
var startDay = moment(firstDayOfMonth);
var endDay = moment(lastDayOfMonth);
// NB: We use weekday() to get a locale aware weekday
startDay = firstDayOfMonth.weekday() === 0 ? startDay : startDay.weekday(0);
endDay = lastDayOfMonth.weekday() === 6 ? endDay : endDay.weekday(6);
var currentWeek = [];
for (var start = moment(startDay); start.isBefore(moment(endDay).add(1, 'days')); start.add(1, 'days')) {
var afterMinDate = !scope.config.minDate || start.isAfter(scope.config.minDate, 'day');
var beforeMaxDate = !scope.config.maxDate || start.isBefore(scope.config.maxDate, 'day');
var isFuture = start.isAfter(today);
var beforeFuture = scope.config.allowFuture || !isFuture;
var day = {
date: moment(start).toDate(),
isToday: start.isSame(today, 'day'),
isInMonth: start.isSame(firstDayOfMonth, 'month'),
isSelected: start.isSame(dateSelected, 'day'),
isSelectable: afterMinDate && beforeMaxDate && beforeFuture
};
currentWeek.push(day);
if (start.weekday() === 6 || start === endDay) {
weeks.push(currentWeek);
currentWeek = [];
}
}
return weeks;
} | javascript | function getWeeks (date) {
var weeks = [];
var date = moment.utc(date);
var firstDayOfMonth = moment(date).date(1);
var lastDayOfMonth = moment(date).date(date.daysInMonth());
var startDay = moment(firstDayOfMonth);
var endDay = moment(lastDayOfMonth);
// NB: We use weekday() to get a locale aware weekday
startDay = firstDayOfMonth.weekday() === 0 ? startDay : startDay.weekday(0);
endDay = lastDayOfMonth.weekday() === 6 ? endDay : endDay.weekday(6);
var currentWeek = [];
for (var start = moment(startDay); start.isBefore(moment(endDay).add(1, 'days')); start.add(1, 'days')) {
var afterMinDate = !scope.config.minDate || start.isAfter(scope.config.minDate, 'day');
var beforeMaxDate = !scope.config.maxDate || start.isBefore(scope.config.maxDate, 'day');
var isFuture = start.isAfter(today);
var beforeFuture = scope.config.allowFuture || !isFuture;
var day = {
date: moment(start).toDate(),
isToday: start.isSame(today, 'day'),
isInMonth: start.isSame(firstDayOfMonth, 'month'),
isSelected: start.isSame(dateSelected, 'day'),
isSelectable: afterMinDate && beforeMaxDate && beforeFuture
};
currentWeek.push(day);
if (start.weekday() === 6 || start === endDay) {
weeks.push(currentWeek);
currentWeek = [];
}
}
return weeks;
} | [
"function",
"getWeeks",
"(",
"date",
")",
"{",
"var",
"weeks",
"=",
"[",
"]",
";",
"var",
"date",
"=",
"moment",
".",
"utc",
"(",
"date",
")",
";",
"var",
"firstDayOfMonth",
"=",
"moment",
"(",
"date",
")",
".",
"date",
"(",
"1",
")",
";",
"var",
"lastDayOfMonth",
"=",
"moment",
"(",
"date",
")",
".",
"date",
"(",
"date",
".",
"daysInMonth",
"(",
")",
")",
";",
"var",
"startDay",
"=",
"moment",
"(",
"firstDayOfMonth",
")",
";",
"var",
"endDay",
"=",
"moment",
"(",
"lastDayOfMonth",
")",
";",
"startDay",
"=",
"firstDayOfMonth",
".",
"weekday",
"(",
")",
"===",
"0",
"?",
"startDay",
":",
"startDay",
".",
"weekday",
"(",
"0",
")",
";",
"endDay",
"=",
"lastDayOfMonth",
".",
"weekday",
"(",
")",
"===",
"6",
"?",
"endDay",
":",
"endDay",
".",
"weekday",
"(",
"6",
")",
";",
"var",
"currentWeek",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"start",
"=",
"moment",
"(",
"startDay",
")",
";",
"start",
".",
"isBefore",
"(",
"moment",
"(",
"endDay",
")",
".",
"add",
"(",
"1",
",",
"'days'",
")",
")",
";",
"start",
".",
"add",
"(",
"1",
",",
"'days'",
")",
")",
"{",
"var",
"afterMinDate",
"=",
"!",
"scope",
".",
"config",
".",
"minDate",
"||",
"start",
".",
"isAfter",
"(",
"scope",
".",
"config",
".",
"minDate",
",",
"'day'",
")",
";",
"var",
"beforeMaxDate",
"=",
"!",
"scope",
".",
"config",
".",
"maxDate",
"||",
"start",
".",
"isBefore",
"(",
"scope",
".",
"config",
".",
"maxDate",
",",
"'day'",
")",
";",
"var",
"isFuture",
"=",
"start",
".",
"isAfter",
"(",
"today",
")",
";",
"var",
"beforeFuture",
"=",
"scope",
".",
"config",
".",
"allowFuture",
"||",
"!",
"isFuture",
";",
"var",
"day",
"=",
"{",
"date",
":",
"moment",
"(",
"start",
")",
".",
"toDate",
"(",
")",
",",
"isToday",
":",
"start",
".",
"isSame",
"(",
"today",
",",
"'day'",
")",
",",
"isInMonth",
":",
"start",
".",
"isSame",
"(",
"firstDayOfMonth",
",",
"'month'",
")",
",",
"isSelected",
":",
"start",
".",
"isSame",
"(",
"dateSelected",
",",
"'day'",
")",
",",
"isSelectable",
":",
"afterMinDate",
"&&",
"beforeMaxDate",
"&&",
"beforeFuture",
"}",
";",
"currentWeek",
".",
"push",
"(",
"day",
")",
";",
"if",
"(",
"start",
".",
"weekday",
"(",
")",
"===",
"6",
"||",
"start",
"===",
"endDay",
")",
"{",
"weeks",
".",
"push",
"(",
"currentWeek",
")",
";",
"currentWeek",
"=",
"[",
"]",
";",
"}",
"}",
"return",
"weeks",
";",
"}"
]
| Get all weeks needed to display a month on the Datepicker
@return {array} list of weeks objects | [
"Get",
"all",
"weeks",
"needed",
"to",
"display",
"a",
"month",
"on",
"the",
"Datepicker"
]
| a349e5da015c714b01ca84d087d760fe31e473b5 | https://github.com/RemiAWE/ng-flat-datepicker/blob/a349e5da015c714b01ca84d087d760fe31e473b5/dist/ng-flat-datepicker.js#L153-L192 | train |
RemiAWE/ng-flat-datepicker | dist/ng-flat-datepicker.js | resetSelectedDays | function resetSelectedDays () {
scope.currentWeeks.forEach(function(week, wIndex){
week.forEach(function(day, dIndex){
scope.currentWeeks[wIndex][dIndex].isSelected = false;
});
});
} | javascript | function resetSelectedDays () {
scope.currentWeeks.forEach(function(week, wIndex){
week.forEach(function(day, dIndex){
scope.currentWeeks[wIndex][dIndex].isSelected = false;
});
});
} | [
"function",
"resetSelectedDays",
"(",
")",
"{",
"scope",
".",
"currentWeeks",
".",
"forEach",
"(",
"function",
"(",
"week",
",",
"wIndex",
")",
"{",
"week",
".",
"forEach",
"(",
"function",
"(",
"day",
",",
"dIndex",
")",
"{",
"scope",
".",
"currentWeeks",
"[",
"wIndex",
"]",
"[",
"dIndex",
"]",
".",
"isSelected",
"=",
"false",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| Reset all selected days | [
"Reset",
"all",
"selected",
"days"
]
| a349e5da015c714b01ca84d087d760fe31e473b5 | https://github.com/RemiAWE/ng-flat-datepicker/blob/a349e5da015c714b01ca84d087d760fe31e473b5/dist/ng-flat-datepicker.js#L197-L203 | train |
RemiAWE/ng-flat-datepicker | dist/ng-flat-datepicker.js | getYearsList | function getYearsList() {
var yearsList = [];
for (var i = 2005; i <= moment().year(); i++) {
yearsList.push(i);
}
return yearsList;
} | javascript | function getYearsList() {
var yearsList = [];
for (var i = 2005; i <= moment().year(); i++) {
yearsList.push(i);
}
return yearsList;
} | [
"function",
"getYearsList",
"(",
")",
"{",
"var",
"yearsList",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"2005",
";",
"i",
"<=",
"moment",
"(",
")",
".",
"year",
"(",
")",
";",
"i",
"++",
")",
"{",
"yearsList",
".",
"push",
"(",
"i",
")",
";",
"}",
"return",
"yearsList",
";",
"}"
]
| List all years for the select
@return {[type]} [description] | [
"List",
"all",
"years",
"for",
"the",
"select"
]
| a349e5da015c714b01ca84d087d760fe31e473b5 | https://github.com/RemiAWE/ng-flat-datepicker/blob/a349e5da015c714b01ca84d087d760fe31e473b5/dist/ng-flat-datepicker.js#L229-L235 | train |
RemiAWE/ng-flat-datepicker | dist/ng-flat-datepicker.js | getDaysNames | function getDaysNames () {
var daysNameList = [];
for (var i = 0; i < 7 ; i++) {
daysNameList.push(moment().weekday(i).format('ddd'));
}
return daysNameList;
} | javascript | function getDaysNames () {
var daysNameList = [];
for (var i = 0; i < 7 ; i++) {
daysNameList.push(moment().weekday(i).format('ddd'));
}
return daysNameList;
} | [
"function",
"getDaysNames",
"(",
")",
"{",
"var",
"daysNameList",
"=",
"[",
"]",
";",
"for",
"(",
"var",
"i",
"=",
"0",
";",
"i",
"<",
"7",
";",
"i",
"++",
")",
"{",
"daysNameList",
".",
"push",
"(",
"moment",
"(",
")",
".",
"weekday",
"(",
"i",
")",
".",
"format",
"(",
"'ddd'",
")",
")",
";",
"}",
"return",
"daysNameList",
";",
"}"
]
| List all days name in the current locale
@return {[type]} [description] | [
"List",
"all",
"days",
"name",
"in",
"the",
"current",
"locale"
]
| a349e5da015c714b01ca84d087d760fe31e473b5 | https://github.com/RemiAWE/ng-flat-datepicker/blob/a349e5da015c714b01ca84d087d760fe31e473b5/dist/ng-flat-datepicker.js#L241-L247 | train |
plasticrake/tplink-smarthome-crypto | lib/index.js | encrypt | function encrypt (input, firstKey = 0xAB) {
const buf = Buffer.from(input);
let key = firstKey;
for (let i = 0; i < buf.length; i++) {
buf[i] = buf[i] ^ key;
key = buf[i];
}
return buf;
} | javascript | function encrypt (input, firstKey = 0xAB) {
const buf = Buffer.from(input);
let key = firstKey;
for (let i = 0; i < buf.length; i++) {
buf[i] = buf[i] ^ key;
key = buf[i];
}
return buf;
} | [
"function",
"encrypt",
"(",
"input",
",",
"firstKey",
"=",
"0xAB",
")",
"{",
"const",
"buf",
"=",
"Buffer",
".",
"from",
"(",
"input",
")",
";",
"let",
"key",
"=",
"firstKey",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"buf",
".",
"length",
";",
"i",
"++",
")",
"{",
"buf",
"[",
"i",
"]",
"=",
"buf",
"[",
"i",
"]",
"^",
"key",
";",
"key",
"=",
"buf",
"[",
"i",
"]",
";",
"}",
"return",
"buf",
";",
"}"
]
| TP-Link Smarthome Crypto
TCP communication includes a 4 byte header, UDP does not.
@module tplink-smarthome-crypto
Encrypts input where each byte is XOR'd with the previous encrypted byte.
@alias module:tplink-smarthome-crypto.encrypt
@param {(Buffer|string)} input Buffer/string to encrypt
@param {number} [firstKey=0xAB]
@return {Buffer} encrypted buffer | [
"TP",
"-",
"Link",
"Smarthome",
"Crypto"
]
| 12a6a3bbcce60913b2c55193818a9fb1854d2b8d | https://github.com/plasticrake/tplink-smarthome-crypto/blob/12a6a3bbcce60913b2c55193818a9fb1854d2b8d/lib/index.js#L15-L23 | train |
plasticrake/tplink-smarthome-crypto | lib/index.js | encryptWithHeader | function encryptWithHeader (input, firstKey = 0xAB) {
const msgBuf = encrypt(input, firstKey);
const outBuf = Buffer.alloc(msgBuf.length + 4);
outBuf.writeUInt32BE(msgBuf.length, 0);
msgBuf.copy(outBuf, 4);
return outBuf;
} | javascript | function encryptWithHeader (input, firstKey = 0xAB) {
const msgBuf = encrypt(input, firstKey);
const outBuf = Buffer.alloc(msgBuf.length + 4);
outBuf.writeUInt32BE(msgBuf.length, 0);
msgBuf.copy(outBuf, 4);
return outBuf;
} | [
"function",
"encryptWithHeader",
"(",
"input",
",",
"firstKey",
"=",
"0xAB",
")",
"{",
"const",
"msgBuf",
"=",
"encrypt",
"(",
"input",
",",
"firstKey",
")",
";",
"const",
"outBuf",
"=",
"Buffer",
".",
"alloc",
"(",
"msgBuf",
".",
"length",
"+",
"4",
")",
";",
"outBuf",
".",
"writeUInt32BE",
"(",
"msgBuf",
".",
"length",
",",
"0",
")",
";",
"msgBuf",
".",
"copy",
"(",
"outBuf",
",",
"4",
")",
";",
"return",
"outBuf",
";",
"}"
]
| Encrypts input that has a 4 byte big-endian length header;
each byte is XOR'd with the previous encrypted byte.
@alias module:tplink-smarthome-crypto.encryptWithHeader
@param {(Buffer|string)} input Buffer/string to encrypt
@param {number} [firstKey=0xAB]
@return {Buffer} encrypted buffer with header | [
"Encrypts",
"input",
"that",
"has",
"a",
"4",
"byte",
"big",
"-",
"endian",
"length",
"header",
";",
"each",
"byte",
"is",
"XOR",
"d",
"with",
"the",
"previous",
"encrypted",
"byte",
"."
]
| 12a6a3bbcce60913b2c55193818a9fb1854d2b8d | https://github.com/plasticrake/tplink-smarthome-crypto/blob/12a6a3bbcce60913b2c55193818a9fb1854d2b8d/lib/index.js#L32-L38 | train |
plasticrake/tplink-smarthome-crypto | lib/index.js | decrypt | function decrypt (input, firstKey = 0xAB) {
const buf = Buffer.from(input);
let key = firstKey;
let nextKey;
for (let i = 0; i < buf.length; i++) {
nextKey = buf[i];
buf[i] = buf[i] ^ key;
key = nextKey;
}
return buf;
} | javascript | function decrypt (input, firstKey = 0xAB) {
const buf = Buffer.from(input);
let key = firstKey;
let nextKey;
for (let i = 0; i < buf.length; i++) {
nextKey = buf[i];
buf[i] = buf[i] ^ key;
key = nextKey;
}
return buf;
} | [
"function",
"decrypt",
"(",
"input",
",",
"firstKey",
"=",
"0xAB",
")",
"{",
"const",
"buf",
"=",
"Buffer",
".",
"from",
"(",
"input",
")",
";",
"let",
"key",
"=",
"firstKey",
";",
"let",
"nextKey",
";",
"for",
"(",
"let",
"i",
"=",
"0",
";",
"i",
"<",
"buf",
".",
"length",
";",
"i",
"++",
")",
"{",
"nextKey",
"=",
"buf",
"[",
"i",
"]",
";",
"buf",
"[",
"i",
"]",
"=",
"buf",
"[",
"i",
"]",
"^",
"key",
";",
"key",
"=",
"nextKey",
";",
"}",
"return",
"buf",
";",
"}"
]
| Decrypts input where each byte is XOR'd with the previous encrypted byte.
@alias module:tplink-smarthome-crypto.decrypt
@param {Buffer} input encrypted Buffer
@param {number} [firstKey=0xAB]
@return {Buffer} decrypted buffer | [
"Decrypts",
"input",
"where",
"each",
"byte",
"is",
"XOR",
"d",
"with",
"the",
"previous",
"encrypted",
"byte",
"."
]
| 12a6a3bbcce60913b2c55193818a9fb1854d2b8d | https://github.com/plasticrake/tplink-smarthome-crypto/blob/12a6a3bbcce60913b2c55193818a9fb1854d2b8d/lib/index.js#L46-L56 | train |
Dev1an/Atem | index.js | getPendingPacket | function getPendingPacket(ls){
var i;
for (i = pendingPackets.length - 1; i >= 0; i--)
if (pendingPackets[i].header.ls == ls)
return pendingPackets[i];
} | javascript | function getPendingPacket(ls){
var i;
for (i = pendingPackets.length - 1; i >= 0; i--)
if (pendingPackets[i].header.ls == ls)
return pendingPackets[i];
} | [
"function",
"getPendingPacket",
"(",
"ls",
")",
"{",
"var",
"i",
";",
"for",
"(",
"i",
"=",
"pendingPackets",
".",
"length",
"-",
"1",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"if",
"(",
"pendingPackets",
"[",
"i",
"]",
".",
"header",
".",
"ls",
"==",
"ls",
")",
"return",
"pendingPackets",
"[",
"i",
"]",
";",
"}"
]
| When an error is encountered during communication, this event will be fired.
@event Device#error
@type {Error}
@property {String} Message
Find a pending packet by local sequence number
@param {Number} ls Local sequence number
@return {UserPacket} The packet | [
"When",
"an",
"error",
"is",
"encountered",
"during",
"communication",
"this",
"event",
"will",
"be",
"fired",
"."
]
| 22436f436687fcf54a84883b3c9a0c072d55f43a | https://github.com/Dev1an/Atem/blob/22436f436687fcf54a84883b3c9a0c072d55f43a/index.js#L278-L283 | train |
Dev1an/Atem | index.js | UserPacket | function UserPacket(commands){
Packet.call(this);
this.interval = undefined;
// If the packet contains commands
if (typeof commands !== 'undefined'){
// If it is a connect packet
if (commands === null) {
this.header.flags = flags.connect;
this.body.commands = [{
get length() { return 8; },
serialize: function() {
const connectCmd = '0100000000000000';
return (new Buffer(connectCmd, 'hex'));
}
}];
}
else {
this.body.commands = commands;
this.header.flags = flags.sync;
}
}
// If the packet contains no commands
else {
this.header.flags = flags.sync;
}
} | javascript | function UserPacket(commands){
Packet.call(this);
this.interval = undefined;
// If the packet contains commands
if (typeof commands !== 'undefined'){
// If it is a connect packet
if (commands === null) {
this.header.flags = flags.connect;
this.body.commands = [{
get length() { return 8; },
serialize: function() {
const connectCmd = '0100000000000000';
return (new Buffer(connectCmd, 'hex'));
}
}];
}
else {
this.body.commands = commands;
this.header.flags = flags.sync;
}
}
// If the packet contains no commands
else {
this.header.flags = flags.sync;
}
} | [
"function",
"UserPacket",
"(",
"commands",
")",
"{",
"Packet",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"interval",
"=",
"undefined",
";",
"if",
"(",
"typeof",
"commands",
"!==",
"'undefined'",
")",
"{",
"if",
"(",
"commands",
"===",
"null",
")",
"{",
"this",
".",
"header",
".",
"flags",
"=",
"flags",
".",
"connect",
";",
"this",
".",
"body",
".",
"commands",
"=",
"[",
"{",
"get",
"length",
"(",
")",
"{",
"return",
"8",
";",
"}",
",",
"serialize",
":",
"function",
"(",
")",
"{",
"const",
"connectCmd",
"=",
"'0100000000000000'",
";",
"return",
"(",
"new",
"Buffer",
"(",
"connectCmd",
",",
"'hex'",
")",
")",
";",
"}",
"}",
"]",
";",
"}",
"else",
"{",
"this",
".",
"body",
".",
"commands",
"=",
"commands",
";",
"this",
".",
"header",
".",
"flags",
"=",
"flags",
".",
"sync",
";",
"}",
"}",
"else",
"{",
"this",
".",
"header",
".",
"flags",
"=",
"flags",
".",
"sync",
";",
"}",
"}"
]
| Create a custom UserPacket.
@constructor UserPacket
@augments Packet
@classdesc A Packet commissiond by the user. This is used to send messages to the ATEM.
@param {Command[]|null} [commands] An array of commands. If null, a connect packet will be created | [
"Create",
"a",
"custom",
"UserPacket",
"."
]
| 22436f436687fcf54a84883b3c9a0c072d55f43a | https://github.com/Dev1an/Atem/blob/22436f436687fcf54a84883b3c9a0c072d55f43a/index.js#L304-L331 | train |
Dev1an/Atem | index.js | AtemPacket | function AtemPacket(msg){
Packet.call(this);
this.header.flags = msg[0]>>>3;
this.header.uid = msg.readUInt16BE(2);
this.header.fs = msg.readUInt16BE(4);
this.header.ls = msg.readUInt16BE(10);
if ((this.header.flags & flags.unknown) == flags.unknown) console.log('Unknown Packet flag!');
if (state === ConnectionState.attempting) {
if (this.isSync()){
atem.state = ConnectionState.establishing;
uid = this.header.uid;
}
} else
if (state === ConnectionState.establishing){
if (msg.length==12 && !this.isConnect()){
atem.state = ConnectionState.open;
clearInterval(syncInterval);
syncInterval = setInterval(sync, 600);
}
}
if (this.isConnect()) {
//Do something
}
else if ((msg.length == (msg.readUInt16BE(0)&0x7FF) && this.header.uid == uid)){
const body = msg.slice(12);
var name, data, cmd, cmdLength, cursor=0;
while (cursor < body.length-1) {
cmdLength = body.readUInt16BE(cursor);
name = body.toString('utf8', cursor+4, cursor+8);
data = body.slice(cursor+8, cursor+cmdLength);
cmd = new Command(name, data);
this.body.commands.push(cmd);
cursor += cmdLength;
/**
* @event Device#rawCommand
* @type {Command}
*/
// todo: check foreign sequence number, to prevent the event emitter
// from emitting the same message twice.
atem.emit('rawCommand', cmd);
atem.emit(cmd.name, cmd.data);
}
}
else if (msg.length != (msg.readUInt16BE(0)&0x7FF)) {
const err = new Error('Message length mismatch');
self.emit('error', err);
} else {
const err2 = new Error('UID mismatch');
self.emit('error', err2);
}
} | javascript | function AtemPacket(msg){
Packet.call(this);
this.header.flags = msg[0]>>>3;
this.header.uid = msg.readUInt16BE(2);
this.header.fs = msg.readUInt16BE(4);
this.header.ls = msg.readUInt16BE(10);
if ((this.header.flags & flags.unknown) == flags.unknown) console.log('Unknown Packet flag!');
if (state === ConnectionState.attempting) {
if (this.isSync()){
atem.state = ConnectionState.establishing;
uid = this.header.uid;
}
} else
if (state === ConnectionState.establishing){
if (msg.length==12 && !this.isConnect()){
atem.state = ConnectionState.open;
clearInterval(syncInterval);
syncInterval = setInterval(sync, 600);
}
}
if (this.isConnect()) {
//Do something
}
else if ((msg.length == (msg.readUInt16BE(0)&0x7FF) && this.header.uid == uid)){
const body = msg.slice(12);
var name, data, cmd, cmdLength, cursor=0;
while (cursor < body.length-1) {
cmdLength = body.readUInt16BE(cursor);
name = body.toString('utf8', cursor+4, cursor+8);
data = body.slice(cursor+8, cursor+cmdLength);
cmd = new Command(name, data);
this.body.commands.push(cmd);
cursor += cmdLength;
/**
* @event Device#rawCommand
* @type {Command}
*/
// todo: check foreign sequence number, to prevent the event emitter
// from emitting the same message twice.
atem.emit('rawCommand', cmd);
atem.emit(cmd.name, cmd.data);
}
}
else if (msg.length != (msg.readUInt16BE(0)&0x7FF)) {
const err = new Error('Message length mismatch');
self.emit('error', err);
} else {
const err2 = new Error('UID mismatch');
self.emit('error', err2);
}
} | [
"function",
"AtemPacket",
"(",
"msg",
")",
"{",
"Packet",
".",
"call",
"(",
"this",
")",
";",
"this",
".",
"header",
".",
"flags",
"=",
"msg",
"[",
"0",
"]",
">>>",
"3",
";",
"this",
".",
"header",
".",
"uid",
"=",
"msg",
".",
"readUInt16BE",
"(",
"2",
")",
";",
"this",
".",
"header",
".",
"fs",
"=",
"msg",
".",
"readUInt16BE",
"(",
"4",
")",
";",
"this",
".",
"header",
".",
"ls",
"=",
"msg",
".",
"readUInt16BE",
"(",
"10",
")",
";",
"if",
"(",
"(",
"this",
".",
"header",
".",
"flags",
"&",
"flags",
".",
"unknown",
")",
"==",
"flags",
".",
"unknown",
")",
"console",
".",
"log",
"(",
"'Unknown Packet flag!'",
")",
";",
"if",
"(",
"state",
"===",
"ConnectionState",
".",
"attempting",
")",
"{",
"if",
"(",
"this",
".",
"isSync",
"(",
")",
")",
"{",
"atem",
".",
"state",
"=",
"ConnectionState",
".",
"establishing",
";",
"uid",
"=",
"this",
".",
"header",
".",
"uid",
";",
"}",
"}",
"else",
"if",
"(",
"state",
"===",
"ConnectionState",
".",
"establishing",
")",
"{",
"if",
"(",
"msg",
".",
"length",
"==",
"12",
"&&",
"!",
"this",
".",
"isConnect",
"(",
")",
")",
"{",
"atem",
".",
"state",
"=",
"ConnectionState",
".",
"open",
";",
"clearInterval",
"(",
"syncInterval",
")",
";",
"syncInterval",
"=",
"setInterval",
"(",
"sync",
",",
"600",
")",
";",
"}",
"}",
"if",
"(",
"this",
".",
"isConnect",
"(",
")",
")",
"{",
"}",
"else",
"if",
"(",
"(",
"msg",
".",
"length",
"==",
"(",
"msg",
".",
"readUInt16BE",
"(",
"0",
")",
"&",
"0x7FF",
")",
"&&",
"this",
".",
"header",
".",
"uid",
"==",
"uid",
")",
")",
"{",
"const",
"body",
"=",
"msg",
".",
"slice",
"(",
"12",
")",
";",
"var",
"name",
",",
"data",
",",
"cmd",
",",
"cmdLength",
",",
"cursor",
"=",
"0",
";",
"while",
"(",
"cursor",
"<",
"body",
".",
"length",
"-",
"1",
")",
"{",
"cmdLength",
"=",
"body",
".",
"readUInt16BE",
"(",
"cursor",
")",
";",
"name",
"=",
"body",
".",
"toString",
"(",
"'utf8'",
",",
"cursor",
"+",
"4",
",",
"cursor",
"+",
"8",
")",
";",
"data",
"=",
"body",
".",
"slice",
"(",
"cursor",
"+",
"8",
",",
"cursor",
"+",
"cmdLength",
")",
";",
"cmd",
"=",
"new",
"Command",
"(",
"name",
",",
"data",
")",
";",
"this",
".",
"body",
".",
"commands",
".",
"push",
"(",
"cmd",
")",
";",
"cursor",
"+=",
"cmdLength",
";",
"atem",
".",
"emit",
"(",
"'rawCommand'",
",",
"cmd",
")",
";",
"atem",
".",
"emit",
"(",
"cmd",
".",
"name",
",",
"cmd",
".",
"data",
")",
";",
"}",
"}",
"else",
"if",
"(",
"msg",
".",
"length",
"!=",
"(",
"msg",
".",
"readUInt16BE",
"(",
"0",
")",
"&",
"0x7FF",
")",
")",
"{",
"const",
"err",
"=",
"new",
"Error",
"(",
"'Message length mismatch'",
")",
";",
"self",
".",
"emit",
"(",
"'error'",
",",
"err",
")",
";",
"}",
"else",
"{",
"const",
"err2",
"=",
"new",
"Error",
"(",
"'UID mismatch'",
")",
";",
"self",
".",
"emit",
"(",
"'error'",
",",
"err2",
")",
";",
"}",
"}"
]
| Parse an ATEM UDP message
@constructor AtemPacket
@augments Packet
@classdesc Used to parse an UDP message from the Atem
@param {Buffer} msg The message to parse | [
"Parse",
"an",
"ATEM",
"UDP",
"message"
]
| 22436f436687fcf54a84883b3c9a0c072d55f43a | https://github.com/Dev1an/Atem/blob/22436f436687fcf54a84883b3c9a0c072d55f43a/index.js#L435-L492 | train |
Dev1an/Atem | index.js | handleQueue | function handleQueue() {
const count = commandQueue.length
if (count>0) {
const packet = new UserPacket(commandQueue.slice(0));
commandQueue = [];
packet.transmit();
}
return count
} | javascript | function handleQueue() {
const count = commandQueue.length
if (count>0) {
const packet = new UserPacket(commandQueue.slice(0));
commandQueue = [];
packet.transmit();
}
return count
} | [
"function",
"handleQueue",
"(",
")",
"{",
"const",
"count",
"=",
"commandQueue",
".",
"length",
"if",
"(",
"count",
">",
"0",
")",
"{",
"const",
"packet",
"=",
"new",
"UserPacket",
"(",
"commandQueue",
".",
"slice",
"(",
"0",
")",
")",
";",
"commandQueue",
"=",
"[",
"]",
";",
"packet",
".",
"transmit",
"(",
")",
";",
"}",
"return",
"count",
"}"
]
| Sends a packet with all the remaining command of the commandQueue | [
"Sends",
"a",
"packet",
"with",
"all",
"the",
"remaining",
"command",
"of",
"the",
"commandQueue"
]
| 22436f436687fcf54a84883b3c9a0c072d55f43a | https://github.com/Dev1an/Atem/blob/22436f436687fcf54a84883b3c9a0c072d55f43a/index.js#L540-L551 | train |
bojand/json-schema-test-data-generator | lib/index.js | generate | function generate(schema) {
const ret = [];
if (!validate(schema)) {
return ret;
}
const fullSample = jsf(schema);
if (!fullSample) {
return ret;
}
ret.push({
valid: true,
data: fullSample,
message: 'should work with all required properties'
});
ret.push(...generateFromRequired(schema));
ret.push(...generateFromRequired(schema, false));
ret.push(...generateForTypes(schema));
return ret;
} | javascript | function generate(schema) {
const ret = [];
if (!validate(schema)) {
return ret;
}
const fullSample = jsf(schema);
if (!fullSample) {
return ret;
}
ret.push({
valid: true,
data: fullSample,
message: 'should work with all required properties'
});
ret.push(...generateFromRequired(schema));
ret.push(...generateFromRequired(schema, false));
ret.push(...generateForTypes(schema));
return ret;
} | [
"function",
"generate",
"(",
"schema",
")",
"{",
"const",
"ret",
"=",
"[",
"]",
";",
"if",
"(",
"!",
"validate",
"(",
"schema",
")",
")",
"{",
"return",
"ret",
";",
"}",
"const",
"fullSample",
"=",
"jsf",
"(",
"schema",
")",
";",
"if",
"(",
"!",
"fullSample",
")",
"{",
"return",
"ret",
";",
"}",
"ret",
".",
"push",
"(",
"{",
"valid",
":",
"true",
",",
"data",
":",
"fullSample",
",",
"message",
":",
"'should work with all required properties'",
"}",
")",
";",
"ret",
".",
"push",
"(",
"...",
"generateFromRequired",
"(",
"schema",
")",
")",
";",
"ret",
".",
"push",
"(",
"...",
"generateFromRequired",
"(",
"schema",
",",
"false",
")",
")",
";",
"ret",
".",
"push",
"(",
"...",
"generateForTypes",
"(",
"schema",
")",
")",
";",
"return",
"ret",
";",
"}"
]
| Generates test data based on JSON schema
@param {Object} schema Fully expanded (no <code>$ref</code>) JSON Schema
@return {Array} Array of test data objects | [
"Generates",
"test",
"data",
"based",
"on",
"JSON",
"schema"
]
| 32c07f7e7a767ec87c2403acad2018754bea862d | https://github.com/bojand/json-schema-test-data-generator/blob/32c07f7e7a767ec87c2403acad2018754bea862d/lib/index.js#L420-L442 | train |
noderaider/localsync | packages/serversync/lib/index.js | serversync | function serversync(key, action, handler) {
var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
_ref$tracing = _ref.tracing,
tracing = _ref$tracing === undefined ? false : _ref$tracing,
_ref$logger = _ref.logger,
logger = _ref$logger === undefined ? console : _ref$logger,
_ref$logLevel = _ref.logLevel,
logLevel = _ref$logLevel === undefined ? 'info' : _ref$logLevel;
(0, _invariant2.default)(key, 'key is required');
(0, _invariant2.default)(action, 'action is required');
(0, _invariant2.default)(handler, 'handler is required');
var log = function log() {
return tracing ? logger[logLevel].apply(logger, arguments) : function () {};
};
var isRunning = false;
var trigger = function trigger() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
log('serversync#trigger', args);
var value = action.apply(undefined, args);
log('serversync#trigger action output ignored', args, value);
};
var start = function start() {
log('serversync#start');
isRunning = true;
};
var stop = function stop() {
log('serversync#stop');
isRunning = false;
};
return { start: start,
stop: stop,
trigger: trigger,
get isRunning() {
return isRunning;
},
mechanism: mechanism,
isFallback: false,
isServer: true
};
} | javascript | function serversync(key, action, handler) {
var _ref = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {},
_ref$tracing = _ref.tracing,
tracing = _ref$tracing === undefined ? false : _ref$tracing,
_ref$logger = _ref.logger,
logger = _ref$logger === undefined ? console : _ref$logger,
_ref$logLevel = _ref.logLevel,
logLevel = _ref$logLevel === undefined ? 'info' : _ref$logLevel;
(0, _invariant2.default)(key, 'key is required');
(0, _invariant2.default)(action, 'action is required');
(0, _invariant2.default)(handler, 'handler is required');
var log = function log() {
return tracing ? logger[logLevel].apply(logger, arguments) : function () {};
};
var isRunning = false;
var trigger = function trigger() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
log('serversync#trigger', args);
var value = action.apply(undefined, args);
log('serversync#trigger action output ignored', args, value);
};
var start = function start() {
log('serversync#start');
isRunning = true;
};
var stop = function stop() {
log('serversync#stop');
isRunning = false;
};
return { start: start,
stop: stop,
trigger: trigger,
get isRunning() {
return isRunning;
},
mechanism: mechanism,
isFallback: false,
isServer: true
};
} | [
"function",
"serversync",
"(",
"key",
",",
"action",
",",
"handler",
")",
"{",
"var",
"_ref",
"=",
"arguments",
".",
"length",
">",
"3",
"&&",
"arguments",
"[",
"3",
"]",
"!==",
"undefined",
"?",
"arguments",
"[",
"3",
"]",
":",
"{",
"}",
",",
"_ref$tracing",
"=",
"_ref",
".",
"tracing",
",",
"tracing",
"=",
"_ref$tracing",
"===",
"undefined",
"?",
"false",
":",
"_ref$tracing",
",",
"_ref$logger",
"=",
"_ref",
".",
"logger",
",",
"logger",
"=",
"_ref$logger",
"===",
"undefined",
"?",
"console",
":",
"_ref$logger",
",",
"_ref$logLevel",
"=",
"_ref",
".",
"logLevel",
",",
"logLevel",
"=",
"_ref$logLevel",
"===",
"undefined",
"?",
"'info'",
":",
"_ref$logLevel",
";",
"(",
"0",
",",
"_invariant2",
".",
"default",
")",
"(",
"key",
",",
"'key is required'",
")",
";",
"(",
"0",
",",
"_invariant2",
".",
"default",
")",
"(",
"action",
",",
"'action is required'",
")",
";",
"(",
"0",
",",
"_invariant2",
".",
"default",
")",
"(",
"handler",
",",
"'handler is required'",
")",
";",
"var",
"log",
"=",
"function",
"log",
"(",
")",
"{",
"return",
"tracing",
"?",
"logger",
"[",
"logLevel",
"]",
".",
"apply",
"(",
"logger",
",",
"arguments",
")",
":",
"function",
"(",
")",
"{",
"}",
";",
"}",
";",
"var",
"isRunning",
"=",
"false",
";",
"var",
"trigger",
"=",
"function",
"trigger",
"(",
")",
"{",
"for",
"(",
"var",
"_len",
"=",
"arguments",
".",
"length",
",",
"args",
"=",
"Array",
"(",
"_len",
")",
",",
"_key",
"=",
"0",
";",
"_key",
"<",
"_len",
";",
"_key",
"++",
")",
"{",
"args",
"[",
"_key",
"]",
"=",
"arguments",
"[",
"_key",
"]",
";",
"}",
"log",
"(",
"'serversync#trigger'",
",",
"args",
")",
";",
"var",
"value",
"=",
"action",
".",
"apply",
"(",
"undefined",
",",
"args",
")",
";",
"log",
"(",
"'serversync#trigger action output ignored'",
",",
"args",
",",
"value",
")",
";",
"}",
";",
"var",
"start",
"=",
"function",
"start",
"(",
")",
"{",
"log",
"(",
"'serversync#start'",
")",
";",
"isRunning",
"=",
"true",
";",
"}",
";",
"var",
"stop",
"=",
"function",
"stop",
"(",
")",
"{",
"log",
"(",
"'serversync#stop'",
")",
";",
"isRunning",
"=",
"false",
";",
"}",
";",
"return",
"{",
"start",
":",
"start",
",",
"stop",
":",
"stop",
",",
"trigger",
":",
"trigger",
",",
"get",
"isRunning",
"(",
")",
"{",
"return",
"isRunning",
";",
"}",
",",
"mechanism",
":",
"mechanism",
",",
"isFallback",
":",
"false",
",",
"isServer",
":",
"true",
"}",
";",
"}"
]
| Creates a mock synchronizer which uses a server safe interface equivalent to serversync
@param {string} key The key to synchronize on.
@param {function} action The action to run when trigger is executed. Should return the payload to be transmitted to the handlers on other tabs.
@param {function} handler The handler which is executed on other tabs when a synchronization is triggered. Argument is the return value of the action.
@param {boolean} [options.tracing=false] Option to turn on tracing for debugging.
@param {Object} [options.logger=console] The logger to debug to.
@param {string} [options.logLevel=info] The log level to trace at.
@return {Object} serversync instance with start, stop, trigger, isRunning, and isFallback mock properties. | [
"Creates",
"a",
"mock",
"synchronizer",
"which",
"uses",
"a",
"server",
"safe",
"interface",
"equivalent",
"to",
"serversync"
]
| 489c68f57203b79c2403aaf045e194ff6b7b7d38 | https://github.com/noderaider/localsync/blob/489c68f57203b79c2403aaf045e194ff6b7b7d38/packages/serversync/lib/index.js#L26-L73 | train |
ArminTamzarian/node-calendar | node-calendar.js | _extractLocaleDays | function _extractLocaleDays(abbr, locale) {
if(abbr) {
return cldr ? cldr.extractDayNames(locale).format.abbreviated : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
}
else {
return cldr ? cldr.extractDayNames(locale).format.wide : ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
}
} | javascript | function _extractLocaleDays(abbr, locale) {
if(abbr) {
return cldr ? cldr.extractDayNames(locale).format.abbreviated : ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
}
else {
return cldr ? cldr.extractDayNames(locale).format.wide : ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
}
} | [
"function",
"_extractLocaleDays",
"(",
"abbr",
",",
"locale",
")",
"{",
"if",
"(",
"abbr",
")",
"{",
"return",
"cldr",
"?",
"cldr",
".",
"extractDayNames",
"(",
"locale",
")",
".",
"format",
".",
"abbreviated",
":",
"[",
"'Mon'",
",",
"'Tue'",
",",
"'Wed'",
",",
"'Thu'",
",",
"'Fri'",
",",
"'Sat'",
",",
"'Sun'",
"]",
";",
"}",
"else",
"{",
"return",
"cldr",
"?",
"cldr",
".",
"extractDayNames",
"(",
"locale",
")",
".",
"format",
".",
"wide",
":",
"[",
"'Monday'",
",",
"'Tuesday'",
",",
"'Wednesday'",
",",
"'Thursday'",
",",
"'Friday'",
",",
"'Saturday'",
",",
"'Sunday'",
"]",
";",
"}",
"}"
]
| Extracts the wide or abbreviated day names for a specified locale.
If cldr is not installed values default to that for locale en_US.
@param {Boolean} abbr
@param {String} locale
@api private | [
"Extracts",
"the",
"wide",
"or",
"abbreviated",
"day",
"names",
"for",
"a",
"specified",
"locale",
".",
"If",
"cldr",
"is",
"not",
"installed",
"values",
"default",
"to",
"that",
"for",
"locale",
"en_US",
"."
]
| aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0 | https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L37-L44 | train |
ArminTamzarian/node-calendar | node-calendar.js | _extractLocaleMonths | function _extractLocaleMonths(abbr, locale) {
var months = []
if(abbr) {
months = cldr ? cldr.extractMonthNames(locale).format.abbreviated : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
}
else {
months = cldr ? cldr.extractMonthNames(locale).format.wide : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
}
months.unshift('');
return months;
} | javascript | function _extractLocaleMonths(abbr, locale) {
var months = []
if(abbr) {
months = cldr ? cldr.extractMonthNames(locale).format.abbreviated : ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
}
else {
months = cldr ? cldr.extractMonthNames(locale).format.wide : ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
}
months.unshift('');
return months;
} | [
"function",
"_extractLocaleMonths",
"(",
"abbr",
",",
"locale",
")",
"{",
"var",
"months",
"=",
"[",
"]",
"if",
"(",
"abbr",
")",
"{",
"months",
"=",
"cldr",
"?",
"cldr",
".",
"extractMonthNames",
"(",
"locale",
")",
".",
"format",
".",
"abbreviated",
":",
"[",
"'Jan'",
",",
"'Feb'",
",",
"'Mar'",
",",
"'Apr'",
",",
"'May'",
",",
"'Jun'",
",",
"'Jul'",
",",
"'Aug'",
",",
"'Sep'",
",",
"'Oct'",
",",
"'Nov'",
",",
"'Dec'",
"]",
";",
"}",
"else",
"{",
"months",
"=",
"cldr",
"?",
"cldr",
".",
"extractMonthNames",
"(",
"locale",
")",
".",
"format",
".",
"wide",
":",
"[",
"'January'",
",",
"'February'",
",",
"'March'",
",",
"'April'",
",",
"'May'",
",",
"'June'",
",",
"'July'",
",",
"'August'",
",",
"'September'",
",",
"'October'",
",",
"'November'",
",",
"'December'",
"]",
";",
"}",
"months",
".",
"unshift",
"(",
"''",
")",
";",
"return",
"months",
";",
"}"
]
| Extracts the wide or abbreviated month names for a specified locale.
If cldr is not installed values default to that for locale en_US.
@param {Boolean} abbr
@param {String} locale
@api private | [
"Extracts",
"the",
"wide",
"or",
"abbreviated",
"month",
"names",
"for",
"a",
"specified",
"locale",
".",
"If",
"cldr",
"is",
"not",
"installed",
"values",
"default",
"to",
"that",
"for",
"locale",
"en_US",
"."
]
| aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0 | https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L54-L65 | train |
ArminTamzarian/node-calendar | node-calendar.js | _toordinal | function _toordinal(year, month, day) {
var days_before_year = ((year - 1) * 365) + Math.floor((year - 1) / 4) - Math.floor((year - 1) / 100) + Math.floor((year - 1) / 400);
var days_before_month = _DAYS_BEFORE_MONTH[month] + (month > 2 && isleap(year) ? 1 : 0);
return (days_before_year + days_before_month + day);
} | javascript | function _toordinal(year, month, day) {
var days_before_year = ((year - 1) * 365) + Math.floor((year - 1) / 4) - Math.floor((year - 1) / 100) + Math.floor((year - 1) / 400);
var days_before_month = _DAYS_BEFORE_MONTH[month] + (month > 2 && isleap(year) ? 1 : 0);
return (days_before_year + days_before_month + day);
} | [
"function",
"_toordinal",
"(",
"year",
",",
"month",
",",
"day",
")",
"{",
"var",
"days_before_year",
"=",
"(",
"(",
"year",
"-",
"1",
")",
"*",
"365",
")",
"+",
"Math",
".",
"floor",
"(",
"(",
"year",
"-",
"1",
")",
"/",
"4",
")",
"-",
"Math",
".",
"floor",
"(",
"(",
"year",
"-",
"1",
")",
"/",
"100",
")",
"+",
"Math",
".",
"floor",
"(",
"(",
"year",
"-",
"1",
")",
"/",
"400",
")",
";",
"var",
"days_before_month",
"=",
"_DAYS_BEFORE_MONTH",
"[",
"month",
"]",
"+",
"(",
"month",
">",
"2",
"&&",
"isleap",
"(",
"year",
")",
"?",
"1",
":",
"0",
")",
";",
"return",
"(",
"days_before_year",
"+",
"days_before_month",
"+",
"day",
")",
";",
"}"
]
| Calculates the ordinal time from given year, month, day values.
@param {Number} year
@param {Number} month
@param {Number} day
@api private | [
"Calculates",
"the",
"ordinal",
"time",
"from",
"given",
"year",
"month",
"day",
"values",
"."
]
| aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0 | https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L75-L79 | train |
ArminTamzarian/node-calendar | node-calendar.js | leapdays | function leapdays(y1, y2) {
y1--;
y2--;
return (Math.floor(y2/4) - Math.floor(y1/4)) - (Math.floor(y2/100) - Math.floor(y1/100)) + (Math.floor(y2/400) - Math.floor(y1/400));
} | javascript | function leapdays(y1, y2) {
y1--;
y2--;
return (Math.floor(y2/4) - Math.floor(y1/4)) - (Math.floor(y2/100) - Math.floor(y1/100)) + (Math.floor(y2/400) - Math.floor(y1/400));
} | [
"function",
"leapdays",
"(",
"y1",
",",
"y2",
")",
"{",
"y1",
"--",
";",
"y2",
"--",
";",
"return",
"(",
"Math",
".",
"floor",
"(",
"y2",
"/",
"4",
")",
"-",
"Math",
".",
"floor",
"(",
"y1",
"/",
"4",
")",
")",
"-",
"(",
"Math",
".",
"floor",
"(",
"y2",
"/",
"100",
")",
"-",
"Math",
".",
"floor",
"(",
"y1",
"/",
"100",
")",
")",
"+",
"(",
"Math",
".",
"floor",
"(",
"y2",
"/",
"400",
")",
"-",
"Math",
".",
"floor",
"(",
"y1",
"/",
"400",
")",
")",
";",
"}"
]
| Return number of leap years in range [y1, y2).
Assumes y1 <= y2.
@param {Number} y1
@param {Number} y2
@api public | [
"Return",
"number",
"of",
"leap",
"years",
"in",
"range",
"[",
"y1",
"y2",
")",
".",
"Assumes",
"y1",
"<",
"=",
"y2",
"."
]
| aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0 | https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L99-L103 | train |
ArminTamzarian/node-calendar | node-calendar.js | setlocale | function setlocale(locale) {
locale = typeof(locale) === "undefined" ? "en_US" : locale;
if((cldr && (cldr.localeIds.indexOf(locale.replace(/-/g, '_').toLowerCase()) === -1)) || (!cldr && ((locale.replace(/-/g, '_').toLowerCase() !== "en_us")))) {
throw new IllegalLocaleError();
}
this.day_name = _extractLocaleDays(false, locale);
this.day_abbr = _extractLocaleDays(true, locale);
this.month_name = _extractLocaleMonths(false, locale);
this.month_abbr = _extractLocaleMonths(true, locale);
} | javascript | function setlocale(locale) {
locale = typeof(locale) === "undefined" ? "en_US" : locale;
if((cldr && (cldr.localeIds.indexOf(locale.replace(/-/g, '_').toLowerCase()) === -1)) || (!cldr && ((locale.replace(/-/g, '_').toLowerCase() !== "en_us")))) {
throw new IllegalLocaleError();
}
this.day_name = _extractLocaleDays(false, locale);
this.day_abbr = _extractLocaleDays(true, locale);
this.month_name = _extractLocaleMonths(false, locale);
this.month_abbr = _extractLocaleMonths(true, locale);
} | [
"function",
"setlocale",
"(",
"locale",
")",
"{",
"locale",
"=",
"typeof",
"(",
"locale",
")",
"===",
"\"undefined\"",
"?",
"\"en_US\"",
":",
"locale",
";",
"if",
"(",
"(",
"cldr",
"&&",
"(",
"cldr",
".",
"localeIds",
".",
"indexOf",
"(",
"locale",
".",
"replace",
"(",
"/",
"-",
"/",
"g",
",",
"'_'",
")",
".",
"toLowerCase",
"(",
")",
")",
"===",
"-",
"1",
")",
")",
"||",
"(",
"!",
"cldr",
"&&",
"(",
"(",
"locale",
".",
"replace",
"(",
"/",
"-",
"/",
"g",
",",
"'_'",
")",
".",
"toLowerCase",
"(",
")",
"!==",
"\"en_us\"",
")",
")",
")",
")",
"{",
"throw",
"new",
"IllegalLocaleError",
"(",
")",
";",
"}",
"this",
".",
"day_name",
"=",
"_extractLocaleDays",
"(",
"false",
",",
"locale",
")",
";",
"this",
".",
"day_abbr",
"=",
"_extractLocaleDays",
"(",
"true",
",",
"locale",
")",
";",
"this",
".",
"month_name",
"=",
"_extractLocaleMonths",
"(",
"false",
",",
"locale",
")",
";",
"this",
".",
"month_abbr",
"=",
"_extractLocaleMonths",
"(",
"true",
",",
"locale",
")",
";",
"}"
]
| Sets the locale for use in extracting month and weekday names.
@param {String} locale
@throws {IllegalLocaleError} If the provided locale is invalid.
@api public | [
"Sets",
"the",
"locale",
"for",
"use",
"in",
"extracting",
"month",
"and",
"weekday",
"names",
"."
]
| aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0 | https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L132-L143 | train |
ArminTamzarian/node-calendar | node-calendar.js | timegm | function timegm(timegmt) {
var year = timegmt[0];
var month = timegmt[1];
var day = timegmt[2];
var hour = timegmt[3];
var minute = timegmt[4];
var second = timegmt[5];
if(month < 1 || month > 12) {
throw new IllegalMonthError();
}
if(day < 1 || day > (_DAYS_IN_MONTH[month] + (month === 2 && isleap(year)))) {
throw new IllegalDayError();
}
if(hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) {
throw new IllegalTimeError();
}
var days = _toordinal(year, month, 1) - 719163 + day - 1;
var hours = (days * 24) + hour;
var minutes = (hours * 60) + minute;
var seconds = (minutes * 60) + second;
return seconds;
} | javascript | function timegm(timegmt) {
var year = timegmt[0];
var month = timegmt[1];
var day = timegmt[2];
var hour = timegmt[3];
var minute = timegmt[4];
var second = timegmt[5];
if(month < 1 || month > 12) {
throw new IllegalMonthError();
}
if(day < 1 || day > (_DAYS_IN_MONTH[month] + (month === 2 && isleap(year)))) {
throw new IllegalDayError();
}
if(hour < 0 || hour > 23 || minute < 0 || minute > 59 || second < 0 || second > 59) {
throw new IllegalTimeError();
}
var days = _toordinal(year, month, 1) - 719163 + day - 1;
var hours = (days * 24) + hour;
var minutes = (hours * 60) + minute;
var seconds = (minutes * 60) + second;
return seconds;
} | [
"function",
"timegm",
"(",
"timegmt",
")",
"{",
"var",
"year",
"=",
"timegmt",
"[",
"0",
"]",
";",
"var",
"month",
"=",
"timegmt",
"[",
"1",
"]",
";",
"var",
"day",
"=",
"timegmt",
"[",
"2",
"]",
";",
"var",
"hour",
"=",
"timegmt",
"[",
"3",
"]",
";",
"var",
"minute",
"=",
"timegmt",
"[",
"4",
"]",
";",
"var",
"second",
"=",
"timegmt",
"[",
"5",
"]",
";",
"if",
"(",
"month",
"<",
"1",
"||",
"month",
">",
"12",
")",
"{",
"throw",
"new",
"IllegalMonthError",
"(",
")",
";",
"}",
"if",
"(",
"day",
"<",
"1",
"||",
"day",
">",
"(",
"_DAYS_IN_MONTH",
"[",
"month",
"]",
"+",
"(",
"month",
"===",
"2",
"&&",
"isleap",
"(",
"year",
")",
")",
")",
")",
"{",
"throw",
"new",
"IllegalDayError",
"(",
")",
";",
"}",
"if",
"(",
"hour",
"<",
"0",
"||",
"hour",
">",
"23",
"||",
"minute",
"<",
"0",
"||",
"minute",
">",
"59",
"||",
"second",
"<",
"0",
"||",
"second",
">",
"59",
")",
"{",
"throw",
"new",
"IllegalTimeError",
"(",
")",
";",
"}",
"var",
"days",
"=",
"_toordinal",
"(",
"year",
",",
"month",
",",
"1",
")",
"-",
"719163",
"+",
"day",
"-",
"1",
";",
"var",
"hours",
"=",
"(",
"days",
"*",
"24",
")",
"+",
"hour",
";",
"var",
"minutes",
"=",
"(",
"hours",
"*",
"60",
")",
"+",
"minute",
";",
"var",
"seconds",
"=",
"(",
"minutes",
"*",
"60",
")",
"+",
"second",
";",
"return",
"seconds",
";",
"}"
]
| Unrelated but handy function to calculate Unix timestamp from GMT.
@param {Array} tuple
@throws {IllegalMonthError} If the provided month element is invalid.
@throws {IllegalDayError} If the provided day element is invalid.
@api public | [
"Unrelated",
"but",
"handy",
"function",
"to",
"calculate",
"Unix",
"timestamp",
"from",
"GMT",
"."
]
| aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0 | https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L153-L179 | train |
ArminTamzarian/node-calendar | node-calendar.js | Calendar | function Calendar(firstweekday) {
this._firstweekday = typeof(firstweekday) === "undefined" ? 0 : firstweekday;
if(firstweekday < 0 || firstweekday > 6) {
throw new IllegalWeekdayError();
}
this._oneday = 1000 * 60 * 60 * 24;
this._onehour = 1000 * 60 * 60;
} | javascript | function Calendar(firstweekday) {
this._firstweekday = typeof(firstweekday) === "undefined" ? 0 : firstweekday;
if(firstweekday < 0 || firstweekday > 6) {
throw new IllegalWeekdayError();
}
this._oneday = 1000 * 60 * 60 * 24;
this._onehour = 1000 * 60 * 60;
} | [
"function",
"Calendar",
"(",
"firstweekday",
")",
"{",
"this",
".",
"_firstweekday",
"=",
"typeof",
"(",
"firstweekday",
")",
"===",
"\"undefined\"",
"?",
"0",
":",
"firstweekday",
";",
"if",
"(",
"firstweekday",
"<",
"0",
"||",
"firstweekday",
">",
"6",
")",
"{",
"throw",
"new",
"IllegalWeekdayError",
"(",
")",
";",
"}",
"this",
".",
"_oneday",
"=",
"1000",
"*",
"60",
"*",
"60",
"*",
"24",
";",
"this",
".",
"_onehour",
"=",
"1000",
"*",
"60",
"*",
"60",
";",
"}"
]
| Base calendar class. This class doesn't do any formatting. It simply
provides data to subclasses.
@param {Number} firstweekday
@throws {IllegalWeekdayError} If the provided firstweekday is invalid.
@api public | [
"Base",
"calendar",
"class",
".",
"This",
"class",
"doesn",
"t",
"do",
"any",
"formatting",
".",
"It",
"simply",
"provides",
"data",
"to",
"subclasses",
"."
]
| aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0 | https://github.com/ArminTamzarian/node-calendar/blob/aa18f79b3e0dc0541688dbfc1c2fea1bddd8b0d0/node-calendar.js#L214-L223 | train |
graphql-factory/graphql-factory | archive/refactoring/subscription/resolver.js | defaultClientIDHandler | function defaultClientIDHandler(args, context, info) {
return get(args, [ 'clientID' ]) ||
get(context, [ 'clientID' ]) ||
get(info, [ 'rootValue', 'clientID' ]);
} | javascript | function defaultClientIDHandler(args, context, info) {
return get(args, [ 'clientID' ]) ||
get(context, [ 'clientID' ]) ||
get(info, [ 'rootValue', 'clientID' ]);
} | [
"function",
"defaultClientIDHandler",
"(",
"args",
",",
"context",
",",
"info",
")",
"{",
"return",
"get",
"(",
"args",
",",
"[",
"'clientID'",
"]",
")",
"||",
"get",
"(",
"context",
",",
"[",
"'clientID'",
"]",
")",
"||",
"get",
"(",
"info",
",",
"[",
"'rootValue'",
",",
"'clientID'",
"]",
")",
";",
"}"
]
| Default client id handler checks args then context
then rootValue for a clientID field to use
@param {*} args
@param {*} context
@param {*} info | [
"Default",
"client",
"id",
"handler",
"checks",
"args",
"then",
"context",
"then",
"rootValue",
"for",
"a",
"clientID",
"field",
"to",
"use"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/refactoring/subscription/resolver.js#L11-L15 | train |
jrmerz/leaflet-canvas-geojson | src/lib/toCanvasXY.js | trimCanvasXY | function trimCanvasXY(xy) {
if( xy.length === 0 ) return;
var last = xy[xy.length-1], i, point;
var c = 0;
for( i = xy.length-2; i >= 0; i-- ) {
point = xy[i];
if( Math.abs(last.x - point.x) === 0 && Math.abs(last.y - point.y) === 0 ) {
xy.splice(i, 1);
c++;
} else {
last = point;
}
}
if( xy.length <= 1 ) {
xy.push(last);
c--;
}
} | javascript | function trimCanvasXY(xy) {
if( xy.length === 0 ) return;
var last = xy[xy.length-1], i, point;
var c = 0;
for( i = xy.length-2; i >= 0; i-- ) {
point = xy[i];
if( Math.abs(last.x - point.x) === 0 && Math.abs(last.y - point.y) === 0 ) {
xy.splice(i, 1);
c++;
} else {
last = point;
}
}
if( xy.length <= 1 ) {
xy.push(last);
c--;
}
} | [
"function",
"trimCanvasXY",
"(",
"xy",
")",
"{",
"if",
"(",
"xy",
".",
"length",
"===",
"0",
")",
"return",
";",
"var",
"last",
"=",
"xy",
"[",
"xy",
".",
"length",
"-",
"1",
"]",
",",
"i",
",",
"point",
";",
"var",
"c",
"=",
"0",
";",
"for",
"(",
"i",
"=",
"xy",
".",
"length",
"-",
"2",
";",
"i",
">=",
"0",
";",
"i",
"--",
")",
"{",
"point",
"=",
"xy",
"[",
"i",
"]",
";",
"if",
"(",
"Math",
".",
"abs",
"(",
"last",
".",
"x",
"-",
"point",
".",
"x",
")",
"===",
"0",
"&&",
"Math",
".",
"abs",
"(",
"last",
".",
"y",
"-",
"point",
".",
"y",
")",
"===",
"0",
")",
"{",
"xy",
".",
"splice",
"(",
"i",
",",
"1",
")",
";",
"c",
"++",
";",
"}",
"else",
"{",
"last",
"=",
"point",
";",
"}",
"}",
"if",
"(",
"xy",
".",
"length",
"<=",
"1",
")",
"{",
"xy",
".",
"push",
"(",
"last",
")",
";",
"c",
"--",
";",
"}",
"}"
]
| given an array of geo xy coordinates, make sure each point is at least more than 1px apart | [
"given",
"an",
"array",
"of",
"geo",
"xy",
"coordinates",
"make",
"sure",
"each",
"point",
"is",
"at",
"least",
"more",
"than",
"1px",
"apart"
]
| 39ccf82d6ee89684b3f5c826c013210dad954d8f | https://github.com/jrmerz/leaflet-canvas-geojson/blob/39ccf82d6ee89684b3f5c826c013210dad954d8f/src/lib/toCanvasXY.js#L45-L64 | train |
dundalek/warehouse | backend/base.js | function(backend, name, options) {
options = _.extend({keyPath: 'id'}, options || {});
this.options = options;
this.backend = backend;
this.name = name;
this.keyPath = this.options.keyPath;
} | javascript | function(backend, name, options) {
options = _.extend({keyPath: 'id'}, options || {});
this.options = options;
this.backend = backend;
this.name = name;
this.keyPath = this.options.keyPath;
} | [
"function",
"(",
"backend",
",",
"name",
",",
"options",
")",
"{",
"options",
"=",
"_",
".",
"extend",
"(",
"{",
"keyPath",
":",
"'id'",
"}",
",",
"options",
"||",
"{",
"}",
")",
";",
"this",
".",
"options",
"=",
"options",
";",
"this",
".",
"backend",
"=",
"backend",
";",
"this",
".",
"name",
"=",
"name",
";",
"this",
".",
"keyPath",
"=",
"this",
".",
"options",
".",
"keyPath",
";",
"}"
]
| Initialize the backend instance
@constructs | [
"Initialize",
"the",
"backend",
"instance"
]
| d5a964a5997c28170dc907ad91b80ea3cb049faa | https://github.com/dundalek/warehouse/blob/d5a964a5997c28170dc907ad91b80ea3cb049faa/backend/base.js#L65-L72 | train |
|
graphql-factory/graphql-factory | archive/src-concept/generate/middleware.js | resolverMiddleware | function resolverMiddleware (resolver) {
return function (req, res, next) {
try {
const { source, args, context, info } = req
const ctx = { req, res, next }
const value = resolver.call(ctx, source, args, context, info)
return Promise.resolve(value)
.then(result => {
req.result = result
return next()
})
.catch(next)
} catch (err) {
return next(err)
}
}
} | javascript | function resolverMiddleware (resolver) {
return function (req, res, next) {
try {
const { source, args, context, info } = req
const ctx = { req, res, next }
const value = resolver.call(ctx, source, args, context, info)
return Promise.resolve(value)
.then(result => {
req.result = result
return next()
})
.catch(next)
} catch (err) {
return next(err)
}
}
} | [
"function",
"resolverMiddleware",
"(",
"resolver",
")",
"{",
"return",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"try",
"{",
"const",
"{",
"source",
",",
"args",
",",
"context",
",",
"info",
"}",
"=",
"req",
"const",
"ctx",
"=",
"{",
"req",
",",
"res",
",",
"next",
"}",
"const",
"value",
"=",
"resolver",
".",
"call",
"(",
"ctx",
",",
"source",
",",
"args",
",",
"context",
",",
"info",
")",
"return",
"Promise",
".",
"resolve",
"(",
"value",
")",
".",
"then",
"(",
"result",
"=>",
"{",
"req",
".",
"result",
"=",
"result",
"return",
"next",
"(",
")",
"}",
")",
".",
"catch",
"(",
"next",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
"}",
"}",
"}"
]
| Wraps the resolver function in middleware so that it can be
added to a middleware queue and processed the same way as
other middleware
@param resolver
@returns {Function} | [
"Wraps",
"the",
"resolver",
"function",
"in",
"middleware",
"so",
"that",
"it",
"can",
"be",
"added",
"to",
"a",
"middleware",
"queue",
"and",
"processed",
"the",
"same",
"way",
"as",
"other",
"middleware"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/src-concept/generate/middleware.js#L18-L35 | train |
graphql-factory/graphql-factory | archive/src-concept/generate/middleware.js | nextMiddleware | function nextMiddleware (factory, mw, info) {
const {
resolved,
index,
routes,
middlewares,
errorMiddleware,
req,
res,
metrics
} = info
const local = {
finished: false,
timeout: null
}
// check if the request has already been resolved
if (resolved) return
// get the current middleware
const current = mw[index]
const exec = {
name: current.functionName,
started: Date.now(),
ended: null,
data: null
}
metrics.executions.push(exec)
// create a next method
const next = data => {
clearTimeout(local.timeout)
if (local.finished || info.resolved) return
local.finished = true
// add the result
exec.ended = Date.now()
exec.data = data
// allow reroutes to valid named route paths
if (_.isString(data)) {
const route = routes[data]
if (!route) {
if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
info.index = 0
req.error = new Error(`No route found for "${data}"`)
return nextMiddleware(factory, errorMiddleware, info)
}
res.end(data)
}
// get the correct route set
const mwSet = route.type === ERROR_MIDDLEWARE
? errorMiddleware
: middlewares
// increment the re-route counter, set the index and go
req.reroutes += 1
info.index = route.index
return nextMiddleware(factory, mwSet, info)
}
// check for an error passed to the next method and not
// already in the error middleware chain. if condition met
// start processing error middleware
if (data instanceof Error) {
if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
info.index = 0
req.error = data
return nextMiddleware(factory, errorMiddleware, info)
}
res.end(data)
}
// check if there is any more middleware in the chain
// if not, call end to complete the request
return info.index === mw.length
? res.end()
: nextMiddleware(factory, mw, info)
}
// create a timeout for the middleware if timeout > 0
if (current.timeout > 0) {
local.timeout = setTimeout(() => {
local.finished = true
req.error = new Error(current.functionName
+ ' middleware timed out')
// add the result
exec.ended = Date.now()
exec.data = req.error
// if already in error middleware and timed out
// end the entire request, othewise move to error mw
if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
info.index = 0
return nextMiddleware(factory, errorMiddleware, info)
}
return res.end()
}, current.timeout)
}
// try to execute the resolver and if unable
// move to error middleware. if already in error
// middleware end the request
try {
info.index += 1
current.resolver(req, res, next)
} catch (err) {
clearTimeout(local.timeout)
local.finished = true
factory.emit(EVENT_ERROR, err)
req.error = err
// add the result
exec.ended = Date.now()
exec.data = req.error
if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
info.index = 0
return nextMiddleware(factory, errorMiddleware, info)
}
return res.end()
}
} | javascript | function nextMiddleware (factory, mw, info) {
const {
resolved,
index,
routes,
middlewares,
errorMiddleware,
req,
res,
metrics
} = info
const local = {
finished: false,
timeout: null
}
// check if the request has already been resolved
if (resolved) return
// get the current middleware
const current = mw[index]
const exec = {
name: current.functionName,
started: Date.now(),
ended: null,
data: null
}
metrics.executions.push(exec)
// create a next method
const next = data => {
clearTimeout(local.timeout)
if (local.finished || info.resolved) return
local.finished = true
// add the result
exec.ended = Date.now()
exec.data = data
// allow reroutes to valid named route paths
if (_.isString(data)) {
const route = routes[data]
if (!route) {
if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
info.index = 0
req.error = new Error(`No route found for "${data}"`)
return nextMiddleware(factory, errorMiddleware, info)
}
res.end(data)
}
// get the correct route set
const mwSet = route.type === ERROR_MIDDLEWARE
? errorMiddleware
: middlewares
// increment the re-route counter, set the index and go
req.reroutes += 1
info.index = route.index
return nextMiddleware(factory, mwSet, info)
}
// check for an error passed to the next method and not
// already in the error middleware chain. if condition met
// start processing error middleware
if (data instanceof Error) {
if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
info.index = 0
req.error = data
return nextMiddleware(factory, errorMiddleware, info)
}
res.end(data)
}
// check if there is any more middleware in the chain
// if not, call end to complete the request
return info.index === mw.length
? res.end()
: nextMiddleware(factory, mw, info)
}
// create a timeout for the middleware if timeout > 0
if (current.timeout > 0) {
local.timeout = setTimeout(() => {
local.finished = true
req.error = new Error(current.functionName
+ ' middleware timed out')
// add the result
exec.ended = Date.now()
exec.data = req.error
// if already in error middleware and timed out
// end the entire request, othewise move to error mw
if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
info.index = 0
return nextMiddleware(factory, errorMiddleware, info)
}
return res.end()
}, current.timeout)
}
// try to execute the resolver and if unable
// move to error middleware. if already in error
// middleware end the request
try {
info.index += 1
current.resolver(req, res, next)
} catch (err) {
clearTimeout(local.timeout)
local.finished = true
factory.emit(EVENT_ERROR, err)
req.error = err
// add the result
exec.ended = Date.now()
exec.data = req.error
if (current.type !== ERROR_MIDDLEWARE && errorMiddleware.length) {
info.index = 0
return nextMiddleware(factory, errorMiddleware, info)
}
return res.end()
}
} | [
"function",
"nextMiddleware",
"(",
"factory",
",",
"mw",
",",
"info",
")",
"{",
"const",
"{",
"resolved",
",",
"index",
",",
"routes",
",",
"middlewares",
",",
"errorMiddleware",
",",
"req",
",",
"res",
",",
"metrics",
"}",
"=",
"info",
"const",
"local",
"=",
"{",
"finished",
":",
"false",
",",
"timeout",
":",
"null",
"}",
"if",
"(",
"resolved",
")",
"return",
"const",
"current",
"=",
"mw",
"[",
"index",
"]",
"const",
"exec",
"=",
"{",
"name",
":",
"current",
".",
"functionName",
",",
"started",
":",
"Date",
".",
"now",
"(",
")",
",",
"ended",
":",
"null",
",",
"data",
":",
"null",
"}",
"metrics",
".",
"executions",
".",
"push",
"(",
"exec",
")",
"const",
"next",
"=",
"data",
"=>",
"{",
"clearTimeout",
"(",
"local",
".",
"timeout",
")",
"if",
"(",
"local",
".",
"finished",
"||",
"info",
".",
"resolved",
")",
"return",
"local",
".",
"finished",
"=",
"true",
"exec",
".",
"ended",
"=",
"Date",
".",
"now",
"(",
")",
"exec",
".",
"data",
"=",
"data",
"if",
"(",
"_",
".",
"isString",
"(",
"data",
")",
")",
"{",
"const",
"route",
"=",
"routes",
"[",
"data",
"]",
"if",
"(",
"!",
"route",
")",
"{",
"if",
"(",
"current",
".",
"type",
"!==",
"ERROR_MIDDLEWARE",
"&&",
"errorMiddleware",
".",
"length",
")",
"{",
"info",
".",
"index",
"=",
"0",
"req",
".",
"error",
"=",
"new",
"Error",
"(",
"`",
"${",
"data",
"}",
"`",
")",
"return",
"nextMiddleware",
"(",
"factory",
",",
"errorMiddleware",
",",
"info",
")",
"}",
"res",
".",
"end",
"(",
"data",
")",
"}",
"const",
"mwSet",
"=",
"route",
".",
"type",
"===",
"ERROR_MIDDLEWARE",
"?",
"errorMiddleware",
":",
"middlewares",
"req",
".",
"reroutes",
"+=",
"1",
"info",
".",
"index",
"=",
"route",
".",
"index",
"return",
"nextMiddleware",
"(",
"factory",
",",
"mwSet",
",",
"info",
")",
"}",
"if",
"(",
"data",
"instanceof",
"Error",
")",
"{",
"if",
"(",
"current",
".",
"type",
"!==",
"ERROR_MIDDLEWARE",
"&&",
"errorMiddleware",
".",
"length",
")",
"{",
"info",
".",
"index",
"=",
"0",
"req",
".",
"error",
"=",
"data",
"return",
"nextMiddleware",
"(",
"factory",
",",
"errorMiddleware",
",",
"info",
")",
"}",
"res",
".",
"end",
"(",
"data",
")",
"}",
"return",
"info",
".",
"index",
"===",
"mw",
".",
"length",
"?",
"res",
".",
"end",
"(",
")",
":",
"nextMiddleware",
"(",
"factory",
",",
"mw",
",",
"info",
")",
"}",
"if",
"(",
"current",
".",
"timeout",
">",
"0",
")",
"{",
"local",
".",
"timeout",
"=",
"setTimeout",
"(",
"(",
")",
"=>",
"{",
"local",
".",
"finished",
"=",
"true",
"req",
".",
"error",
"=",
"new",
"Error",
"(",
"current",
".",
"functionName",
"+",
"' middleware timed out'",
")",
"exec",
".",
"ended",
"=",
"Date",
".",
"now",
"(",
")",
"exec",
".",
"data",
"=",
"req",
".",
"error",
"if",
"(",
"current",
".",
"type",
"!==",
"ERROR_MIDDLEWARE",
"&&",
"errorMiddleware",
".",
"length",
")",
"{",
"info",
".",
"index",
"=",
"0",
"return",
"nextMiddleware",
"(",
"factory",
",",
"errorMiddleware",
",",
"info",
")",
"}",
"return",
"res",
".",
"end",
"(",
")",
"}",
",",
"current",
".",
"timeout",
")",
"}",
"try",
"{",
"info",
".",
"index",
"+=",
"1",
"current",
".",
"resolver",
"(",
"req",
",",
"res",
",",
"next",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"clearTimeout",
"(",
"local",
".",
"timeout",
")",
"local",
".",
"finished",
"=",
"true",
"factory",
".",
"emit",
"(",
"EVENT_ERROR",
",",
"err",
")",
"req",
".",
"error",
"=",
"err",
"exec",
".",
"ended",
"=",
"Date",
".",
"now",
"(",
")",
"exec",
".",
"data",
"=",
"req",
".",
"error",
"if",
"(",
"current",
".",
"type",
"!==",
"ERROR_MIDDLEWARE",
"&&",
"errorMiddleware",
".",
"length",
")",
"{",
"info",
".",
"index",
"=",
"0",
"return",
"nextMiddleware",
"(",
"factory",
",",
"errorMiddleware",
",",
"info",
")",
"}",
"return",
"res",
".",
"end",
"(",
")",
"}",
"}"
]
| Processes the next middleware in the queue
@param mw
@param info
@returns {*} | [
"Processes",
"the",
"next",
"middleware",
"in",
"the",
"queue"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/src-concept/generate/middleware.js#L43-L169 | train |
graphql-factory/graphql-factory | archive/v2/example/example.js | function (source, args, context, info) {
// console.log(this.utils.getRootFieldDef(info, '_tableName'))
let typeName = this.utils.getReturnTypeName(info)
let db = this.globals.db.main
let config = db.tables[typeName]
let cursor = db.cursor
return cursor.db(config.db).table(config.table).run()
} | javascript | function (source, args, context, info) {
// console.log(this.utils.getRootFieldDef(info, '_tableName'))
let typeName = this.utils.getReturnTypeName(info)
let db = this.globals.db.main
let config = db.tables[typeName]
let cursor = db.cursor
return cursor.db(config.db).table(config.table).run()
} | [
"function",
"(",
"source",
",",
"args",
",",
"context",
",",
"info",
")",
"{",
"let",
"typeName",
"=",
"this",
".",
"utils",
".",
"getReturnTypeName",
"(",
"info",
")",
"let",
"db",
"=",
"this",
".",
"globals",
".",
"db",
".",
"main",
"let",
"config",
"=",
"db",
".",
"tables",
"[",
"typeName",
"]",
"let",
"cursor",
"=",
"db",
".",
"cursor",
"return",
"cursor",
".",
"db",
"(",
"config",
".",
"db",
")",
".",
"table",
"(",
"config",
".",
"table",
")",
".",
"run",
"(",
")",
"}"
]
| get user list | [
"get",
"user",
"list"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/v2/example/example.js#L42-L51 | train |
|
dundalek/warehouse | backend/fs.js | function() {
var self = this;
return Q.ninvoke(fs, 'readdir', path.join(this.backend.options.path, this.name))
.then(function(files) {
return Q.all(files.map(function(f) {
return self.delete(f);
}));
})
.then(function() {
return true;
});
} | javascript | function() {
var self = this;
return Q.ninvoke(fs, 'readdir', path.join(this.backend.options.path, this.name))
.then(function(files) {
return Q.all(files.map(function(f) {
return self.delete(f);
}));
})
.then(function() {
return true;
});
} | [
"function",
"(",
")",
"{",
"var",
"self",
"=",
"this",
";",
"return",
"Q",
".",
"ninvoke",
"(",
"fs",
",",
"'readdir'",
",",
"path",
".",
"join",
"(",
"this",
".",
"backend",
".",
"options",
".",
"path",
",",
"this",
".",
"name",
")",
")",
".",
"then",
"(",
"function",
"(",
"files",
")",
"{",
"return",
"Q",
".",
"all",
"(",
"files",
".",
"map",
"(",
"function",
"(",
"f",
")",
"{",
"return",
"self",
".",
"delete",
"(",
"f",
")",
";",
"}",
")",
")",
";",
"}",
")",
".",
"then",
"(",
"function",
"(",
")",
"{",
"return",
"true",
";",
"}",
")",
";",
"}"
]
| Delete all items | [
"Delete",
"all",
"items"
]
| d5a964a5997c28170dc907ad91b80ea3cb049faa | https://github.com/dundalek/warehouse/blob/d5a964a5997c28170dc907ad91b80ea3cb049faa/backend/fs.js#L131-L142 | train |
|
dundalek/warehouse | backend/fs.js | function(file) {
return path.join(this.backend.options.path, this.name, ''+path.basename(file));
} | javascript | function(file) {
return path.join(this.backend.options.path, this.name, ''+path.basename(file));
} | [
"function",
"(",
"file",
")",
"{",
"return",
"path",
".",
"join",
"(",
"this",
".",
"backend",
".",
"options",
".",
"path",
",",
"this",
".",
"name",
",",
"''",
"+",
"path",
".",
"basename",
"(",
"file",
")",
")",
";",
"}"
]
| Get absolute filename for given key | [
"Get",
"absolute",
"filename",
"for",
"given",
"key"
]
| d5a964a5997c28170dc907ad91b80ea3cb049faa | https://github.com/dundalek/warehouse/blob/d5a964a5997c28170dc907ad91b80ea3cb049faa/backend/fs.js#L145-L147 | train |
|
graphql-factory/graphql-factory | src-old/definition/definition.js | filterStore | function filterStore(operation, store, args) {
const filter = obj => {
switch (operation) {
case 'omit':
return _.isFunction(args[0])
? _.omitBy(obj, args[0])
: _.omit(obj, args);
case 'pick':
return _.isFunction(args[0])
? _.pickBy(obj, args[0])
: _.pick(obj, args);
default:
break;
}
};
switch (store) {
case 'context':
case 'functions':
case 'directives':
case 'plugins':
case 'types':
_.set(this, `_${store}`, filter(_.get(this, `_${store}`)));
break;
default:
assert(false, `invalid store for ${operation} operation`);
break;
}
return this;
} | javascript | function filterStore(operation, store, args) {
const filter = obj => {
switch (operation) {
case 'omit':
return _.isFunction(args[0])
? _.omitBy(obj, args[0])
: _.omit(obj, args);
case 'pick':
return _.isFunction(args[0])
? _.pickBy(obj, args[0])
: _.pick(obj, args);
default:
break;
}
};
switch (store) {
case 'context':
case 'functions':
case 'directives':
case 'plugins':
case 'types':
_.set(this, `_${store}`, filter(_.get(this, `_${store}`)));
break;
default:
assert(false, `invalid store for ${operation} operation`);
break;
}
return this;
} | [
"function",
"filterStore",
"(",
"operation",
",",
"store",
",",
"args",
")",
"{",
"const",
"filter",
"=",
"obj",
"=>",
"{",
"switch",
"(",
"operation",
")",
"{",
"case",
"'omit'",
":",
"return",
"_",
".",
"isFunction",
"(",
"args",
"[",
"0",
"]",
")",
"?",
"_",
".",
"omitBy",
"(",
"obj",
",",
"args",
"[",
"0",
"]",
")",
":",
"_",
".",
"omit",
"(",
"obj",
",",
"args",
")",
";",
"case",
"'pick'",
":",
"return",
"_",
".",
"isFunction",
"(",
"args",
"[",
"0",
"]",
")",
"?",
"_",
".",
"pickBy",
"(",
"obj",
",",
"args",
"[",
"0",
"]",
")",
":",
"_",
".",
"pick",
"(",
"obj",
",",
"args",
")",
";",
"default",
":",
"break",
";",
"}",
"}",
";",
"switch",
"(",
"store",
")",
"{",
"case",
"'context'",
":",
"case",
"'functions'",
":",
"case",
"'directives'",
":",
"case",
"'plugins'",
":",
"case",
"'types'",
":",
"_",
".",
"set",
"(",
"this",
",",
"`",
"${",
"store",
"}",
"`",
",",
"filter",
"(",
"_",
".",
"get",
"(",
"this",
",",
"`",
"${",
"store",
"}",
"`",
")",
")",
")",
";",
"break",
";",
"default",
":",
"assert",
"(",
"false",
",",
"`",
"${",
"operation",
"}",
"`",
")",
";",
"break",
";",
"}",
"return",
"this",
";",
"}"
]
| performs a filter operation on a specified store
@param {*} operation
@param {*} store
@param {*} args | [
"performs",
"a",
"filter",
"operation",
"on",
"a",
"specified",
"store"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/src-old/definition/definition.js#L91-L119 | train |
graphql-factory/graphql-factory | archive/refactoring/definition/merge.js | defaultConflictResolution | function defaultConflictResolution(definition, name, type, tgt, src) {
// TODO: Add support for type/field level conflict settings
// TODO: Add support for extending types via extend key
switch(type) {
case 'type':
const {
query,
mutation,
subscription
} = get(definition, [ 'schema' ]) || {};
// always merge a rootTypes definition
if ([ query, mutation, subscription].indexOf(name) !== -1) {
return { name, config: merge(tgt, src) };
}
break;
case 'function':
return { name, config: Object.assign(tgt, src) };
case 'context':
return { name, config: merge(tgt, src) };
default:
break;
}
// emit a warning
definition.emit(FactoryEvent.WARN, 'MergeConflict: Duplicate ' + type +
' with name "' + name + '" found. Using newer value');
return { name, config: tgt };
} | javascript | function defaultConflictResolution(definition, name, type, tgt, src) {
// TODO: Add support for type/field level conflict settings
// TODO: Add support for extending types via extend key
switch(type) {
case 'type':
const {
query,
mutation,
subscription
} = get(definition, [ 'schema' ]) || {};
// always merge a rootTypes definition
if ([ query, mutation, subscription].indexOf(name) !== -1) {
return { name, config: merge(tgt, src) };
}
break;
case 'function':
return { name, config: Object.assign(tgt, src) };
case 'context':
return { name, config: merge(tgt, src) };
default:
break;
}
// emit a warning
definition.emit(FactoryEvent.WARN, 'MergeConflict: Duplicate ' + type +
' with name "' + name + '" found. Using newer value');
return { name, config: tgt };
} | [
"function",
"defaultConflictResolution",
"(",
"definition",
",",
"name",
",",
"type",
",",
"tgt",
",",
"src",
")",
"{",
"switch",
"(",
"type",
")",
"{",
"case",
"'type'",
":",
"const",
"{",
"query",
",",
"mutation",
",",
"subscription",
"}",
"=",
"get",
"(",
"definition",
",",
"[",
"'schema'",
"]",
")",
"||",
"{",
"}",
";",
"if",
"(",
"[",
"query",
",",
"mutation",
",",
"subscription",
"]",
".",
"indexOf",
"(",
"name",
")",
"!==",
"-",
"1",
")",
"{",
"return",
"{",
"name",
",",
"config",
":",
"merge",
"(",
"tgt",
",",
"src",
")",
"}",
";",
"}",
"break",
";",
"case",
"'function'",
":",
"return",
"{",
"name",
",",
"config",
":",
"Object",
".",
"assign",
"(",
"tgt",
",",
"src",
")",
"}",
";",
"case",
"'context'",
":",
"return",
"{",
"name",
",",
"config",
":",
"merge",
"(",
"tgt",
",",
"src",
")",
"}",
";",
"default",
":",
"break",
";",
"}",
"definition",
".",
"emit",
"(",
"FactoryEvent",
".",
"WARN",
",",
"'MergeConflict: Duplicate '",
"+",
"type",
"+",
"' with name \"'",
"+",
"name",
"+",
"'\" found. Using newer value'",
")",
";",
"return",
"{",
"name",
",",
"config",
":",
"tgt",
"}",
";",
"}"
]
| Default conflict resolver for merging root types, context, and overwriting
parts of type definitions
@param {*} definition
@param {*} name
@param {*} type
@param {*} tgt
@param {*} src | [
"Default",
"conflict",
"resolver",
"for",
"merging",
"root",
"types",
"context",
"and",
"overwriting",
"parts",
"of",
"type",
"definitions"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/refactoring/definition/merge.js#L32-L58 | train |
graphql-factory/graphql-factory | archive/refactoring/definition/merge.js | handleConflict | function handleConflict(definition, method, name, type, tgt, src) {
const _method = method ?
method :
defaultConflictResolution;
// allow the method to be a function that returns the new name
// and type configuration
if (typeof _method === 'function') {
return _method(definition, name, type, tgt, src);
}
switch (_method) {
// merges the target and source configurations
case NameConflictResolution.MERGE:
return { name, config: merge(tgt, src) };
// throws an error
case NameConflictResolution.ERROR:
throw new Error('Duplicate ' + type + ' name "' + name +
'" is not allowed ' + 'when conflict is set to ' +
NameConflictResolution.ERROR);
// prints a warning and then overwrites the existing type definition
case NameConflictResolution.WARN:
definition.emit(FactoryEvent.WARN, 'GraphQLFactoryWarning: duplicate ' +
'type name "' + name + '" found. Merging ' + type +
' configuration')
return { name, config: merge(tgt, src) };
// ignores the definition
case NameConflictResolution.SKIP:
return { name, config: tgt };
// silently overwrites the value
case NameConflictResolution.OVERWRITE:
return { name, config: src };
default:
throw new Error('Invalid name conflict resolution');
}
} | javascript | function handleConflict(definition, method, name, type, tgt, src) {
const _method = method ?
method :
defaultConflictResolution;
// allow the method to be a function that returns the new name
// and type configuration
if (typeof _method === 'function') {
return _method(definition, name, type, tgt, src);
}
switch (_method) {
// merges the target and source configurations
case NameConflictResolution.MERGE:
return { name, config: merge(tgt, src) };
// throws an error
case NameConflictResolution.ERROR:
throw new Error('Duplicate ' + type + ' name "' + name +
'" is not allowed ' + 'when conflict is set to ' +
NameConflictResolution.ERROR);
// prints a warning and then overwrites the existing type definition
case NameConflictResolution.WARN:
definition.emit(FactoryEvent.WARN, 'GraphQLFactoryWarning: duplicate ' +
'type name "' + name + '" found. Merging ' + type +
' configuration')
return { name, config: merge(tgt, src) };
// ignores the definition
case NameConflictResolution.SKIP:
return { name, config: tgt };
// silently overwrites the value
case NameConflictResolution.OVERWRITE:
return { name, config: src };
default:
throw new Error('Invalid name conflict resolution');
}
} | [
"function",
"handleConflict",
"(",
"definition",
",",
"method",
",",
"name",
",",
"type",
",",
"tgt",
",",
"src",
")",
"{",
"const",
"_method",
"=",
"method",
"?",
"method",
":",
"defaultConflictResolution",
";",
"if",
"(",
"typeof",
"_method",
"===",
"'function'",
")",
"{",
"return",
"_method",
"(",
"definition",
",",
"name",
",",
"type",
",",
"tgt",
",",
"src",
")",
";",
"}",
"switch",
"(",
"_method",
")",
"{",
"case",
"NameConflictResolution",
".",
"MERGE",
":",
"return",
"{",
"name",
",",
"config",
":",
"merge",
"(",
"tgt",
",",
"src",
")",
"}",
";",
"case",
"NameConflictResolution",
".",
"ERROR",
":",
"throw",
"new",
"Error",
"(",
"'Duplicate '",
"+",
"type",
"+",
"' name \"'",
"+",
"name",
"+",
"'\" is not allowed '",
"+",
"'when conflict is set to '",
"+",
"NameConflictResolution",
".",
"ERROR",
")",
";",
"case",
"NameConflictResolution",
".",
"WARN",
":",
"definition",
".",
"emit",
"(",
"FactoryEvent",
".",
"WARN",
",",
"'GraphQLFactoryWarning: duplicate '",
"+",
"'type name \"'",
"+",
"name",
"+",
"'\" found. Merging '",
"+",
"type",
"+",
"' configuration'",
")",
"return",
"{",
"name",
",",
"config",
":",
"merge",
"(",
"tgt",
",",
"src",
")",
"}",
";",
"case",
"NameConflictResolution",
".",
"SKIP",
":",
"return",
"{",
"name",
",",
"config",
":",
"tgt",
"}",
";",
"case",
"NameConflictResolution",
".",
"OVERWRITE",
":",
"return",
"{",
"name",
",",
"config",
":",
"src",
"}",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"'Invalid name conflict resolution'",
")",
";",
"}",
"}"
]
| Handles a type name conflict
returns an object containing the type name to use
and the type configuration to use.
@param {*} method
@param {*} name
@param {*} prefix | [
"Handles",
"a",
"type",
"name",
"conflict",
"returns",
"an",
"object",
"containing",
"the",
"type",
"name",
"to",
"use",
"and",
"the",
"type",
"configuration",
"to",
"use",
"."
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/refactoring/definition/merge.js#L68-L107 | train |
jrmerz/leaflet-canvas-geojson | src/defaultRenderer/index.js | render | function render(context, xyPoints, map, canvasFeature) {
ctx = context;
if( canvasFeature.type === 'Point' ) {
renderPoint(xyPoints, this.size);
} else if( canvasFeature.type === 'LineString' ) {
renderLine(xyPoints);
} else if( canvasFeature.type === 'Polygon' ) {
renderPolygon(xyPoints);
} else if( canvasFeature.type === 'MultiPolygon' ) {
xyPoints.forEach(renderPolygon);
}
} | javascript | function render(context, xyPoints, map, canvasFeature) {
ctx = context;
if( canvasFeature.type === 'Point' ) {
renderPoint(xyPoints, this.size);
} else if( canvasFeature.type === 'LineString' ) {
renderLine(xyPoints);
} else if( canvasFeature.type === 'Polygon' ) {
renderPolygon(xyPoints);
} else if( canvasFeature.type === 'MultiPolygon' ) {
xyPoints.forEach(renderPolygon);
}
} | [
"function",
"render",
"(",
"context",
",",
"xyPoints",
",",
"map",
",",
"canvasFeature",
")",
"{",
"ctx",
"=",
"context",
";",
"if",
"(",
"canvasFeature",
".",
"type",
"===",
"'Point'",
")",
"{",
"renderPoint",
"(",
"xyPoints",
",",
"this",
".",
"size",
")",
";",
"}",
"else",
"if",
"(",
"canvasFeature",
".",
"type",
"===",
"'LineString'",
")",
"{",
"renderLine",
"(",
"xyPoints",
")",
";",
"}",
"else",
"if",
"(",
"canvasFeature",
".",
"type",
"===",
"'Polygon'",
")",
"{",
"renderPolygon",
"(",
"xyPoints",
")",
";",
"}",
"else",
"if",
"(",
"canvasFeature",
".",
"type",
"===",
"'MultiPolygon'",
")",
"{",
"xyPoints",
".",
"forEach",
"(",
"renderPolygon",
")",
";",
"}",
"}"
]
| Fuction called in scope of CanvasFeature | [
"Fuction",
"called",
"in",
"scope",
"of",
"CanvasFeature"
]
| 39ccf82d6ee89684b3f5c826c013210dad954d8f | https://github.com/jrmerz/leaflet-canvas-geojson/blob/39ccf82d6ee89684b3f5c826c013210dad954d8f/src/defaultRenderer/index.js#L6-L18 | train |
jrmerz/leaflet-canvas-geojson | src/lib/intersects.js | intersects | function intersects(e) {
if( !this.showing ) return;
var dpp = this.getDegreesPerPx(e.latlng);
var mpp = this.getMetersPerPx(e.latlng);
var r = mpp * 5; // 5 px radius buffer;
var center = {
type : 'Point',
coordinates : [e.latlng.lng, e.latlng.lat]
};
var containerPoint = e.containerPoint;
var x1 = e.latlng.lng - dpp;
var x2 = e.latlng.lng + dpp;
var y1 = e.latlng.lat - dpp;
var y2 = e.latlng.lat + dpp;
var intersects = this.intersectsBbox([[x1, y1], [x2, y2]], r, center, containerPoint);
onIntersectsListCreated.call(this, e, intersects);
} | javascript | function intersects(e) {
if( !this.showing ) return;
var dpp = this.getDegreesPerPx(e.latlng);
var mpp = this.getMetersPerPx(e.latlng);
var r = mpp * 5; // 5 px radius buffer;
var center = {
type : 'Point',
coordinates : [e.latlng.lng, e.latlng.lat]
};
var containerPoint = e.containerPoint;
var x1 = e.latlng.lng - dpp;
var x2 = e.latlng.lng + dpp;
var y1 = e.latlng.lat - dpp;
var y2 = e.latlng.lat + dpp;
var intersects = this.intersectsBbox([[x1, y1], [x2, y2]], r, center, containerPoint);
onIntersectsListCreated.call(this, e, intersects);
} | [
"function",
"intersects",
"(",
"e",
")",
"{",
"if",
"(",
"!",
"this",
".",
"showing",
")",
"return",
";",
"var",
"dpp",
"=",
"this",
".",
"getDegreesPerPx",
"(",
"e",
".",
"latlng",
")",
";",
"var",
"mpp",
"=",
"this",
".",
"getMetersPerPx",
"(",
"e",
".",
"latlng",
")",
";",
"var",
"r",
"=",
"mpp",
"*",
"5",
";",
"var",
"center",
"=",
"{",
"type",
":",
"'Point'",
",",
"coordinates",
":",
"[",
"e",
".",
"latlng",
".",
"lng",
",",
"e",
".",
"latlng",
".",
"lat",
"]",
"}",
";",
"var",
"containerPoint",
"=",
"e",
".",
"containerPoint",
";",
"var",
"x1",
"=",
"e",
".",
"latlng",
".",
"lng",
"-",
"dpp",
";",
"var",
"x2",
"=",
"e",
".",
"latlng",
".",
"lng",
"+",
"dpp",
";",
"var",
"y1",
"=",
"e",
".",
"latlng",
".",
"lat",
"-",
"dpp",
";",
"var",
"y2",
"=",
"e",
".",
"latlng",
".",
"lat",
"+",
"dpp",
";",
"var",
"intersects",
"=",
"this",
".",
"intersectsBbox",
"(",
"[",
"[",
"x1",
",",
"y1",
"]",
",",
"[",
"x2",
",",
"y2",
"]",
"]",
",",
"r",
",",
"center",
",",
"containerPoint",
")",
";",
"onIntersectsListCreated",
".",
"call",
"(",
"this",
",",
"e",
",",
"intersects",
")",
";",
"}"
]
| Handle mouse intersection events
e - leaflet event | [
"Handle",
"mouse",
"intersection",
"events",
"e",
"-",
"leaflet",
"event"
]
| 39ccf82d6ee89684b3f5c826c013210dad954d8f | https://github.com/jrmerz/leaflet-canvas-geojson/blob/39ccf82d6ee89684b3f5c826c013210dad954d8f/src/lib/intersects.js#L8-L31 | train |
graphql-factory/graphql-factory | src-old/utilities/http.js | processBody | function processBody(opts, body) {
if (body === undefined) {
return '';
}
const handlers = Object.assign({}, serializers, opts.serializers);
const headers = typeof opts.headers === 'object' ? opts.headers : {};
const contentType = Object.keys(headers).reduce((type, header) => {
if (typeof type === 'string') {
return type;
}
if (
header.match(/^content-type$/i) &&
typeof headers[header] === 'string'
) {
return headers[header].toLowerCase();
}
return type;
}, undefined);
const handler = handlers[contentType];
if (typeof handler === 'function') {
return String(handler(body));
}
if (typeof body === 'object') {
return JSON.stringify(body);
}
return String(body);
} | javascript | function processBody(opts, body) {
if (body === undefined) {
return '';
}
const handlers = Object.assign({}, serializers, opts.serializers);
const headers = typeof opts.headers === 'object' ? opts.headers : {};
const contentType = Object.keys(headers).reduce((type, header) => {
if (typeof type === 'string') {
return type;
}
if (
header.match(/^content-type$/i) &&
typeof headers[header] === 'string'
) {
return headers[header].toLowerCase();
}
return type;
}, undefined);
const handler = handlers[contentType];
if (typeof handler === 'function') {
return String(handler(body));
}
if (typeof body === 'object') {
return JSON.stringify(body);
}
return String(body);
} | [
"function",
"processBody",
"(",
"opts",
",",
"body",
")",
"{",
"if",
"(",
"body",
"===",
"undefined",
")",
"{",
"return",
"''",
";",
"}",
"const",
"handlers",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"serializers",
",",
"opts",
".",
"serializers",
")",
";",
"const",
"headers",
"=",
"typeof",
"opts",
".",
"headers",
"===",
"'object'",
"?",
"opts",
".",
"headers",
":",
"{",
"}",
";",
"const",
"contentType",
"=",
"Object",
".",
"keys",
"(",
"headers",
")",
".",
"reduce",
"(",
"(",
"type",
",",
"header",
")",
"=>",
"{",
"if",
"(",
"typeof",
"type",
"===",
"'string'",
")",
"{",
"return",
"type",
";",
"}",
"if",
"(",
"header",
".",
"match",
"(",
"/",
"^content-type$",
"/",
"i",
")",
"&&",
"typeof",
"headers",
"[",
"header",
"]",
"===",
"'string'",
")",
"{",
"return",
"headers",
"[",
"header",
"]",
".",
"toLowerCase",
"(",
")",
";",
"}",
"return",
"type",
";",
"}",
",",
"undefined",
")",
";",
"const",
"handler",
"=",
"handlers",
"[",
"contentType",
"]",
";",
"if",
"(",
"typeof",
"handler",
"===",
"'function'",
")",
"{",
"return",
"String",
"(",
"handler",
"(",
"body",
")",
")",
";",
"}",
"if",
"(",
"typeof",
"body",
"===",
"'object'",
")",
"{",
"return",
"JSON",
".",
"stringify",
"(",
"body",
")",
";",
"}",
"return",
"String",
"(",
"body",
")",
";",
"}"
]
| Converts the body value to a string using optional serializers
@param {*} opts
@param {*} body | [
"Converts",
"the",
"body",
"value",
"to",
"a",
"string",
"using",
"optional",
"serializers"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/src-old/utilities/http.js#L35-L63 | train |
graphql-factory/graphql-factory | src-old/utilities/http.js | processData | function processData(res, data, options) {
const handlers = Object.assign({}, deserializers, options.deserializers);
const contentType = res.headers['content-type'];
const types = typeof contentType === 'string' ? contentType.split(';') : [];
// if there are no content types, return the data unmodified
if (!types.length) {
return data;
}
return types.reduce((d, type) => {
try {
const t = type.toLocaleLowerCase().trim();
const handler = handlers[t];
if (d instanceof Error || typeof handler !== 'function') {
return d;
}
return handler(d);
} catch (error) {
return error;
}
}, data);
} | javascript | function processData(res, data, options) {
const handlers = Object.assign({}, deserializers, options.deserializers);
const contentType = res.headers['content-type'];
const types = typeof contentType === 'string' ? contentType.split(';') : [];
// if there are no content types, return the data unmodified
if (!types.length) {
return data;
}
return types.reduce((d, type) => {
try {
const t = type.toLocaleLowerCase().trim();
const handler = handlers[t];
if (d instanceof Error || typeof handler !== 'function') {
return d;
}
return handler(d);
} catch (error) {
return error;
}
}, data);
} | [
"function",
"processData",
"(",
"res",
",",
"data",
",",
"options",
")",
"{",
"const",
"handlers",
"=",
"Object",
".",
"assign",
"(",
"{",
"}",
",",
"deserializers",
",",
"options",
".",
"deserializers",
")",
";",
"const",
"contentType",
"=",
"res",
".",
"headers",
"[",
"'content-type'",
"]",
";",
"const",
"types",
"=",
"typeof",
"contentType",
"===",
"'string'",
"?",
"contentType",
".",
"split",
"(",
"';'",
")",
":",
"[",
"]",
";",
"if",
"(",
"!",
"types",
".",
"length",
")",
"{",
"return",
"data",
";",
"}",
"return",
"types",
".",
"reduce",
"(",
"(",
"d",
",",
"type",
")",
"=>",
"{",
"try",
"{",
"const",
"t",
"=",
"type",
".",
"toLocaleLowerCase",
"(",
")",
".",
"trim",
"(",
")",
";",
"const",
"handler",
"=",
"handlers",
"[",
"t",
"]",
";",
"if",
"(",
"d",
"instanceof",
"Error",
"||",
"typeof",
"handler",
"!==",
"'function'",
")",
"{",
"return",
"d",
";",
"}",
"return",
"handler",
"(",
"d",
")",
";",
"}",
"catch",
"(",
"error",
")",
"{",
"return",
"error",
";",
"}",
"}",
",",
"data",
")",
";",
"}"
]
| Processes the response data based on content type using optional
deserializers
@param {*} res
@param {*} data
@param {*} options | [
"Processes",
"the",
"response",
"data",
"based",
"on",
"content",
"type",
"using",
"optional",
"deserializers"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/src-old/utilities/http.js#L72-L95 | train |
graphql-factory/graphql-factory | scratch/mongo-plugin.js | mongoType | function mongoType(
typeStr,
options
) {
const required = typeStr.match(/^(\S+)!$/);
const list = typeStr.match(/^\[(\S+)]$/);
if (required) {
const innerType = required[1];
if (_.includes(SCALARS, innerType)) {
options.required = true;
}
return mongoType(innerType);
} else if (list) {
return [ mongoType(list[1]) ];
}
switch (typeStr) {
case 'String':
return String;
case 'Int':
case 'Float':
return Number;
case 'Boolean':
return Boolean;
case 'DateTime':
return Date;
case 'ID':
return mongoose.Schema.Types.ObjectId;
case 'JSON':
return mongoose.Schema.Types.Mixed;
default:
throw new Error(typeStr);
}
} | javascript | function mongoType(
typeStr,
options
) {
const required = typeStr.match(/^(\S+)!$/);
const list = typeStr.match(/^\[(\S+)]$/);
if (required) {
const innerType = required[1];
if (_.includes(SCALARS, innerType)) {
options.required = true;
}
return mongoType(innerType);
} else if (list) {
return [ mongoType(list[1]) ];
}
switch (typeStr) {
case 'String':
return String;
case 'Int':
case 'Float':
return Number;
case 'Boolean':
return Boolean;
case 'DateTime':
return Date;
case 'ID':
return mongoose.Schema.Types.ObjectId;
case 'JSON':
return mongoose.Schema.Types.Mixed;
default:
throw new Error(typeStr);
}
} | [
"function",
"mongoType",
"(",
"typeStr",
",",
"options",
")",
"{",
"const",
"required",
"=",
"typeStr",
".",
"match",
"(",
"/",
"^(\\S+)!$",
"/",
")",
";",
"const",
"list",
"=",
"typeStr",
".",
"match",
"(",
"/",
"^\\[(\\S+)]$",
"/",
")",
";",
"if",
"(",
"required",
")",
"{",
"const",
"innerType",
"=",
"required",
"[",
"1",
"]",
";",
"if",
"(",
"_",
".",
"includes",
"(",
"SCALARS",
",",
"innerType",
")",
")",
"{",
"options",
".",
"required",
"=",
"true",
";",
"}",
"return",
"mongoType",
"(",
"innerType",
")",
";",
"}",
"else",
"if",
"(",
"list",
")",
"{",
"return",
"[",
"mongoType",
"(",
"list",
"[",
"1",
"]",
")",
"]",
";",
"}",
"switch",
"(",
"typeStr",
")",
"{",
"case",
"'String'",
":",
"return",
"String",
";",
"case",
"'Int'",
":",
"case",
"'Float'",
":",
"return",
"Number",
";",
"case",
"'Boolean'",
":",
"return",
"Boolean",
";",
"case",
"'DateTime'",
":",
"return",
"Date",
";",
"case",
"'ID'",
":",
"return",
"mongoose",
".",
"Schema",
".",
"Types",
".",
"ObjectId",
";",
"case",
"'JSON'",
":",
"return",
"mongoose",
".",
"Schema",
".",
"Types",
".",
"Mixed",
";",
"default",
":",
"throw",
"new",
"Error",
"(",
"typeStr",
")",
";",
"}",
"}"
]
| Translates a graphql scalar type to a valid mongoose type
@param {*} typeStr
@param {*} options | [
"Translates",
"a",
"graphql",
"scalar",
"type",
"to",
"a",
"valid",
"mongoose",
"type"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/scratch/mongo-plugin.js#L31-L64 | train |
graphql-factory/graphql-factory | archive/v2/src/GraphQLFactoryDecomposer.js | getTypeInfo | function getTypeInfo (obj, info) {
const constructorName = _.constructorName(obj)
const _info = info || {
type: null,
name: null,
isList: false,
isNonNull: false
}
switch (constructorName) {
case 'GraphQLNonNull':
_info.isNonNull = true
return getTypeInfo(obj.ofType, _info)
case 'GraphQLList':
_info.isList = true
return getTypeInfo(obj.ofType, _info)
default:
_info.type = obj
_info.name = obj.name
}
return _info
} | javascript | function getTypeInfo (obj, info) {
const constructorName = _.constructorName(obj)
const _info = info || {
type: null,
name: null,
isList: false,
isNonNull: false
}
switch (constructorName) {
case 'GraphQLNonNull':
_info.isNonNull = true
return getTypeInfo(obj.ofType, _info)
case 'GraphQLList':
_info.isList = true
return getTypeInfo(obj.ofType, _info)
default:
_info.type = obj
_info.name = obj.name
}
return _info
} | [
"function",
"getTypeInfo",
"(",
"obj",
",",
"info",
")",
"{",
"const",
"constructorName",
"=",
"_",
".",
"constructorName",
"(",
"obj",
")",
"const",
"_info",
"=",
"info",
"||",
"{",
"type",
":",
"null",
",",
"name",
":",
"null",
",",
"isList",
":",
"false",
",",
"isNonNull",
":",
"false",
"}",
"switch",
"(",
"constructorName",
")",
"{",
"case",
"'GraphQLNonNull'",
":",
"_info",
".",
"isNonNull",
"=",
"true",
"return",
"getTypeInfo",
"(",
"obj",
".",
"ofType",
",",
"_info",
")",
"case",
"'GraphQLList'",
":",
"_info",
".",
"isList",
"=",
"true",
"return",
"getTypeInfo",
"(",
"obj",
".",
"ofType",
",",
"_info",
")",
"default",
":",
"_info",
".",
"type",
"=",
"obj",
"_info",
".",
"name",
"=",
"obj",
".",
"name",
"}",
"return",
"_info",
"}"
]
| Strips away nonnull and list objects to
build an info object containing the type
@param obj
@param info
@returns {*} | [
"Strips",
"away",
"nonnull",
"and",
"list",
"objects",
"to",
"build",
"an",
"info",
"object",
"containing",
"the",
"type"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/v2/src/GraphQLFactoryDecomposer.js#L11-L32 | train |
graphql-factory/graphql-factory | archive/v2/src/GraphQLFactoryDecomposer.js | baseDef | function baseDef (info) {
const { name, isList, isNonNull } = info
const def = {
type: isList ? [ name ] : name
}
if (isNonNull) def.nullable = false
return def
} | javascript | function baseDef (info) {
const { name, isList, isNonNull } = info
const def = {
type: isList ? [ name ] : name
}
if (isNonNull) def.nullable = false
return def
} | [
"function",
"baseDef",
"(",
"info",
")",
"{",
"const",
"{",
"name",
",",
"isList",
",",
"isNonNull",
"}",
"=",
"info",
"const",
"def",
"=",
"{",
"type",
":",
"isList",
"?",
"[",
"name",
"]",
":",
"name",
"}",
"if",
"(",
"isNonNull",
")",
"def",
".",
"nullable",
"=",
"false",
"return",
"def",
"}"
]
| creates a base def object
@param info
@returns {{type: [null]}} | [
"creates",
"a",
"base",
"def",
"object"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/v2/src/GraphQLFactoryDecomposer.js#L39-L46 | train |
graphql-factory/graphql-factory | src-old/utilities/request.js | resolveBuild | function resolveBuild(schema) {
const build = _.get(schema, 'definition._build');
return isPromise(build) ? build : Promise.resolve();
} | javascript | function resolveBuild(schema) {
const build = _.get(schema, 'definition._build');
return isPromise(build) ? build : Promise.resolve();
} | [
"function",
"resolveBuild",
"(",
"schema",
")",
"{",
"const",
"build",
"=",
"_",
".",
"get",
"(",
"schema",
",",
"'definition._build'",
")",
";",
"return",
"isPromise",
"(",
"build",
")",
"?",
"build",
":",
"Promise",
".",
"resolve",
"(",
")",
";",
"}"
]
| Resolves the schema definition build before
performing the request
@param {*} schema | [
"Resolves",
"the",
"schema",
"definition",
"build",
"before",
"performing",
"the",
"request"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/src-old/utilities/request.js#L14-L17 | train |
graphql-factory/graphql-factory | src-old/execution/middleware.js | middleware | function middleware(definition, resolver, options) {
const customExecution = options.factoryExecution !== false;
const resolve = function(source, args, context, info) {
// ensure that context is an object and extend it
const ctx = _.isObjectLike(context) ? context : {};
Object.assign(ctx, definition.context);
info.definition = definition;
return customExecution
? factoryExecute(source, args, ctx, info)
: graphqlExecute(source, args, ctx, info);
};
// add the resolver as a property on the resolve middleware
// function so that when deconstructing the schema the original
// resolver is preserved. Also add a flag that identifies this
// resolver as factory middleware
resolve.__resolver = resolver;
resolve.__factoryMiddleware = true;
return resolve;
} | javascript | function middleware(definition, resolver, options) {
const customExecution = options.factoryExecution !== false;
const resolve = function(source, args, context, info) {
// ensure that context is an object and extend it
const ctx = _.isObjectLike(context) ? context : {};
Object.assign(ctx, definition.context);
info.definition = definition;
return customExecution
? factoryExecute(source, args, ctx, info)
: graphqlExecute(source, args, ctx, info);
};
// add the resolver as a property on the resolve middleware
// function so that when deconstructing the schema the original
// resolver is preserved. Also add a flag that identifies this
// resolver as factory middleware
resolve.__resolver = resolver;
resolve.__factoryMiddleware = true;
return resolve;
} | [
"function",
"middleware",
"(",
"definition",
",",
"resolver",
",",
"options",
")",
"{",
"const",
"customExecution",
"=",
"options",
".",
"factoryExecution",
"!==",
"false",
";",
"const",
"resolve",
"=",
"function",
"(",
"source",
",",
"args",
",",
"context",
",",
"info",
")",
"{",
"const",
"ctx",
"=",
"_",
".",
"isObjectLike",
"(",
"context",
")",
"?",
"context",
":",
"{",
"}",
";",
"Object",
".",
"assign",
"(",
"ctx",
",",
"definition",
".",
"context",
")",
";",
"info",
".",
"definition",
"=",
"definition",
";",
"return",
"customExecution",
"?",
"factoryExecute",
"(",
"source",
",",
"args",
",",
"ctx",
",",
"info",
")",
":",
"graphqlExecute",
"(",
"source",
",",
"args",
",",
"ctx",
",",
"info",
")",
";",
"}",
";",
"resolve",
".",
"__resolver",
"=",
"resolver",
";",
"resolve",
".",
"__factoryMiddleware",
"=",
"true",
";",
"return",
"resolve",
";",
"}"
]
| Main middleware function that is wrapped around all resolvers
in the graphql schema
@param {*} source
@param {*} args
@param {*} context
@param {*} info | [
"Main",
"middleware",
"function",
"that",
"is",
"wrapped",
"around",
"all",
"resolvers",
"in",
"the",
"graphql",
"schema"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/src-old/execution/middleware.js#L13-L33 | train |
graphql-factory/graphql-factory | src-old/directives/by.js | defaultResolveUser | function defaultResolveUser(source, args, context, info) {
return (
get(args, ['userID']) ||
get(context, ['userID']) ||
get(info, ['rootValue', 'userID'])
);
} | javascript | function defaultResolveUser(source, args, context, info) {
return (
get(args, ['userID']) ||
get(context, ['userID']) ||
get(info, ['rootValue', 'userID'])
);
} | [
"function",
"defaultResolveUser",
"(",
"source",
",",
"args",
",",
"context",
",",
"info",
")",
"{",
"return",
"(",
"get",
"(",
"args",
",",
"[",
"'userID'",
"]",
")",
"||",
"get",
"(",
"context",
",",
"[",
"'userID'",
"]",
")",
"||",
"get",
"(",
"info",
",",
"[",
"'rootValue'",
",",
"'userID'",
"]",
")",
")",
";",
"}"
]
| Default user id resolver, checks args, then context, then rootValue
for a userID value
@param {*} source
@param {*} args
@param {*} context
@param {*} info | [
"Default",
"user",
"id",
"resolver",
"checks",
"args",
"then",
"context",
"then",
"rootValue",
"for",
"a",
"userID",
"value"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/src-old/directives/by.js#L16-L22 | train |
graphql-factory/graphql-factory | archive/src/generate/backing.js | resolverMiddleware | function resolverMiddleware (resolver) {
return function (req, res, next) {
try {
const { source, args, context, info } = req
const nonCircularReq = _.omit(req, [ 'context' ])
const ctx = _.assign({}, context, { req: nonCircularReq, res, next })
const value = resolver(source, args, ctx, info)
// return a resolved promise
return Promise.resolve(value)
.then(result => {
req.result = result
return next()
})
.catch(next)
} catch (err) {
return next(err)
}
}
} | javascript | function resolverMiddleware (resolver) {
return function (req, res, next) {
try {
const { source, args, context, info } = req
const nonCircularReq = _.omit(req, [ 'context' ])
const ctx = _.assign({}, context, { req: nonCircularReq, res, next })
const value = resolver(source, args, ctx, info)
// return a resolved promise
return Promise.resolve(value)
.then(result => {
req.result = result
return next()
})
.catch(next)
} catch (err) {
return next(err)
}
}
} | [
"function",
"resolverMiddleware",
"(",
"resolver",
")",
"{",
"return",
"function",
"(",
"req",
",",
"res",
",",
"next",
")",
"{",
"try",
"{",
"const",
"{",
"source",
",",
"args",
",",
"context",
",",
"info",
"}",
"=",
"req",
"const",
"nonCircularReq",
"=",
"_",
".",
"omit",
"(",
"req",
",",
"[",
"'context'",
"]",
")",
"const",
"ctx",
"=",
"_",
".",
"assign",
"(",
"{",
"}",
",",
"context",
",",
"{",
"req",
":",
"nonCircularReq",
",",
"res",
",",
"next",
"}",
")",
"const",
"value",
"=",
"resolver",
"(",
"source",
",",
"args",
",",
"ctx",
",",
"info",
")",
"return",
"Promise",
".",
"resolve",
"(",
"value",
")",
".",
"then",
"(",
"result",
"=>",
"{",
"req",
".",
"result",
"=",
"result",
"return",
"next",
"(",
")",
"}",
")",
".",
"catch",
"(",
"next",
")",
"}",
"catch",
"(",
"err",
")",
"{",
"return",
"next",
"(",
"err",
")",
"}",
"}",
"}"
]
| Creates a middleware function from the field resolve
@param resolver
@returns {Function} | [
"Creates",
"a",
"middleware",
"function",
"from",
"the",
"field",
"resolve"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/src/generate/backing.js#L36-L55 | train |
graphql-factory/graphql-factory | archive/src/generate/backing.js | addTypeFunction | function addTypeFunction (typeName, funcName, func) {
if (!stringValue(typeName)) {
throw new Error('Invalid "typeName" argument, must be String')
} else if (!_.isFunction(func) && !stringValue(func)) {
throw new Error('Invalid func argument, must be function')
}
_.set(this.backing, [ typeName, `_${funcName}` ], func)
return this
} | javascript | function addTypeFunction (typeName, funcName, func) {
if (!stringValue(typeName)) {
throw new Error('Invalid "typeName" argument, must be String')
} else if (!_.isFunction(func) && !stringValue(func)) {
throw new Error('Invalid func argument, must be function')
}
_.set(this.backing, [ typeName, `_${funcName}` ], func)
return this
} | [
"function",
"addTypeFunction",
"(",
"typeName",
",",
"funcName",
",",
"func",
")",
"{",
"if",
"(",
"!",
"stringValue",
"(",
"typeName",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid \"typeName\" argument, must be String'",
")",
"}",
"else",
"if",
"(",
"!",
"_",
".",
"isFunction",
"(",
"func",
")",
"&&",
"!",
"stringValue",
"(",
"func",
")",
")",
"{",
"throw",
"new",
"Error",
"(",
"'Invalid func argument, must be function'",
")",
"}",
"_",
".",
"set",
"(",
"this",
".",
"backing",
",",
"[",
"typeName",
",",
"`",
"${",
"funcName",
"}",
"`",
"]",
",",
"func",
")",
"return",
"this",
"}"
]
| Adds a type function to the backing
@param typeName
@param funcName
@param func
@returns {addTypeFunction} | [
"Adds",
"a",
"type",
"function",
"to",
"the",
"backing"
]
| 22f98d8e8ada5affcc8eac214b864109dcbb74d7 | https://github.com/graphql-factory/graphql-factory/blob/22f98d8e8ada5affcc8eac214b864109dcbb74d7/archive/src/generate/backing.js#L64-L72 | train |
sony/cordova-plugin-cdp-nativebridge | dev/platforms/android/cordova/lib/prepare.js | deleteDefaultResourceAt | function deleteDefaultResourceAt(baseDir, resourceName) {
shell.ls(path.join(baseDir, 'res/drawable-*'))
.forEach(function (drawableFolder) {
var imagePath = path.join(drawableFolder, resourceName);
shell.rm('-f', [imagePath, imagePath.replace(/\.png$/, '.9.png')]);
events.emit('verbose', 'Deleted ' + imagePath);
});
} | javascript | function deleteDefaultResourceAt(baseDir, resourceName) {
shell.ls(path.join(baseDir, 'res/drawable-*'))
.forEach(function (drawableFolder) {
var imagePath = path.join(drawableFolder, resourceName);
shell.rm('-f', [imagePath, imagePath.replace(/\.png$/, '.9.png')]);
events.emit('verbose', 'Deleted ' + imagePath);
});
} | [
"function",
"deleteDefaultResourceAt",
"(",
"baseDir",
",",
"resourceName",
")",
"{",
"shell",
".",
"ls",
"(",
"path",
".",
"join",
"(",
"baseDir",
",",
"'res/drawable-*'",
")",
")",
".",
"forEach",
"(",
"function",
"(",
"drawableFolder",
")",
"{",
"var",
"imagePath",
"=",
"path",
".",
"join",
"(",
"drawableFolder",
",",
"resourceName",
")",
";",
"shell",
".",
"rm",
"(",
"'-f'",
",",
"[",
"imagePath",
",",
"imagePath",
".",
"replace",
"(",
"/",
"\\.png$",
"/",
",",
"'.9.png'",
")",
"]",
")",
";",
"events",
".",
"emit",
"(",
"'verbose'",
",",
"'Deleted '",
"+",
"imagePath",
")",
";",
"}",
")",
";",
"}"
]
| remove the default resource name from all drawable folders | [
"remove",
"the",
"default",
"resource",
"name",
"from",
"all",
"drawable",
"folders"
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/platforms/android/cordova/lib/prepare.js#L310-L317 | train |
sony/cordova-plugin-cdp-nativebridge | dev/build/tasks/build.app.plugins.js | queryTargetScripts | function queryTargetScripts(targetDir) {
var scripts = [];
fs.readdirSync(targetDir).forEach(function (file) {
if (!path.basename(file).toLowerCase().match(/.d.ts/g) && path.basename(file).toLowerCase().match(/\.ts$/i)) {
scripts.push(path.basename(file, path.extname(file)));
}
});
return scripts;
} | javascript | function queryTargetScripts(targetDir) {
var scripts = [];
fs.readdirSync(targetDir).forEach(function (file) {
if (!path.basename(file).toLowerCase().match(/.d.ts/g) && path.basename(file).toLowerCase().match(/\.ts$/i)) {
scripts.push(path.basename(file, path.extname(file)));
}
});
return scripts;
} | [
"function",
"queryTargetScripts",
"(",
"targetDir",
")",
"{",
"var",
"scripts",
"=",
"[",
"]",
";",
"fs",
".",
"readdirSync",
"(",
"targetDir",
")",
".",
"forEach",
"(",
"function",
"(",
"file",
")",
"{",
"if",
"(",
"!",
"path",
".",
"basename",
"(",
"file",
")",
".",
"toLowerCase",
"(",
")",
".",
"match",
"(",
"/",
".d.ts",
"/",
"g",
")",
"&&",
"path",
".",
"basename",
"(",
"file",
")",
".",
"toLowerCase",
"(",
")",
".",
"match",
"(",
"/",
"\\.ts$",
"/",
"i",
")",
")",
"{",
"scripts",
".",
"push",
"(",
"path",
".",
"basename",
"(",
"file",
",",
"path",
".",
"extname",
"(",
"file",
")",
")",
")",
";",
"}",
"}",
")",
";",
"return",
"scripts",
";",
"}"
]
| query build target scripts. | [
"query",
"build",
"target",
"scripts",
"."
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.app.plugins.js#L377-L385 | train |
sony/cordova-plugin-cdp-nativebridge | dev/build/tasks/build.app.plugins.js | queryPluginVersion | function queryPluginVersion(pluginDir) {
var pluginXml = path.join(pluginDir, 'plugin.xml');
var domPluginXml = jsdom.jsdom(fs.readFileSync(pluginXml).toString());
return $(domPluginXml).find('plugin').attr('version');
} | javascript | function queryPluginVersion(pluginDir) {
var pluginXml = path.join(pluginDir, 'plugin.xml');
var domPluginXml = jsdom.jsdom(fs.readFileSync(pluginXml).toString());
return $(domPluginXml).find('plugin').attr('version');
} | [
"function",
"queryPluginVersion",
"(",
"pluginDir",
")",
"{",
"var",
"pluginXml",
"=",
"path",
".",
"join",
"(",
"pluginDir",
",",
"'plugin.xml'",
")",
";",
"var",
"domPluginXml",
"=",
"jsdom",
".",
"jsdom",
"(",
"fs",
".",
"readFileSync",
"(",
"pluginXml",
")",
".",
"toString",
"(",
")",
")",
";",
"return",
"$",
"(",
"domPluginXml",
")",
".",
"find",
"(",
"'plugin'",
")",
".",
"attr",
"(",
"'version'",
")",
";",
"}"
]
| query plugin version. | [
"query",
"plugin",
"version",
"."
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.app.plugins.js#L388-L393 | train |
sony/cordova-plugin-cdp-nativebridge | dev/build/tasks/build.app.plugins.js | setBanner | function setBanner() {
if (grunt.config.get('app_plugins_mode_release')) {
var moduleName = grunt.config.get('app_plugins_work_script_name') + '.js';
var version = grunt.config.get('app_plugins_work_version');
var src = path.join(
grunt.config.get('app_plugins_root_dir'),
grunt.config.get('app_plugins_work_id'),
grunt.config.get('plugins_www'),
grunt.config.get('app_plugins_work_script_name') + '.js'
);
var info = {
src: src,
moduleName: moduleName,
version: version,
};
grunt.config.set('banner_info', info);
grunt.task.run('banner_setup');
}
} | javascript | function setBanner() {
if (grunt.config.get('app_plugins_mode_release')) {
var moduleName = grunt.config.get('app_plugins_work_script_name') + '.js';
var version = grunt.config.get('app_plugins_work_version');
var src = path.join(
grunt.config.get('app_plugins_root_dir'),
grunt.config.get('app_plugins_work_id'),
grunt.config.get('plugins_www'),
grunt.config.get('app_plugins_work_script_name') + '.js'
);
var info = {
src: src,
moduleName: moduleName,
version: version,
};
grunt.config.set('banner_info', info);
grunt.task.run('banner_setup');
}
} | [
"function",
"setBanner",
"(",
")",
"{",
"if",
"(",
"grunt",
".",
"config",
".",
"get",
"(",
"'app_plugins_mode_release'",
")",
")",
"{",
"var",
"moduleName",
"=",
"grunt",
".",
"config",
".",
"get",
"(",
"'app_plugins_work_script_name'",
")",
"+",
"'.js'",
";",
"var",
"version",
"=",
"grunt",
".",
"config",
".",
"get",
"(",
"'app_plugins_work_version'",
")",
";",
"var",
"src",
"=",
"path",
".",
"join",
"(",
"grunt",
".",
"config",
".",
"get",
"(",
"'app_plugins_root_dir'",
")",
",",
"grunt",
".",
"config",
".",
"get",
"(",
"'app_plugins_work_id'",
")",
",",
"grunt",
".",
"config",
".",
"get",
"(",
"'plugins_www'",
")",
",",
"grunt",
".",
"config",
".",
"get",
"(",
"'app_plugins_work_script_name'",
")",
"+",
"'.js'",
")",
";",
"var",
"info",
"=",
"{",
"src",
":",
"src",
",",
"moduleName",
":",
"moduleName",
",",
"version",
":",
"version",
",",
"}",
";",
"grunt",
".",
"config",
".",
"set",
"(",
"'banner_info'",
",",
"info",
")",
";",
"grunt",
".",
"task",
".",
"run",
"(",
"'banner_setup'",
")",
";",
"}",
"}"
]
| set banner if needed. | [
"set",
"banner",
"if",
"needed",
"."
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.app.plugins.js#L396-L416 | train |
sony/cordova-plugin-cdp-nativebridge | dev/platforms/ios/cordova/Api.js | Api | function Api(platform, platformRootDir, events) {
// 'platform' property is required as per PlatformApi spec
this.platform = platform || 'ios';
this.root = platformRootDir || path.resolve(__dirname, '..');
this.events = events || ConsoleLogger.get();
// NOTE: trick to share one EventEmitter instance across all js code
require('cordova-common').events = this.events;
var xcodeProjDir;
var xcodeCordovaProj;
try {
xcodeProjDir = fs.readdirSync(this.root).filter( function(e) { return e.match(/\.xcodeproj$/i); })[0];
if (!xcodeProjDir) {
throw new CordovaError('The provided path "' + this.root + '" is not a Cordova iOS project.');
}
var cordovaProjName = xcodeProjDir.substring(xcodeProjDir.lastIndexOf(path.sep)+1, xcodeProjDir.indexOf('.xcodeproj'));
xcodeCordovaProj = path.join(this.root, cordovaProjName);
} catch(e) {
throw new CordovaError('The provided path "'+this.root+'" is not a Cordova iOS project.');
}
this.locations = {
root: this.root,
www: path.join(this.root, 'www'),
platformWww: path.join(this.root, 'platform_www'),
configXml: path.join(xcodeCordovaProj, 'config.xml'),
defaultConfigXml: path.join(this.root, 'cordova/defaults.xml'),
pbxproj: path.join(this.root, xcodeProjDir, 'project.pbxproj'),
xcodeProjDir: path.join(this.root, xcodeProjDir),
xcodeCordovaProj: xcodeCordovaProj,
// NOTE: this is required by browserify logic.
// As per platformApi spec we return relative to template root paths here
cordovaJs: 'bin/CordovaLib/cordova.js',
cordovaJsSrc: 'bin/cordova-js-src'
};
} | javascript | function Api(platform, platformRootDir, events) {
// 'platform' property is required as per PlatformApi spec
this.platform = platform || 'ios';
this.root = platformRootDir || path.resolve(__dirname, '..');
this.events = events || ConsoleLogger.get();
// NOTE: trick to share one EventEmitter instance across all js code
require('cordova-common').events = this.events;
var xcodeProjDir;
var xcodeCordovaProj;
try {
xcodeProjDir = fs.readdirSync(this.root).filter( function(e) { return e.match(/\.xcodeproj$/i); })[0];
if (!xcodeProjDir) {
throw new CordovaError('The provided path "' + this.root + '" is not a Cordova iOS project.');
}
var cordovaProjName = xcodeProjDir.substring(xcodeProjDir.lastIndexOf(path.sep)+1, xcodeProjDir.indexOf('.xcodeproj'));
xcodeCordovaProj = path.join(this.root, cordovaProjName);
} catch(e) {
throw new CordovaError('The provided path "'+this.root+'" is not a Cordova iOS project.');
}
this.locations = {
root: this.root,
www: path.join(this.root, 'www'),
platformWww: path.join(this.root, 'platform_www'),
configXml: path.join(xcodeCordovaProj, 'config.xml'),
defaultConfigXml: path.join(this.root, 'cordova/defaults.xml'),
pbxproj: path.join(this.root, xcodeProjDir, 'project.pbxproj'),
xcodeProjDir: path.join(this.root, xcodeProjDir),
xcodeCordovaProj: xcodeCordovaProj,
// NOTE: this is required by browserify logic.
// As per platformApi spec we return relative to template root paths here
cordovaJs: 'bin/CordovaLib/cordova.js',
cordovaJsSrc: 'bin/cordova-js-src'
};
} | [
"function",
"Api",
"(",
"platform",
",",
"platformRootDir",
",",
"events",
")",
"{",
"this",
".",
"platform",
"=",
"platform",
"||",
"'ios'",
";",
"this",
".",
"root",
"=",
"platformRootDir",
"||",
"path",
".",
"resolve",
"(",
"__dirname",
",",
"'..'",
")",
";",
"this",
".",
"events",
"=",
"events",
"||",
"ConsoleLogger",
".",
"get",
"(",
")",
";",
"require",
"(",
"'cordova-common'",
")",
".",
"events",
"=",
"this",
".",
"events",
";",
"var",
"xcodeProjDir",
";",
"var",
"xcodeCordovaProj",
";",
"try",
"{",
"xcodeProjDir",
"=",
"fs",
".",
"readdirSync",
"(",
"this",
".",
"root",
")",
".",
"filter",
"(",
"function",
"(",
"e",
")",
"{",
"return",
"e",
".",
"match",
"(",
"/",
"\\.xcodeproj$",
"/",
"i",
")",
";",
"}",
")",
"[",
"0",
"]",
";",
"if",
"(",
"!",
"xcodeProjDir",
")",
"{",
"throw",
"new",
"CordovaError",
"(",
"'The provided path \"'",
"+",
"this",
".",
"root",
"+",
"'\" is not a Cordova iOS project.'",
")",
";",
"}",
"var",
"cordovaProjName",
"=",
"xcodeProjDir",
".",
"substring",
"(",
"xcodeProjDir",
".",
"lastIndexOf",
"(",
"path",
".",
"sep",
")",
"+",
"1",
",",
"xcodeProjDir",
".",
"indexOf",
"(",
"'.xcodeproj'",
")",
")",
";",
"xcodeCordovaProj",
"=",
"path",
".",
"join",
"(",
"this",
".",
"root",
",",
"cordovaProjName",
")",
";",
"}",
"catch",
"(",
"e",
")",
"{",
"throw",
"new",
"CordovaError",
"(",
"'The provided path \"'",
"+",
"this",
".",
"root",
"+",
"'\" is not a Cordova iOS project.'",
")",
";",
"}",
"this",
".",
"locations",
"=",
"{",
"root",
":",
"this",
".",
"root",
",",
"www",
":",
"path",
".",
"join",
"(",
"this",
".",
"root",
",",
"'www'",
")",
",",
"platformWww",
":",
"path",
".",
"join",
"(",
"this",
".",
"root",
",",
"'platform_www'",
")",
",",
"configXml",
":",
"path",
".",
"join",
"(",
"xcodeCordovaProj",
",",
"'config.xml'",
")",
",",
"defaultConfigXml",
":",
"path",
".",
"join",
"(",
"this",
".",
"root",
",",
"'cordova/defaults.xml'",
")",
",",
"pbxproj",
":",
"path",
".",
"join",
"(",
"this",
".",
"root",
",",
"xcodeProjDir",
",",
"'project.pbxproj'",
")",
",",
"xcodeProjDir",
":",
"path",
".",
"join",
"(",
"this",
".",
"root",
",",
"xcodeProjDir",
")",
",",
"xcodeCordovaProj",
":",
"xcodeCordovaProj",
",",
"cordovaJs",
":",
"'bin/CordovaLib/cordova.js'",
",",
"cordovaJsSrc",
":",
"'bin/cordova-js-src'",
"}",
";",
"}"
]
| Creates a new PlatformApi instance.
@param {String} [platform] Platform name, used for backward compatibility
w/ PlatformPoly (CordovaLib).
@param {String} [platformRootDir] Platform root location, used for backward
compatibility w/ PlatformPoly (CordovaLib).
@param {EventEmitter} [events] An EventEmitter instance that will be used for
logging purposes. If no EventEmitter provided, all events will be logged to
console | [
"Creates",
"a",
"new",
"PlatformApi",
"instance",
"."
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/platforms/ios/cordova/Api.js#L39-L77 | train |
sony/cordova-plugin-cdp-nativebridge | dev/platforms/ios/cordova/lib/prepare.js | parseTargetDevicePreference | function parseTargetDevicePreference(value) {
if (!value) return null;
var map = { 'universal': '"1,2"', 'handset': '"1"', 'tablet': '"2"'};
if (map[value.toLowerCase()]) {
return map[value.toLowerCase()];
}
events.emit('warn', 'Unknown target-device preference value: "' + value + '".');
return null;
} | javascript | function parseTargetDevicePreference(value) {
if (!value) return null;
var map = { 'universal': '"1,2"', 'handset': '"1"', 'tablet': '"2"'};
if (map[value.toLowerCase()]) {
return map[value.toLowerCase()];
}
events.emit('warn', 'Unknown target-device preference value: "' + value + '".');
return null;
} | [
"function",
"parseTargetDevicePreference",
"(",
"value",
")",
"{",
"if",
"(",
"!",
"value",
")",
"return",
"null",
";",
"var",
"map",
"=",
"{",
"'universal'",
":",
"'\"1,2\"'",
",",
"'handset'",
":",
"'\"1\"'",
",",
"'tablet'",
":",
"'\"2\"'",
"}",
";",
"if",
"(",
"map",
"[",
"value",
".",
"toLowerCase",
"(",
")",
"]",
")",
"{",
"return",
"map",
"[",
"value",
".",
"toLowerCase",
"(",
")",
"]",
";",
"}",
"events",
".",
"emit",
"(",
"'warn'",
",",
"'Unknown target-device preference value: \"'",
"+",
"value",
"+",
"'\".'",
")",
";",
"return",
"null",
";",
"}"
]
| Converts cordova specific representation of target device to XCode value | [
"Converts",
"cordova",
"specific",
"representation",
"of",
"target",
"device",
"to",
"XCode",
"value"
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/platforms/ios/cordova/lib/prepare.js#L535-L543 | train |
sony/cordova-plugin-cdp-nativebridge | dev/build/tasks/build.lazyload.js | getDocDom | function getDocDom() {
return jsdom.jsdom(fs.readFileSync(path.join(grunt.config.get('tmpdir'), 'index.html')).toString());
} | javascript | function getDocDom() {
return jsdom.jsdom(fs.readFileSync(path.join(grunt.config.get('tmpdir'), 'index.html')).toString());
} | [
"function",
"getDocDom",
"(",
")",
"{",
"return",
"jsdom",
".",
"jsdom",
"(",
"fs",
".",
"readFileSync",
"(",
"path",
".",
"join",
"(",
"grunt",
".",
"config",
".",
"get",
"(",
"'tmpdir'",
")",
",",
"'index.html'",
")",
")",
".",
"toString",
"(",
")",
")",
";",
"}"
]
| ! get doc dom from index.html. | [
"!",
"get",
"doc",
"dom",
"from",
"index",
".",
"html",
"."
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.lazyload.js#L99-L101 | train |
sony/cordova-plugin-cdp-nativebridge | dev/build/tasks/build.lazyload.js | getExtension | function getExtension(file) {
var ret;
if (file) {
var fileTypes = file.split('.');
var len = fileTypes.length;
if (0 === len) {
return ret;
}
ret = fileTypes[len - 1];
return ret;
}
} | javascript | function getExtension(file) {
var ret;
if (file) {
var fileTypes = file.split('.');
var len = fileTypes.length;
if (0 === len) {
return ret;
}
ret = fileTypes[len - 1];
return ret;
}
} | [
"function",
"getExtension",
"(",
"file",
")",
"{",
"var",
"ret",
";",
"if",
"(",
"file",
")",
"{",
"var",
"fileTypes",
"=",
"file",
".",
"split",
"(",
"'.'",
")",
";",
"var",
"len",
"=",
"fileTypes",
".",
"length",
";",
"if",
"(",
"0",
"===",
"len",
")",
"{",
"return",
"ret",
";",
"}",
"ret",
"=",
"fileTypes",
"[",
"len",
"-",
"1",
"]",
";",
"return",
"ret",
";",
"}",
"}"
]
| ! get file extension. | [
"!",
"get",
"file",
"extension",
"."
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.lazyload.js#L104-L115 | train |
sony/cordova-plugin-cdp-nativebridge | dev/build/tasks/build.lazyload.js | getScriptElements | function getScriptElements($typeLazy) {
var scripts;
var src = $typeLazy.attr("src");
if ("js" === getExtension(src).toLowerCase()) {
return $typeLazy;
} else {
src = path.join(grunt.config.get('tmpdir'), src);
if (fs.existsSync(src)) {
scripts = jsdom.jsdom(fs.readFileSync(src).toString());
return $(scripts).find("script");
} else {
return $();
}
}
} | javascript | function getScriptElements($typeLazy) {
var scripts;
var src = $typeLazy.attr("src");
if ("js" === getExtension(src).toLowerCase()) {
return $typeLazy;
} else {
src = path.join(grunt.config.get('tmpdir'), src);
if (fs.existsSync(src)) {
scripts = jsdom.jsdom(fs.readFileSync(src).toString());
return $(scripts).find("script");
} else {
return $();
}
}
} | [
"function",
"getScriptElements",
"(",
"$typeLazy",
")",
"{",
"var",
"scripts",
";",
"var",
"src",
"=",
"$typeLazy",
".",
"attr",
"(",
"\"src\"",
")",
";",
"if",
"(",
"\"js\"",
"===",
"getExtension",
"(",
"src",
")",
".",
"toLowerCase",
"(",
")",
")",
"{",
"return",
"$typeLazy",
";",
"}",
"else",
"{",
"src",
"=",
"path",
".",
"join",
"(",
"grunt",
".",
"config",
".",
"get",
"(",
"'tmpdir'",
")",
",",
"src",
")",
";",
"if",
"(",
"fs",
".",
"existsSync",
"(",
"src",
")",
")",
"{",
"scripts",
"=",
"jsdom",
".",
"jsdom",
"(",
"fs",
".",
"readFileSync",
"(",
"src",
")",
".",
"toString",
"(",
")",
")",
";",
"return",
"$",
"(",
"scripts",
")",
".",
"find",
"(",
"\"script\"",
")",
";",
"}",
"else",
"{",
"return",
"$",
"(",
")",
";",
"}",
"}",
"}"
]
| ! get script element. | [
"!",
"get",
"script",
"element",
"."
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.lazyload.js#L118-L132 | train |
sony/cordova-plugin-cdp-nativebridge | dev/build/tasks/build.lazyload.js | prepareAppScriptsInfo | function prepareAppScriptsInfo(docDom) {
// read index file, and getting target ts files.
var appScripts = [];
var $appScripts = $(docDom).find('script[type="lazy"]');
var findAppJs = false;
$appScripts.each(function () {
var $scripts = getScriptElements($(this));
$scripts.each(function () {
var src = $(this).attr('src');
if (src.match(/app.js$/i)) {
findAppJs = true;
}
appScripts.push(path.join(grunt.config.get('tmpdir'), src).replace(/\.js$/i, '.ts'));
});
});
if (!findAppJs) {
grunt.config.set('app_js_suffix', '-all');
}
// set app_scripts
grunt.config.set('app_scripts', appScripts);
} | javascript | function prepareAppScriptsInfo(docDom) {
// read index file, and getting target ts files.
var appScripts = [];
var $appScripts = $(docDom).find('script[type="lazy"]');
var findAppJs = false;
$appScripts.each(function () {
var $scripts = getScriptElements($(this));
$scripts.each(function () {
var src = $(this).attr('src');
if (src.match(/app.js$/i)) {
findAppJs = true;
}
appScripts.push(path.join(grunt.config.get('tmpdir'), src).replace(/\.js$/i, '.ts'));
});
});
if (!findAppJs) {
grunt.config.set('app_js_suffix', '-all');
}
// set app_scripts
grunt.config.set('app_scripts', appScripts);
} | [
"function",
"prepareAppScriptsInfo",
"(",
"docDom",
")",
"{",
"var",
"appScripts",
"=",
"[",
"]",
";",
"var",
"$appScripts",
"=",
"$",
"(",
"docDom",
")",
".",
"find",
"(",
"'script[type=\"lazy\"]'",
")",
";",
"var",
"findAppJs",
"=",
"false",
";",
"$appScripts",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"$scripts",
"=",
"getScriptElements",
"(",
"$",
"(",
"this",
")",
")",
";",
"$scripts",
".",
"each",
"(",
"function",
"(",
")",
"{",
"var",
"src",
"=",
"$",
"(",
"this",
")",
".",
"attr",
"(",
"'src'",
")",
";",
"if",
"(",
"src",
".",
"match",
"(",
"/",
"app.js$",
"/",
"i",
")",
")",
"{",
"findAppJs",
"=",
"true",
";",
"}",
"appScripts",
".",
"push",
"(",
"path",
".",
"join",
"(",
"grunt",
".",
"config",
".",
"get",
"(",
"'tmpdir'",
")",
",",
"src",
")",
".",
"replace",
"(",
"/",
"\\.js$",
"/",
"i",
",",
"'.ts'",
")",
")",
";",
"}",
")",
";",
"}",
")",
";",
"if",
"(",
"!",
"findAppJs",
")",
"{",
"grunt",
".",
"config",
".",
"set",
"(",
"'app_js_suffix'",
",",
"'-all'",
")",
";",
"}",
"grunt",
".",
"config",
".",
"set",
"(",
"'app_scripts'",
",",
"appScripts",
")",
";",
"}"
]
| ! extract app scripts and reset app.js script tag. | [
"!",
"extract",
"app",
"scripts",
"and",
"reset",
"app",
".",
"js",
"script",
"tag",
"."
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.lazyload.js#L135-L158 | train |
sony/cordova-plugin-cdp-nativebridge | dev/platforms/ios/cordova/lib/run.js | deployToSim | function deployToSim(appPath, target) {
// Select target device for emulator. Default is 'iPhone-6'
if (!target) {
return require('./list-emulator-images').run()
.then(function (emulators) {
if (emulators.length > 0) {
target = emulators[0];
}
emulators.forEach(function (emulator) {
if (emulator.indexOf('iPhone') === 0) {
target = emulator;
}
});
events.emit('log','No target specified for emulator. Deploying to ' + target + ' simulator');
return startSim(appPath, target);
});
} else {
return startSim(appPath, target);
}
} | javascript | function deployToSim(appPath, target) {
// Select target device for emulator. Default is 'iPhone-6'
if (!target) {
return require('./list-emulator-images').run()
.then(function (emulators) {
if (emulators.length > 0) {
target = emulators[0];
}
emulators.forEach(function (emulator) {
if (emulator.indexOf('iPhone') === 0) {
target = emulator;
}
});
events.emit('log','No target specified for emulator. Deploying to ' + target + ' simulator');
return startSim(appPath, target);
});
} else {
return startSim(appPath, target);
}
} | [
"function",
"deployToSim",
"(",
"appPath",
",",
"target",
")",
"{",
"if",
"(",
"!",
"target",
")",
"{",
"return",
"require",
"(",
"'./list-emulator-images'",
")",
".",
"run",
"(",
")",
".",
"then",
"(",
"function",
"(",
"emulators",
")",
"{",
"if",
"(",
"emulators",
".",
"length",
">",
"0",
")",
"{",
"target",
"=",
"emulators",
"[",
"0",
"]",
";",
"}",
"emulators",
".",
"forEach",
"(",
"function",
"(",
"emulator",
")",
"{",
"if",
"(",
"emulator",
".",
"indexOf",
"(",
"'iPhone'",
")",
"===",
"0",
")",
"{",
"target",
"=",
"emulator",
";",
"}",
"}",
")",
";",
"events",
".",
"emit",
"(",
"'log'",
",",
"'No target specified for emulator. Deploying to '",
"+",
"target",
"+",
"' simulator'",
")",
";",
"return",
"startSim",
"(",
"appPath",
",",
"target",
")",
";",
"}",
")",
";",
"}",
"else",
"{",
"return",
"startSim",
"(",
"appPath",
",",
"target",
")",
";",
"}",
"}"
]
| Deploy specified app package to ios-sim simulator
@param {String} appPath Path to application package
@param {String} target Target device type
@return {Promise} Resolves when deploy succeeds otherwise rejects | [
"Deploy",
"specified",
"app",
"package",
"to",
"ios",
"-",
"sim",
"simulator"
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/platforms/ios/cordova/lib/run.js#L147-L166 | train |
sony/cordova-plugin-cdp-nativebridge | dev/build/tasks/build.library.module.js | prepareCssModulesInfo | function prepareCssModulesInfo(docDom) {
var cssModule = { name: '' },
cssModulesInfo = [];
$(docDom).find('link[rel="stylesheet"]')
.filter(function () {
if (grunt.config.get('lib_kind_fileter_enable')) {
var type = path.join(grunt.config.get('lib_kind'), grunt.config.get('stylesheets'));
var regexp = new RegExp('^' + type + '\/', 'i');
return $(this).attr('href').match(regexp) ? true : false;
} else {
return true;
}
})
.each(function () {
var href = $(this).attr('href');
var name = href.slice(href.lastIndexOf('/') + 1, href.length).replace(/\.css$/i, '');
cssModule = {
name: name,
version: $(this).attr('data-version'),
};
cssModulesInfo.push(cssModule);
});
// set lib_css_modules_info
grunt.config.set('lib_css_modules_info', cssModulesInfo);
} | javascript | function prepareCssModulesInfo(docDom) {
var cssModule = { name: '' },
cssModulesInfo = [];
$(docDom).find('link[rel="stylesheet"]')
.filter(function () {
if (grunt.config.get('lib_kind_fileter_enable')) {
var type = path.join(grunt.config.get('lib_kind'), grunt.config.get('stylesheets'));
var regexp = new RegExp('^' + type + '\/', 'i');
return $(this).attr('href').match(regexp) ? true : false;
} else {
return true;
}
})
.each(function () {
var href = $(this).attr('href');
var name = href.slice(href.lastIndexOf('/') + 1, href.length).replace(/\.css$/i, '');
cssModule = {
name: name,
version: $(this).attr('data-version'),
};
cssModulesInfo.push(cssModule);
});
// set lib_css_modules_info
grunt.config.set('lib_css_modules_info', cssModulesInfo);
} | [
"function",
"prepareCssModulesInfo",
"(",
"docDom",
")",
"{",
"var",
"cssModule",
"=",
"{",
"name",
":",
"''",
"}",
",",
"cssModulesInfo",
"=",
"[",
"]",
";",
"$",
"(",
"docDom",
")",
".",
"find",
"(",
"'link[rel=\"stylesheet\"]'",
")",
".",
"filter",
"(",
"function",
"(",
")",
"{",
"if",
"(",
"grunt",
".",
"config",
".",
"get",
"(",
"'lib_kind_fileter_enable'",
")",
")",
"{",
"var",
"type",
"=",
"path",
".",
"join",
"(",
"grunt",
".",
"config",
".",
"get",
"(",
"'lib_kind'",
")",
",",
"grunt",
".",
"config",
".",
"get",
"(",
"'stylesheets'",
")",
")",
";",
"var",
"regexp",
"=",
"new",
"RegExp",
"(",
"'^'",
"+",
"type",
"+",
"'\\/'",
",",
"\\/",
")",
";",
"'i'",
"}",
"else",
"return",
"$",
"(",
"this",
")",
".",
"attr",
"(",
"'href'",
")",
".",
"match",
"(",
"regexp",
")",
"?",
"true",
":",
"false",
";",
"}",
")",
".",
"{",
"return",
"true",
";",
"}",
"each",
";",
"(",
"function",
"(",
")",
"{",
"var",
"href",
"=",
"$",
"(",
"this",
")",
".",
"attr",
"(",
"'href'",
")",
";",
"var",
"name",
"=",
"href",
".",
"slice",
"(",
"href",
".",
"lastIndexOf",
"(",
"'/'",
")",
"+",
"1",
",",
"href",
".",
"length",
")",
".",
"replace",
"(",
"/",
"\\.css$",
"/",
"i",
",",
"''",
")",
";",
"cssModule",
"=",
"{",
"name",
":",
"name",
",",
"version",
":",
"$",
"(",
"this",
")",
".",
"attr",
"(",
"'data-version'",
")",
",",
"}",
";",
"cssModulesInfo",
".",
"push",
"(",
"cssModule",
")",
";",
"}",
")",
"}"
]
| Helper API ! extract css libraries info. | [
"Helper",
"API",
"!",
"extract",
"css",
"libraries",
"info",
"."
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.library.module.js#L292-L316 | train |
sony/cordova-plugin-cdp-nativebridge | dev/build/tasks/build.lower.js | lowerScriptsInfo | function lowerScriptsInfo(docDom) {
// read index file, and getting target ts files.
var $scripts = $(docDom).find('script[src]');
$scripts.each(function () {
$(this).attr('src', function (idx, path) {
return path.toLowerCase();
});
});
} | javascript | function lowerScriptsInfo(docDom) {
// read index file, and getting target ts files.
var $scripts = $(docDom).find('script[src]');
$scripts.each(function () {
$(this).attr('src', function (idx, path) {
return path.toLowerCase();
});
});
} | [
"function",
"lowerScriptsInfo",
"(",
"docDom",
")",
"{",
"var",
"$scripts",
"=",
"$",
"(",
"docDom",
")",
".",
"find",
"(",
"'script[src]'",
")",
";",
"$scripts",
".",
"each",
"(",
"function",
"(",
")",
"{",
"$",
"(",
"this",
")",
".",
"attr",
"(",
"'src'",
",",
"function",
"(",
"idx",
",",
"path",
")",
"{",
"return",
"path",
".",
"toLowerCase",
"(",
")",
";",
"}",
")",
";",
"}",
")",
";",
"}"
]
| lower src of scripts . | [
"lower",
"src",
"of",
"scripts",
"."
]
| 6c4f0c3bb875a81395c9ce727f8f6e335a465705 | https://github.com/sony/cordova-plugin-cdp-nativebridge/blob/6c4f0c3bb875a81395c9ce727f8f6e335a465705/dev/build/tasks/build.lower.js#L96-L104 | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.