_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q51100
|
exportDiagramBulk
|
train
|
function exportDiagramBulk(diagrams, filename, format, options, fn) {
diagrams = diagrams || [];
filename = filename || "<%=diagram.name%>.png";
format = format || "png";
options = options || {};
// if elements parameter is selector expression, retrieve them from Repository.
if (_.isString(diagrams)) {
diagrams = mdjson.Repository.select(diagrams) || [];
}
_.extend(options, {
mdjson : mdjson,
root : mdjson.getRoot()
});
// Append predefined filters
if (!options.filters) {
options.filters = {};
}
_.extend(options.filters, filters);
var renderedFilename = "";
for (var i = 0, len = diagrams.length; i < len; i++) {
try {
options.diagram = diagrams[i];
renderedFilename = ejs.render(filename, options);
fs.ensureFileSync(renderedFilename);
if (format === "png") {
exportDiagramAsPNG(options.diagram, renderedFilename);
} else if (format === "svg") {
exportDiagramAsSVG(options.diagram, renderedFilename);
}
if (_.isFunction(fn)) {
fn(null, renderedFilename, options.diagram);
}
} catch (err) {
if (_.isFunction(fn)) {
fn(err);
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51101
|
getFee
|
train
|
function getFee(callback) {
var fee = this.remote.createTransaction()._computeFee();
callback(null, {fee: utils.dropsToXrp(fee)});
}
|
javascript
|
{
"resource": ""
}
|
q51102
|
isConnected
|
train
|
function isConnected(remote) {
if (isNaN(remote._ledger_current_index)) {
// Remote is missing the index of last ledger closed. Unprepared to submit
// transactions
return false;
}
var server = remote.getServer();
if (!server) {
return false;
}
if (remote._stand_alone) {
// If rippled is in standalone mode we can assume there will not be a
// ledger close within 30 seconds.
return true;
}
return (Date.now() - server._lastLedgerClose) <= CONNECTION_TIMEOUT;
}
|
javascript
|
{
"resource": ""
}
|
q51103
|
ensureConnected
|
train
|
function ensureConnected(remote, callback) {
if (remote.getServer()) {
callback(null, isConnected(remote));
} else {
callback(null, false);
}
}
|
javascript
|
{
"resource": ""
}
|
q51104
|
success
|
train
|
function success(response, body) {
var content = _.assign(body || {}, {success: true});
send(response, content, StatusCode.ok);
}
|
javascript
|
{
"resource": ""
}
|
q51105
|
transactionError
|
train
|
function transactionError(response, message, body) {
var content = errorContent(ErrorType.transaction, message, body);
send(response, content, StatusCode.internalServerError);
}
|
javascript
|
{
"resource": ""
}
|
q51106
|
apiError
|
train
|
function apiError(response, error) {
var content = errorContentExt(ErrorType.server, error);
send(response, content, StatusCode.internalServerError);
}
|
javascript
|
{
"resource": ""
}
|
q51107
|
invalidRequestError
|
train
|
function invalidRequestError(response, error) {
var content = errorContentExt(ErrorType.invalidRequest, error);
send(response, content, StatusCode.badRequest);
}
|
javascript
|
{
"resource": ""
}
|
q51108
|
internalError
|
train
|
function internalError(response, message, body) {
var content = errorContent(ErrorType.server, message, body);
send(response, content, StatusCode.internalServerError);
}
|
javascript
|
{
"resource": ""
}
|
q51109
|
connectionError
|
train
|
function connectionError(response, message, body) {
var content = errorContent(ErrorType.connection, message, body);
send(response, content, StatusCode.badGateway);
}
|
javascript
|
{
"resource": ""
}
|
q51110
|
timeOutError
|
train
|
function timeOutError(response, message, body) {
var content = errorContent(ErrorType.connection, message, body);
send(response, content, StatusCode.timeout);
}
|
javascript
|
{
"resource": ""
}
|
q51111
|
train
|
function(transaction, _callback) {
transaction.remote = api.remote;
if (options.blockDuplicates === true) {
blockDuplicates(transaction, options, _callback);
} else {
_callback(null, transaction);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51112
|
train
|
function(transaction, _callback) {
try {
transaction.secret(secret);
} catch (exception) {
return _callback(exception);
}
transaction.once('error', _callback);
transaction.once('submitted', function(message) {
if (message.result.slice(0, 3) === 'tec'
&& options.validated !== true) {
return formatTransactionResponseWrapper(transaction, message,
_callback);
}
// Handle erred transactions that should not make it into ledger (all
// errors that aren't tec-class). This function is called before the
// transaction `error` listener.
switch (message.engine_result) {
case 'terNO_ACCOUNT':
case 'terNO_AUTH':
case 'terNO_LINE':
case 'terINSUF_FEE_B':
// The transaction needs to be aborted. Preserve the original ter-
// class error for presentation to the client
transaction.removeListener('error', _callback);
transaction.once('error', function() {
_callback(message);
});
transaction.abort();
break;
}
});
transaction.once('proposed', function(message) {
if (options.validated !== true) {
formatTransactionResponseWrapper(transaction, message, _callback);
}
});
transaction.once('success', function(message) {
if (options.validated === true) {
formatTransactionResponseWrapper(transaction, message, _callback);
}
});
if (options.saveTransaction === true) {
transaction.on('state', function() {
var transactionSummary = transaction.summary();
if (transactionSummary.submitIndex !== undefined) {
api.db.saveTransaction(transactionSummary);
}
});
transaction.on('postsubmit', function() {
api.db.saveTransaction(transaction.summary());
});
}
transaction.submit();
}
|
javascript
|
{
"resource": ""
}
|
|
q51113
|
getTransactionAndRespond
|
train
|
function getTransactionAndRespond(account, identifier, options, callback) {
getTransaction(
this,
account,
identifier,
options,
function(error, transaction) {
if (error) {
callback(error);
} else {
callback(null, {transaction: transaction});
}
}
);
}
|
javascript
|
{
"resource": ""
}
|
q51114
|
getAccountTx
|
train
|
function getAccountTx(api, options, callback) {
var params = {
account: options.account,
ledger_index_min: options.ledger_index_min || options.ledger_index || -1,
ledger_index_max: options.ledger_index_max || options.ledger_index || -1,
limit: options.limit || DEFAULT_RESULTS_PER_PAGE,
forward: options.earliestFirst,
marker: options.marker
};
if (options.binary) {
params.binary = true;
}
api.remote.requestAccountTx(params, function(error, account_tx_results) {
if (error) {
return callback(error);
}
var transactions = [];
account_tx_results.transactions.forEach(function(tx_entry) {
if (!tx_entry.validated) {
return;
}
var tx = tx_entry.tx;
tx.meta = tx_entry.meta;
tx.validated = tx_entry.validated;
transactions.push(tx);
});
callback(null, {
transactions: transactions,
marker: account_tx_results.marker
});
});
}
|
javascript
|
{
"resource": ""
}
|
q51115
|
getLocalAndRemoteTransactions
|
train
|
function getLocalAndRemoteTransactions(api, options, callback) {
function queryRippled(_callback) {
getAccountTx(api, options, function(error, results) {
if (error) {
_callback(error);
} else {
// Set marker so that when this function is called again
// recursively it starts from the last place it left off
options.marker = results.marker;
_callback(null, results.transactions);
}
});
}
function queryDB(_callback) {
if (options.exclude_failed) {
_callback(null, []);
} else {
api.db.getFailedTransactions(options, _callback);
}
}
var transactionSources = [
queryRippled,
queryDB
];
async.parallel(transactionSources, function(error, sourceResults) {
if (error) {
return callback(error);
}
var results = sourceResults[0].concat(sourceResults[1]);
var transactions = _.uniq(results, function(tx) {
return tx.hash;
});
callback(null, transactions);
});
}
|
javascript
|
{
"resource": ""
}
|
q51116
|
transactionFilter
|
train
|
function transactionFilter(transactions, options) {
var filtered_transactions = transactions.filter(function(transaction) {
if (options.exclude_failed) {
if (transaction.state === 'failed' || (transaction.meta
&& transaction.meta.TransactionResult !== 'tesSUCCESS')) {
return false;
}
}
if (options.types && options.types.length > 0) {
if (options.types.indexOf(
transaction.TransactionType.toLowerCase()) === -1) {
return false;
}
}
if (options.source_account) {
if (transaction.Account !== options.source_account) {
return false;
}
}
if (options.destination_account) {
if (transaction.Destination !== options.destination_account) {
return false;
}
}
if (options.direction) {
if (options.direction === 'outgoing'
&& transaction.Account !== options.account) {
return false;
}
if (options.direction === 'incoming' && transaction.Destination
&& transaction.Destination !== options.account) {
return false;
}
}
return true;
});
return filtered_transactions;
}
|
javascript
|
{
"resource": ""
}
|
q51117
|
getAccountTransactions
|
train
|
function getAccountTransactions(api, options, callback) {
try {
validate.address(options.account);
} catch(err) {
return callback(err);
}
if (!options.min) {
options.min = module.exports.DEFAULT_RESULTS_PER_PAGE;
}
if (!options.max) {
options.max = Math.max(options.min,
module.exports.DEFAULT_RESULTS_PER_PAGE);
}
if (!options.limit) {
options.limit = module.exports.DEFAULT_LIMIT;
}
function queryTransactions(async_callback) {
getLocalAndRemoteTransactions(api, options, async_callback);
}
function filterTransactions(transactions, async_callback) {
async_callback(null, transactionFilter(transactions, options));
}
function sortTransactions(transactions, async_callback) {
var compare = options.earliestFirst ? utils.compareTransactions :
_.rearg(utils.compareTransactions, 1, 0);
transactions.sort(compare);
async_callback(null, transactions);
}
function mergeAndTruncateResults(transactions, async_callback) {
if (options.previous_transactions
&& options.previous_transactions.length > 0) {
transactions = options.previous_transactions.concat(transactions);
}
if (options.offset && options.offset > 0) {
var offset_remaining = options.offset - transactions.length;
transactions = transactions.slice(options.offset);
options.offset = offset_remaining;
}
if (transactions.length > options.max) {
transactions = transactions.slice(0, options.max);
}
async_callback(null, transactions);
}
function asyncWaterfallCallback(error, transactions) {
if (error) {
return callback(error);
}
if (!options.min || transactions.length >= options.min || !options.marker) {
callback(null, transactions);
} else {
options.previous_transactions = transactions;
setImmediate(function() {
getAccountTransactions(api, options, callback);
});
}
}
var steps = [
queryTransactions,
filterTransactions,
sortTransactions,
mergeAndTruncateResults
];
async.waterfall(steps, asyncWaterfallCallback);
}
|
javascript
|
{
"resource": ""
}
|
q51118
|
attachPreviousAndNextTransactionIdentifiers
|
train
|
function attachPreviousAndNextTransactionIdentifiers(api,
notificationDetails, topCallback) {
// Get all of the transactions affecting the specified
// account in the given ledger. This is done so that
// we can query for one more than that number on either
// side to ensure that we'll find the next and previous
// transactions, no matter how many transactions the
// given account had in the same ledger
function getAccountTransactionsInBaseTransactionLedger(callback) {
var params = {
account: notificationDetails.account,
ledger_index_min: notificationDetails.transaction.ledger_index,
ledger_index_max: notificationDetails.transaction.ledger_index,
exclude_failed: false,
max: 99999999,
limit: 200 // arbitrary, just checking number of transactions in ledger
};
transactions.getAccountTransactions(api, params, callback);
}
// All we care about is the count of the transactions
function countAccountTransactionsInBaseTransactionledger(txns, callback) {
callback(null, txns.length);
}
// Query for one more than the numTransactionsInLedger
// going forward and backwards to get a range of transactions
// that will definitely include the next and previous transactions
function getNextAndPreviousTransactions(numTransactionsInLedger, callback) {
async.concat([false, true], function(earliestFirst, concat_callback) {
var params = {
account: notificationDetails.account,
max: numTransactionsInLedger + 1,
min: numTransactionsInLedger + 1,
limit: numTransactionsInLedger + 1,
earliestFirst: earliestFirst
};
// In rippled -1 corresponds to the first or last ledger
// in its database, depending on whether it is the min or max value
if (params.earliestFirst) {
params.ledger_index_max = -1;
params.ledger_index_min = notificationDetails.transaction.ledger_index;
} else {
params.ledger_index_max = notificationDetails.transaction.ledger_index;
params.ledger_index_min = -1;
}
transactions.getAccountTransactions(api, params, concat_callback);
}, callback);
}
// Sort the transactions returned by ledger_index and remove duplicates
function sortTransactions(allTransactions, callback) {
allTransactions.push(notificationDetails.transaction);
var txns = _.uniq(allTransactions, function(tx) {
return tx.hash;
});
txns.sort(utils.compareTransactions);
callback(null, txns);
}
// Find the baseTransaction amongst the results. Because the
// transactions have been sorted, the next and previous transactions
// will be the ones on either side of the base transaction
function findPreviousAndNextTransactions(txns, callback) {
// Find the index in the array of the baseTransaction
var baseTransactionIndex = _.findIndex(txns, function(possibility) {
if (possibility.hash === notificationDetails.transaction.hash) {
return true;
} else if (possibility.client_resource_id &&
(possibility.client_resource_id ===
notificationDetails.transaction.client_resource_id ||
possibility.client_resource_id === notificationDetails.identifier)) {
return true;
}
return false;
});
// The previous transaction is the one with an index in
// the array of baseTransactionIndex - 1
if (baseTransactionIndex > 0) {
var previous_transaction = txns[baseTransactionIndex - 1];
notificationDetails.previous_transaction_identifier =
(previous_transaction.from_local_db ?
previous_transaction.client_resource_id : previous_transaction.hash);
notificationDetails.previous_hash = previous_transaction.hash;
}
// The next transaction is the one with an index in
// the array of baseTransactionIndex + 1
if (baseTransactionIndex + 1 < txns.length) {
var next_transaction = txns[baseTransactionIndex + 1];
notificationDetails.next_transaction_identifier =
(next_transaction.from_local_db ?
next_transaction.client_resource_id : next_transaction.hash);
notificationDetails.next_hash = next_transaction.hash;
}
callback(null, notificationDetails);
}
var steps = [
getAccountTransactionsInBaseTransactionLedger,
countAccountTransactionsInBaseTransactionledger,
getNextAndPreviousTransactions,
sortTransactions,
findPreviousAndNextTransactions
];
async.waterfall(steps, topCallback);
}
|
javascript
|
{
"resource": ""
}
|
q51119
|
getAccountTransactionsInBaseTransactionLedger
|
train
|
function getAccountTransactionsInBaseTransactionLedger(callback) {
var params = {
account: notificationDetails.account,
ledger_index_min: notificationDetails.transaction.ledger_index,
ledger_index_max: notificationDetails.transaction.ledger_index,
exclude_failed: false,
max: 99999999,
limit: 200 // arbitrary, just checking number of transactions in ledger
};
transactions.getAccountTransactions(api, params, callback);
}
|
javascript
|
{
"resource": ""
}
|
q51120
|
getNextAndPreviousTransactions
|
train
|
function getNextAndPreviousTransactions(numTransactionsInLedger, callback) {
async.concat([false, true], function(earliestFirst, concat_callback) {
var params = {
account: notificationDetails.account,
max: numTransactionsInLedger + 1,
min: numTransactionsInLedger + 1,
limit: numTransactionsInLedger + 1,
earliestFirst: earliestFirst
};
// In rippled -1 corresponds to the first or last ledger
// in its database, depending on whether it is the min or max value
if (params.earliestFirst) {
params.ledger_index_max = -1;
params.ledger_index_min = notificationDetails.transaction.ledger_index;
} else {
params.ledger_index_max = notificationDetails.transaction.ledger_index;
params.ledger_index_min = -1;
}
transactions.getAccountTransactions(api, params, concat_callback);
}, callback);
}
|
javascript
|
{
"resource": ""
}
|
q51121
|
sortTransactions
|
train
|
function sortTransactions(allTransactions, callback) {
allTransactions.push(notificationDetails.transaction);
var txns = _.uniq(allTransactions, function(tx) {
return tx.hash;
});
txns.sort(utils.compareTransactions);
callback(null, txns);
}
|
javascript
|
{
"resource": ""
}
|
q51122
|
findPreviousAndNextTransactions
|
train
|
function findPreviousAndNextTransactions(txns, callback) {
// Find the index in the array of the baseTransaction
var baseTransactionIndex = _.findIndex(txns, function(possibility) {
if (possibility.hash === notificationDetails.transaction.hash) {
return true;
} else if (possibility.client_resource_id &&
(possibility.client_resource_id ===
notificationDetails.transaction.client_resource_id ||
possibility.client_resource_id === notificationDetails.identifier)) {
return true;
}
return false;
});
// The previous transaction is the one with an index in
// the array of baseTransactionIndex - 1
if (baseTransactionIndex > 0) {
var previous_transaction = txns[baseTransactionIndex - 1];
notificationDetails.previous_transaction_identifier =
(previous_transaction.from_local_db ?
previous_transaction.client_resource_id : previous_transaction.hash);
notificationDetails.previous_hash = previous_transaction.hash;
}
// The next transaction is the one with an index in
// the array of baseTransactionIndex + 1
if (baseTransactionIndex + 1 < txns.length) {
var next_transaction = txns[baseTransactionIndex + 1];
notificationDetails.next_transaction_identifier =
(next_transaction.from_local_db ?
next_transaction.client_resource_id : next_transaction.hash);
notificationDetails.next_hash = next_transaction.hash;
}
callback(null, notificationDetails);
}
|
javascript
|
{
"resource": ""
}
|
q51123
|
getNotificationHelper
|
train
|
function getNotificationHelper(api, account, identifier, urlBase, topCallback) {
function getTransaction(callback) {
try {
transactions.getTransaction(api, account, identifier, {}, callback);
} catch(err) {
callback(err);
}
}
function checkLedger(baseTransaction, callback) {
serverLib.remoteHasLedger(api.remote, baseTransaction.ledger_index,
function(error, remoteHasLedger) {
if (error) {
return callback(error);
}
if (remoteHasLedger) {
callback(null, baseTransaction);
} else {
callback(new errors.NotFoundError('Cannot Get Notification. ' +
'This transaction is not in the ripple\'s complete ledger set. ' +
'Because there is a gap in the rippled\'s historical database it ' +
'is not possible to determine the transactions that precede this one')
);
}
});
}
function prepareNotificationDetails(baseTransaction, callback) {
var notificationDetails = {
account: account,
identifier: identifier,
transaction: baseTransaction
};
// Move client_resource_id to notificationDetails from transaction
if (baseTransaction.client_resource_id) {
notificationDetails.client_resource_id =
baseTransaction.client_resource_id;
}
attachPreviousAndNextTransactionIdentifiers(api, notificationDetails,
callback);
}
// Parse the Notification object from the notificationDetails
function parseNotificationDetails(notificationDetails, callback) {
callback(null, NotificationParser.parse(notificationDetails, urlBase));
}
function formatNotificationResponse(notificationDetails, callback) {
var responseBody = {
notification: notificationDetails
};
// Move client_resource_id to response body instead of inside
// the Notification
var client_resource_id = responseBody.notification.client_resource_id;
delete responseBody.notification.client_resource_id;
if (client_resource_id) {
responseBody.client_resource_id = client_resource_id;
}
callback(null, responseBody);
}
var steps = [
getTransaction,
checkLedger,
prepareNotificationDetails,
parseNotificationDetails,
formatNotificationResponse
];
async.waterfall(steps, topCallback);
}
|
javascript
|
{
"resource": ""
}
|
q51124
|
getNotification
|
train
|
function getNotification(account, identifier, urlBase, callback) {
validate.address(account);
validate.paymentIdentifier(identifier);
return getNotificationHelper(this, account, identifier, urlBase, callback);
}
|
javascript
|
{
"resource": ""
}
|
q51125
|
getNotifications
|
train
|
function getNotifications(account, urlBase, options, callback) {
validate.address(account);
var self = this;
function getTransactions(_callback) {
var resultsPerPage = options.results_per_page ||
transactions.DEFAULT_RESULTS_PER_PAGE;
var offset = resultsPerPage * ((options.page || 1) - 1);
var args = {
account: account,
direction: options.direction,
min: resultsPerPage,
max: resultsPerPage,
ledger_index_min: options.ledger_min,
ledger_index_max: options.ledger_max,
offset: offset,
earliestFirst: options.earliest_first
};
transactions.getAccountTransactions(self, args, _callback);
}
function parseNotifications(baseTransactions, _callback) {
var numTransactions = baseTransactions.length;
function parseNotification(transaction, __callback) {
var args = {
account: account,
identifier: transaction.hash,
transaction: transaction
};
// Attaching previous and next identifiers
var idx = baseTransactions.indexOf(transaction);
var previous = baseTransactions[idx - 1];
var next = baseTransactions[idx + 1];
if (!options.earliest_first) {
args.previous_hash = previous ? previous.hash : undefined;
args.next_hash = next ? next.hash : undefined;
} else {
args.previous_hash = next ? next.hash : undefined;
args.next_hash = previous ? previous.hash : undefined;
}
args.previous_transaction_identifier = args.previous_hash;
args.next_transaction_identifier = args.next_hash;
var firstAndPaging = options.page &&
(options.earliest_first ?
args.previous_hash === undefined : args.next_hash === undefined);
var last = idx === numTransactions - 1;
if (firstAndPaging || last) {
attachPreviousAndNextTransactionIdentifiers(self, args,
function(err, _args) {
return __callback(err, NotificationParser.parse(_args, urlBase));
}
);
} else {
return __callback(null, NotificationParser.parse(args, urlBase));
}
}
return async.map(baseTransactions, parseNotification, _callback);
}
function formatResponse(notifications, _callback) {
_callback(null, {notifications: notifications});
}
var steps = [
getTransactions,
_.partial(utils.attachDate, self),
parseNotifications,
formatResponse
];
return async.waterfall(steps, callback);
}
|
javascript
|
{
"resource": ""
}
|
q51126
|
getSettings
|
train
|
function getSettings(account, callback) {
validate.address(account);
this.remote.requestAccountInfo({account: account}, function(error, info) {
if (error) {
return callback(error);
}
var data = info.account_data;
var settings = {
account: data.Account,
transfer_rate: '0'
};
// Attach account flags
_.extend(settings, TxToRestConverter.parseFlagsFromResponse(data.Flags,
constants.AccountRootFlags));
// Attach account fields
_.extend(settings, parseFieldsFromResponse(data,
constants.AccountRootFields));
settings.transaction_sequence = String(settings.transaction_sequence);
callback(null, {settings: settings});
});
}
|
javascript
|
{
"resource": ""
}
|
q51127
|
changeSettings
|
train
|
function changeSettings(account, settings, secret, options, callback) {
var transaction = createSettingsTransaction(account, settings);
var converter = _.partial(
TxToRestConverter.parseSettingsResponseFromTx, settings);
transact(transaction, this, secret, options, converter, callback);
}
|
javascript
|
{
"resource": ""
}
|
q51128
|
setTransactionBitFlags
|
train
|
function setTransactionBitFlags(transaction, options) {
for (var flagName in options.flags) {
var flag = options.flags[flagName];
// Set transaction flags
if (!(flag.name in options.input)) {
continue;
}
var value = options.input[flag.name];
if (value === options.clear_setting) {
value = false;
}
if (flag.unset) {
transaction.setFlags(value ? flag.set : flag.unset);
} else if (flag.set && value) {
transaction.setFlags(flag.set);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51129
|
formatPaymentHelper
|
train
|
function formatPaymentHelper(account, txJSON) {
if (!(txJSON && /^payment$/i.test(txJSON.TransactionType))) {
throw new InvalidRequestError('Not a payment. The transaction '
+ 'corresponding to the given identifier is not a payment.');
}
var metadata = {
client_resource_id: txJSON.client_resource_id || '',
hash: txJSON.hash || '',
ledger: String(!_.isUndefined(txJSON.inLedger) ?
txJSON.inLedger : txJSON.ledger_index),
state: txJSON.validated === true ? 'validated' : 'pending'
};
var message = {tx_json: txJSON};
var meta = txJSON.meta;
var parsed = TxToRestConverter.parsePaymentFromTx(account, message, meta);
return _.assign({payment: parsed.payment}, metadata);
}
|
javascript
|
{
"resource": ""
}
|
q51130
|
submitPayment
|
train
|
function submitPayment(account, payment, clientResourceID, secret,
urlBase, options, callback) {
function formatTransactionResponse(message, meta) {
if (meta.state === 'validated') {
var txJSON = message.tx_json;
txJSON.meta = message.metadata;
txJSON.validated = message.validated;
txJSON.ledger_index = txJSON.inLedger = message.ledger_index;
return formatPaymentHelper(payment.source_account, txJSON);
}
return {
client_resource_id: clientResourceID,
status_url: urlBase + '/v1/accounts/' + payment.source_account
+ '/payments/' + clientResourceID
};
}
function prepareTransaction(_transaction, remote) {
validate.client_resource_id(clientResourceID);
_transaction.lastLedger(Number(options.last_ledger_sequence ||
(remote.getLedgerSequence() + transactions.DEFAULT_LEDGER_BUFFER)));
if (Number(options.max_fee) >= 0) {
_transaction.maxFee(Number(xrpToDrops(options.max_fee)));
}
if (Number(options.fixed_fee) >= 0) {
_transaction.setFixedFee(Number(xrpToDrops(options.fixed_fee)));
}
_transaction.clientID(clientResourceID);
return _transaction;
}
var isSubmitMode = options.submit !== false;
var _options = _.assign({}, options, {
clientResourceId: clientResourceID,
blockDuplicates: isSubmitMode,
saveTransaction: isSubmitMode
});
var initialTx = createPaymentTransaction(account, payment);
var transaction = isSubmitMode ? prepareTransaction(
initialTx, this.remote) : initialTx;
var converter = isSubmitMode ? formatTransactionResponse :
_.partial(TxToRestConverter.parsePaymentFromTx, account);
transact(transaction, this, secret, _options, converter, callback);
}
|
javascript
|
{
"resource": ""
}
|
q51131
|
getPayment
|
train
|
function getPayment(account, identifier, callback) {
var self = this;
validate.address(account);
validate.paymentIdentifier(identifier);
// If the transaction was not in the outgoing_transactions db,
// get it from rippled
function getTransaction(_callback) {
transactions.getTransaction(self, account, identifier, {}, _callback);
}
var steps = [
getTransaction,
asyncify(_.partial(formatPaymentHelper, account))
];
async.waterfall(steps, callback);
}
|
javascript
|
{
"resource": ""
}
|
q51132
|
getAccountPayments
|
train
|
function getAccountPayments(account, source_account, destination_account,
direction, options, callback) {
var self = this;
function getTransactions(_callback) {
var args = {
account: account,
source_account: source_account,
destination_account: destination_account,
direction: direction,
min: options.results_per_page,
max: options.results_per_page,
offset: (options.results_per_page || DEFAULT_RESULTS_PER_PAGE)
* ((options.page || 1) - 1),
types: ['payment'],
earliestFirst: options.earliest_first
};
transactions.getAccountTransactions(self,
_.merge(options, args), _callback);
}
function formatTransactions(_transactions) {
return _transactions.map(_.partial(formatPaymentHelper, account));
}
function attachResourceId(_transactions, _callback) {
async.map(_transactions, function(paymentResult, async_map_callback) {
var hash = paymentResult.hash;
self.db.getTransaction({hash: hash}, function(error, db_entry) {
if (error) {
return async_map_callback(error);
}
var client_resource_id = '';
if (db_entry && db_entry.client_resource_id) {
client_resource_id = db_entry.client_resource_id;
}
paymentResult.client_resource_id = client_resource_id;
async_map_callback(null, paymentResult);
});
}, _callback);
}
function formatResponse(_transactions) {
return {payments: _transactions};
}
var steps = [
getTransactions,
_.partial(utils.attachDate, self),
asyncify(formatTransactions),
attachResourceId,
asyncify(formatResponse)
];
async.waterfall(steps, callback);
}
|
javascript
|
{
"resource": ""
}
|
q51133
|
getOrders
|
train
|
function getOrders(account, options, callback) {
var self = this;
validate.address(account);
validate.options(options);
function getAccountOrders(prevResult) {
var isAggregate = options.limit === 'all';
if (prevResult && (!isAggregate || !prevResult.marker)) {
return Promise.resolve(prevResult);
}
var promise = new Promise(function(resolve, reject) {
var accountOrdersRequest;
var marker;
var ledger;
var limit;
if (prevResult) {
marker = prevResult.marker;
limit = prevResult.limit;
ledger = prevResult.ledger_index;
} else {
marker = options.marker;
limit = validator.isValid(options.limit, 'UINT32') ?
Number(options.limit) : DefaultPageLimit;
ledger = utils.parseLedger(options.ledger);
}
accountOrdersRequest = self.remote.requestAccountOffers({
account: account,
marker: marker,
limit: limit,
ledger: ledger
});
accountOrdersRequest.once('error', reject);
accountOrdersRequest.once('success', function(nextResult) {
nextResult.offers = prevResult ?
nextResult.offers.concat(prevResult.offers) : nextResult.offers;
resolve(nextResult);
});
accountOrdersRequest.request();
});
return promise.then(getAccountOrders);
}
function getParsedOrders(offers) {
return _.reduce(offers, function(orders, off) {
var sequence = off.seq;
var type = off.flags & ripple.Remote.flags.offer.Sell ? 'sell' : 'buy';
var passive = (off.flags & ripple.Remote.flags.offer.Passive) !== 0;
var taker_gets = utils.parseCurrencyAmount(off.taker_gets);
var taker_pays = utils.parseCurrencyAmount(off.taker_pays);
orders.push({
type: type,
taker_gets: taker_gets,
taker_pays: taker_pays,
sequence: sequence,
passive: passive
});
return orders;
}, []);
}
function respondWithOrders(result) {
var promise = new Promise(function(resolve) {
var orders = {};
if (result.marker) {
orders.marker = result.marker;
}
orders.limit = result.limit;
orders.ledger = result.ledger_index;
orders.validated = result.validated;
orders.orders = getParsedOrders(result.offers);
resolve(callback(null, orders));
});
return promise;
}
getAccountOrders()
.then(respondWithOrders)
.catch(callback);
}
|
javascript
|
{
"resource": ""
}
|
q51134
|
placeOrder
|
train
|
function placeOrder(account, order, secret, options, callback) {
var transaction = createOrderTransaction(account, order);
var converter = TxToRestConverter.parseSubmitOrderFromTx;
transact(transaction, this, secret, options, converter, callback);
}
|
javascript
|
{
"resource": ""
}
|
q51135
|
cancelOrder
|
train
|
function cancelOrder(account, sequence, secret, options, callback) {
var transaction = createOrderCancellationTransaction(account, sequence);
var converter = TxToRestConverter.parseCancelOrderFromTx;
transact(transaction, this, secret, options, converter, callback);
}
|
javascript
|
{
"resource": ""
}
|
q51136
|
padValue
|
train
|
function padValue(value, length) {
assert.strictEqual(typeof value, 'string');
assert.strictEqual(typeof length, 'number');
var result = value;
while (result.length < length) {
result = '0' + result;
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q51137
|
setTransactionIntFlags
|
train
|
function setTransactionIntFlags(transaction, input, flags) {
for (var flagName in flags) {
var flag = flags[flagName];
if (!input.hasOwnProperty(flag.name)) {
continue;
}
var value = input[flag.name];
if (value) {
transaction.tx_json.SetFlag = flag.value;
} else {
transaction.tx_json.ClearFlag = flag.value;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51138
|
setTransactionFields
|
train
|
function setTransactionFields(transaction, input, fieldSchema) {
for (var fieldName in fieldSchema) {
var field = fieldSchema[fieldName];
var value = input[field.name];
if (typeof value === 'undefined') {
continue;
}
// The value required to clear an account root field varies
if (value === CLEAR_SETTING && field.hasOwnProperty('defaults')) {
value = field.defaults;
}
if (field.encoding === 'hex') {
// If the field is supposed to be hex, why don't we do a
// toString('hex') on it?
if (field.length) {
// Field is fixed length, why are we checking here though?
// We could move this to validateInputs
if (value.length > field.length) {
throw new InvalidRequestError(
'Parameter length exceeded: ' + fieldName);
} else if (value.length < field.length) {
value = padValue(value, field.length);
}
} else {
// Field is variable length. Expecting an ascii string as input.
// This is currently only used for Domain field
value = new Buffer(value, 'ascii').toString('hex');
}
value = value.toUpperCase();
}
transaction.tx_json[fieldName] = value;
}
}
|
javascript
|
{
"resource": ""
}
|
q51139
|
renameCounterpartyToIssuerInOrderChanges
|
train
|
function renameCounterpartyToIssuerInOrderChanges(orderChanges) {
return _.mapValues(orderChanges, function(changes) {
return _.map(changes, function(change) {
return utils.renameCounterpartyToIssuerInOrder(change);
});
});
}
|
javascript
|
{
"resource": ""
}
|
q51140
|
parseFlagsFromResponse
|
train
|
function parseFlagsFromResponse(responseFlags, flags) {
var parsedFlags = {};
for (var flagName in flags) {
var flag = flags[flagName];
parsedFlags[flag.name] = Boolean(responseFlags & flag.value);
}
return parsedFlags;
}
|
javascript
|
{
"resource": ""
}
|
q51141
|
parseOrderFromTx
|
train
|
function parseOrderFromTx(tx, options) {
if (!options.account) {
throw new Error('Internal Error. must supply options.account');
}
if (tx.TransactionType !== 'OfferCreate'
&& tx.TransactionType !== 'OfferCancel') {
throw new Error('Invalid parameter: identifier. The transaction '
+ 'corresponding to the given identifier is not an order');
}
if (tx.meta !== undefined && tx.meta.TransactionResult !== undefined) {
if (tx.meta.TransactionResult === 'tejSecretInvalid') {
throw new Error('Invalid secret provided.');
}
}
var order;
var flags = parseFlagsFromResponse(tx.flags, constants.OfferCreateFlags);
var action = tx.TransactionType === 'OfferCreate'
? 'order_create' : 'order_cancel';
var balance_changes = tx.meta
? parseBalanceChanges(tx.meta)[options.account] || [] : [];
var timestamp = tx.date
? new Date(ripple.utils.toTimestamp(tx.date)).toISOString() : '';
var order_changes = tx.meta ?
parseOrderBookChanges(tx.meta)[options.account] : [];
var direction;
if (options.account === tx.Account) {
direction = 'outgoing';
} else if (balance_changes.length && order_changes.length) {
direction = 'incoming';
} else {
direction = 'passthrough';
}
if (action === 'order_create') {
order = {
account: tx.Account,
taker_pays: utils.parseCurrencyAmount(tx.TakerPays),
taker_gets: utils.parseCurrencyAmount(tx.TakerGets),
passive: flags.passive,
immediate_or_cancel: flags.immediate_or_cancel,
fill_or_kill: flags.fill_or_kill,
type: flags.sell ? 'sell' : 'buy',
sequence: tx.Sequence
};
} else {
order = {
account: tx.Account,
type: 'cancel',
sequence: tx.Sequence,
cancel_sequence: tx.OfferSequence
};
}
return {
hash: tx.hash,
ledger: tx.ledger_index,
validated: tx.validated,
timestamp: timestamp,
fee: utils.dropsToXrp(tx.Fee),
action: action,
direction: direction,
order: order,
balance_changes: balance_changes,
order_changes: order_changes || []
};
}
|
javascript
|
{
"resource": ""
}
|
q51142
|
parsePaymentsFromPathFind
|
train
|
function parsePaymentsFromPathFind(pathfindResults) {
return pathfindResults.alternatives.map(function(alternative) {
return {
source_account: pathfindResults.source_account,
source_tag: '',
source_amount: (typeof alternative.source_amount === 'string' ?
{
value: utils.dropsToXrp(alternative.source_amount),
currency: 'XRP',
issuer: ''
} :
{
value: alternative.source_amount.value,
currency: alternative.source_amount.currency,
issuer: (typeof alternative.source_amount.issuer !== 'string'
|| alternative.source_amount.issuer === pathfindResults.source_account
? '' : alternative.source_amount.issuer)
}),
source_slippage: '0',
destination_account: pathfindResults.destination_account,
destination_tag: '',
destination_amount: (
typeof pathfindResults.destination_amount === 'string' ?
{
value: utils.dropsToXrp(pathfindResults.destination_amount),
currency: 'XRP',
issuer: ''
} :
{
value: pathfindResults.destination_amount.value,
currency: pathfindResults.destination_amount.currency,
issuer: pathfindResults.destination_amount.issuer
}),
invoice_id: '',
paths: JSON.stringify(alternative.paths_computed),
partial_payment: false,
no_direct_ripple: false
};
});
}
|
javascript
|
{
"resource": ""
}
|
q51143
|
addTrustLine
|
train
|
function addTrustLine(account, trustline, secret, options, callback) {
var transaction = createTrustLineTransaction(account, trustline);
var converter = TxToRestConverter.parseTrustResponseFromTx;
transact(transaction, this, secret, options, converter, callback);
}
|
javascript
|
{
"resource": ""
}
|
q51144
|
getStylingNodes
|
train
|
function getStylingNodes (selector) {
if (typeof queryCache[selector] === 'undefined') {
queryCache[selector] = Array.prototype.map.call(
document.querySelectorAll(selector),
function (stylesheet) {
return stylesheet.outerHTML;
}
).join('');
}
return queryCache[selector];
}
|
javascript
|
{
"resource": ""
}
|
q51145
|
getIframeContentForNode
|
train
|
function getIframeContentForNode (node, options) {
return '<!doctype html>' +
'<html ' + options.htmlAttr + '>' +
'<head>' +
options.metaCharset +
options.metaViewport +
options.stylesheets +
options.styles +
'</head>' +
'<body ' + options.bodyAttr + '>' +
node.innerHTML +
'</body>' +
'</html>';
}
|
javascript
|
{
"resource": ""
}
|
q51146
|
formatAttributes
|
train
|
function formatAttributes (attrObj) {
var attributes = [];
for (var attribute in attrObj) {
attributes.push(attribute + '="' + attrObj[attribute] + '"');
}
return attributes.join(' ');
}
|
javascript
|
{
"resource": ""
}
|
q51147
|
iframify
|
train
|
function iframify (node, options) {
options = getOptions(options);
var iframe = document.createElement('iframe');
var html = getIframeContentForNode(node, options);
iframe.srcdoc = html;
if (!('srcdoc' in iframe)) {
console.log(
'Your browser does not support the `srcdoc` attribute on elements.' +
'Therefore, it is not possible to wrap this node with an iframe due' +
'to CORS policy.'
);
return null;
}
node.parentNode.replaceChild(iframe, node);
setTimeout(function () {
var iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
iframe.height = getDocumentHeight(iframeDocument);
}, options.sizingTimeout);
return iframe;
}
|
javascript
|
{
"resource": ""
}
|
q51148
|
Loader
|
train
|
function Loader () {
var FINAL_STATES = {'loaded': true, 'complete': true, 4: true}
var head = document.getElementsByTagName('head')[0]
var pending = {}
var counter = 0
return {
/**
* @private
* @callback dataCallback
* @memberof Loader.prototype
* @param {object|string} data JSON object, or string returned by request as `responseText`.
*/
/**
* Loads and returns a JSON resource asynchronously, using XMLHttpRequest (AJAX).
* @memberof Loader.prototype
* @param {string} src HTTP(S) URL of the JSON resource to load.
* @param {dataCallback} cb Callback function with request's data as first parameter.
*/
loadJSON: function (src, cb) {
// if (pending[src]) return cb && cb();
// pending[src] = true;
// cross-domain ajax call
var xdr = new window.XMLHttpRequest()
xdr.onload = function () {
var data = xdr.responseText
try {
data = JSON.parse(data)
} catch (e) {};
cb(data)
// delete pending[src];
}
xdr.open('GET', src, true)
xdr.send()
},
/**
* @private
* @callback errorCallback
* @memberof Loader.prototype
* @param {Error} error Error caught thru the `error` event or `appendChild()` call, if any.
*/
/**
* Loads a JavaScript resource into the page.
* @memberof Loader.prototype
* @param {string} src HTTP(S) URL of the JavaScript resource to load into the page.
* @param {errorCallback} cb Callback function with error as first parameter, if any.
*/
includeJS: function (src, cb) {
var inc, nt
if (pending[src]) {
if (cb) {
nt = setInterval(function () {
if (pending[src]) { return console.log('still loading', src, '...') }
clearInterval(nt)
cb()
}, 50)
}
return
}
pending[src] = true
inc = document.createElement('script')
// inc.async = "async";
inc.onload = function () {
if (!pending[src]) { return }
delete pending[src]
cb && setTimeout(cb, 1)
delete inc.onload
}
inc.onerror = function (e) {
e.preventDefault()
inc.onload(e)
}
inc.onreadystatechange = function () {
if (!inc.readyState || FINAL_STATES[inc.readyState]) { inc.onload() }
}
try {
inc.src = src
head.appendChild(inc)
} catch (e) {
console.error('Error while including', src, e)
cb(e)
}
},
/**
* Loads and returns a JSON resource asynchronously, by including it into the page (not AJAX).
* @memberof Loader.prototype
* @param {string} src HTTP(S) URL of the JSON resource to load.
* @param {function} cb Callback function, called by the resource's script.
*/
loadJSONP: function (src, cb) {
var callbackFct = '__loadjsonp__' + (counter++)
window[callbackFct] = function () {
cb.apply(window, arguments)
delete window[callbackFct]
}
this.includeJS(src + (src.indexOf('?') == -1 ? '?' : '&') + 'callback=' + callbackFct, function () {
// if http request fails (e.g. 404 error / no content)
setTimeout(window[callbackFct], 10)
})
}
}
}
|
javascript
|
{
"resource": ""
}
|
q51149
|
createEventHandlers
|
train
|
function createEventHandlers (playemFunctions) {
var eventHandlers = {
onApiReady: function (player) {
// console.log(player.label + " api ready");
if (whenReady && player == whenReady.player) { whenReady.fct() }
if (--playersToLoad == 0) { that.emit('onReady') }
},
onEmbedReady: function (player) {
// console.log("embed ready");
setVolume(volume)
},
onBuffering: function (player) {
setTimeout(function () {
setPlayTimeout()
that.emit('onBuffering')
})
},
onPlaying: function (player) {
// console.log(player.label + ".onPlaying");
// setPlayTimeout(); // removed because soundcloud sends a "onPlaying" event, even for not authorized tracks
setVolume(volume)
setTimeout(function () {
that.emit('onPlay')
}, 1)
if (player.trackInfo && player.trackInfo.duration) {
eventHandlers.onTrackInfo({
position: player.trackInfo.position || 0,
duration: player.trackInfo.duration
})
}
if (progress) { clearInterval(progress) }
if (player.getTrackPosition) {
// var that = eventHandlers; //this;
progress = setInterval(function () {
player.getTrackPosition(function (trackPos) {
eventHandlers.onTrackInfo({
position: trackPos,
duration: player.trackInfo.duration || currentTrack.trackDuration
})
})
}, 1000)
}
},
onTrackInfo: function (trackInfo) {
// console.log("ontrackinfo", trackInfo, currentTrack);
if (currentTrack && trackInfo) {
if (trackInfo.duration) {
currentTrack.trackDuration = trackInfo.duration
setPlayTimeout()
}
if (trackInfo.position) { currentTrack.trackPosition = trackInfo.position }
}
that.emit('onTrackInfo', currentTrack)
},
onPaused: function (player) {
// console.log(player.label + ".onPaused");
setPlayTimeout()
if (progress) { clearInterval(progress) }
progress = null
// if (!avoidPauseEventPropagation)
// that.emit("onPause");
// avoidPauseEventPropagation = false;
},
onEnded: function (player) {
// console.log(player.label + ".onEnded");
stopTrack()
that.emit('onEnd')
playemFunctions.next()
},
onError: function (player, error) {
console.error(player.label + ' error:', ((error || {}).exception || error || {}).stack || error)
setPlayTimeout()
that.emit('onError', error)
}
};
// handlers will only be triggered is their associated player is currently active
['onEmbedReady', 'onBuffering', 'onPlaying', 'onPaused', 'onEnded', 'onError'].map(function (evt) {
var fct = eventHandlers[evt]
eventHandlers[evt] = function (player, x) {
if (currentTrack && player == currentTrack.player) { return fct(player, x) }
/*
else if (evt != "onEmbedReady")
console.warn("ignore event:", evt, "from", player, "instead of:", currentTrack.player);
*/
}
})
return eventHandlers
}
|
javascript
|
{
"resource": ""
}
|
q51150
|
train
|
function( url, dir, options, callback ) {
if ( typeof options === 'function' ) {
callback = options;
options = null;
}
options = options || {};
addExtraOptions( [ 'force', 'quiet', 'revision', 'depth', 'ignoreExternals' ], options );
var dirPath = dir;
if(typeof options.cwd !== 'undefined')
dirPath = path.resolve(options.cwd, dir);
if ( !fs.existsSync( dirPath ) ) {
fs.mkdirsSync( dirPath );
}
executeSvn( [ 'checkout', url, dir ], options, callback );
}
|
javascript
|
{
"resource": ""
}
|
|
q51151
|
train
|
function( files, options, callback ) {
if ( !Array.isArray( files ) ) {
files = [files];
}
if ( typeof options === 'function' ) {
callback = options;
options = null;
} else if ( typeof options === 'string' ) {
options = { msg: options };
}
options = options || {};
addExtraOptions( [ 'quiet', 'depth', 'msg' ], options );
executeSvn( [ 'commit' ].concat( files ), options, callback );
}
|
javascript
|
{
"resource": ""
}
|
|
q51152
|
train
|
function( url, wc, options, callback ) {
if ( typeof options === 'function' ) {
callback = options;
options = null;
}
options = options || {};
executeSvn( [ 'relocate', url, wc ], options, callback );
}
|
javascript
|
{
"resource": ""
}
|
|
q51153
|
train
|
function( wc, options, callback ) {
if ( typeof options === 'function' ) {
callback = options;
options = null;
}
options = options || {};
addExtraOptions( [ 'quiet', 'depth' ], options );
executeSvnXml( [ 'status', wc ], options, callback );
}
|
javascript
|
{
"resource": ""
}
|
|
q51154
|
train
|
function( wcs, options, callback ) {
if ( typeof options === 'function' ) {
callback = options;
options = null;
}
if ( !Array.isArray( wcs ) ) {
wcs = [wcs];
}
options = options || {};
addExtraOptions( [ 'force', 'quiet', 'revision', 'depth', 'ignoreExternals' ], options );
executeSvn( [ 'update' ].concat( wcs ), options, callback );
}
|
javascript
|
{
"resource": ""
}
|
|
q51155
|
train
|
function( target, options, callback ) {
if ( typeof options === "function" ) {
callback = options;
options = null;
}
options = options || {};
info( target, options, function( err, data ) {
var rev;
if ( !err ) {
var revString;
if ( options.lastChangeRevision ) {
if ( data && data.entry && data.entry.commit && data.entry.commit.$ && data.entry.commit.$.revision ) {
revString = data.entry.commit.$.revision;
}
} else {
if ( data && data.entry && data.entry.$ && data.entry.$.revision ) {
revString = data.entry.$.revision;
}
}
if ( revString !== undefined ) {
try {
rev = parseInt( revString, 10 );
}
catch ( err3 ) {
err = 'Invalid revision value [' + revString + ']';
}
} else {
err = 'Could not parse info result to get revision [' + JSON.stringify( data ) + ']';
}
}
callback( err, rev );
} );
}
|
javascript
|
{
"resource": ""
}
|
|
q51156
|
train
|
function( wcDir, options, callback ) {
if ( typeof options === "function" ) {
callback = options;
options = null;
}
options = options || {};
if ( !Array.isArray( wcDir ) ) {
wcDir = [wcDir];
}
var args = [ '-n' ];
if ( options.lastChangeRevision ) {
args.push( '-c' );
}
execSvnVersion( wcDir.concat( args ), options, function( err, data ) {
var result;
if ( !err ) {
var match = data.match( /(\d+):?(\d*)(\w*)/ );
if ( match ) {
result = {};
result.low = parseInt( match[1] );
if ( match[2].length > 0 ) {
result.high = parseInt( match[2] );
} else {
result.high = result.low;
}
result.flags = match[3];
if ( result.flags.length > 0 ) {
result.modified = result.flags.indexOf( 'M' ) >= 0;
result.partial = result.flags.indexOf( 'P' ) >= 0;
result.switched = result.flags.indexOf( 'S' ) >= 0;
}
} else {
err = data;
}
}
callback( err, result );
} );
}
|
javascript
|
{
"resource": ""
}
|
|
q51157
|
train
|
function( url ) {
var trunkMatch = url.match( /(.*)\/(trunk|branches|tags)\/*(.*)\/*(.*)$/i );
if ( trunkMatch ) {
var rootUrl = trunkMatch[1];
var projectName = rootUrl.match( /\/([^\/]+)$/ )[1];
return {
rootUrl: rootUrl,
projectName: projectName,
type: trunkMatch[2],
typeName: trunkMatch[3],
trunkUrl: trunkMatch[1] + "/trunk",
tagsUrl: trunkMatch[1] + "/tags",
branchesUrl: trunkMatch[1] + "/branches"
};
}
throw new Error( "parseUrl: Url does not look like an SVN repository" );
}
|
javascript
|
{
"resource": ""
}
|
|
q51158
|
train
|
function( url, options, callback ) {
if ( typeof options === "function" ) {
callback = options;
options = null;
}
options = options || {};
var tagsUrl = parseUrl( url ).tagsUrl;
list( tagsUrl, options, function( err, data ) {
var result = [];
if ( !err && data && data.list && data.list.entry ) {
if ( Array.isArray( data.list.entry ) ) {
result = data.list.entry.filter( function( entry ) {
return entry && entry.$ && entry.$.kind === "dir";
} );
} else {
if ( data.list.entry.$ && data.list.entry.$.kind === "dir" ) {
result = [ data.list.entry ];
}
}
}
callback( err, result );
} );
}
|
javascript
|
{
"resource": ""
}
|
|
q51159
|
train
|
function( url, options, callback ) {
if ( typeof options === "function" ) {
callback = options;
options = null;
}
options = options || {};
getTags( url, options, function( err, tagArray ) {
var latest;
if ( !err && Array.isArray( tagArray ) && tagArray.length > 0 ) {
tagArray.sort( function( a, b ) {
try {
return semver.rcompare( a.name, b.name );
}
catch ( err2 ) {
return -1;
}
} );
latest = tagArray[0];
}
callback( err, latest );
} );
}
|
javascript
|
{
"resource": ""
}
|
|
q51160
|
train
|
function( options ) {
this._options = options || {};
this._commands = [];
this._options.tempFolder = this._options.tempFolder || path.join( os.tmpdir(), 'mucc_' + uuid.v4() );
}
|
javascript
|
{
"resource": ""
}
|
|
q51161
|
train
|
function(element, options) {
element = this.setElement(element);
options = this.setOptions(options);
if (!options.target || !options.marker) {
throw new Error('A marker and target is required');
}
if (element.css('overflow') === 'auto') {
this.container = element;
}
// Initialize events
this.addEvents([
['scroll', 'container', $.throttle(this.onScroll.bind(this), options.throttle)],
['ready', 'document', 'onScroll']
]);
this.initialize();
// Gather markets and targets
this.refresh();
}
|
javascript
|
{
"resource": ""
}
|
|
q51162
|
train
|
function(marker, type) {
marker = $(marker);
// Stop all the unnecessary processing
if (type === 'activate' && marker.hasClass('is-stalked')) {
return;
} else if (type === 'deactivate' && !marker.hasClass('is-stalked')) {
return;
}
var options = this.options,
targetBy = options.targetBy,
markBy = options.markBy,
target = this.targets.filter(function() {
return $(this).attr(targetBy).replace('#', '') === marker.attr(markBy);
}),
before,
after,
method;
if (type === 'activate') {
before = 'activating';
after = 'activated';
method = 'addClass';
} else {
before = 'deactivating';
after = 'deactivated';
method = 'removeClass';
}
this.fireEvent(before, [marker, target]);
marker[method]('is-stalked');
target[method]('is-active');
this.fireEvent(after, [marker, target]);
}
|
javascript
|
{
"resource": ""
}
|
|
q51163
|
train
|
function() {
var isWindow = this.container.is(window),
eTop = this.element.offset().top,
offset,
offsets = [];
if (this.element.css('overflow') === 'auto' && !this.element.is('body')) {
this.element[0].scrollTop = 0; // Set scroll to top so offsets are correct
}
this.targets = $(this.options.target);
this.markers = $(this.options.marker).each(function(index, marker) {
offset = $(marker).offset();
if (!isWindow) {
offset.top -= eTop;
}
offsets.push(offset);
});
this.offsets = offsets;
}
|
javascript
|
{
"resource": ""
}
|
|
q51164
|
train
|
function() {
var scroll = this.container.scrollTop(),
offsets = this.offsets,
onlyWithin = this.options.onlyWithin,
threshold = this.options.threshold;
this.markers.each(function(index, marker) {
marker = $(marker);
var offset = offsets[index],
top = offset.top - threshold,
bot = offset.top + marker.height() - threshold;
// Scroll is within the marker
if (
(onlyWithin && scroll >= top && scroll <= bot) ||
(!onlyWithin && scroll >= top)
) {
this.activate(marker);
// Scroll went outside the marker
} else {
this.deactivate(marker);
}
}.bind(this));
this.fireEvent('scroll');
}
|
javascript
|
{
"resource": ""
}
|
|
q51165
|
train
|
function(element, options) {
this.setElement(element);
this.setOptions(options, this.element);
// Set events
this.addEvent('horizontalresize', 'window', $.debounce(this.onResize.bind(this)));
this.initialize();
// Render the matrix
this.refresh();
}
|
javascript
|
{
"resource": ""
}
|
|
q51166
|
train
|
function() {
this.items = this.element.find('> li').each(function() {
var self = $(this);
// Cache the initial column width
self.cache('matrix-column-width', self.outerWidth());
});
if (this.options.defer) {
this._deferRender();
} else {
this.render();
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51167
|
train
|
function() {
this._calculateColumns();
this.fireEvent('rendering');
var element = this.element,
items = this.items;
// No items
if (!items.length) {
element.removeAttr('style');
// Single column
} else if (this.colCount <= 1) {
element.removeAttr('style').addClass('no-columns');
items.removeAttr('style');
// Multi column
} else {
element.removeClass('no-columns');
this._organizeItems();
this._positionItems();
}
this.fireEvent('rendered');
}
|
javascript
|
{
"resource": ""
}
|
|
q51168
|
train
|
function() {
var wrapperWidth = this.element.outerWidth(),
colWidth = this.options.width,
gutter = this.options.gutter,
cols = Math.max(Math.floor(wrapperWidth / colWidth), 1),
colsWidth = (cols * (colWidth + gutter)) - gutter,
diff;
if (cols > 1) {
if (colsWidth > wrapperWidth) {
diff = colsWidth - wrapperWidth;
colWidth -= (diff / cols);
} else if (colsWidth < wrapperWidth) {
diff = wrapperWidth - colsWidth;
colWidth += (diff / cols);
}
}
this.wrapperWidth = wrapperWidth;
this.colWidth = colWidth;
this.colCount = cols;
}
|
javascript
|
{
"resource": ""
}
|
|
q51169
|
train
|
function() {
var promises = [];
this.images = this.element.find('img').each(function(index, image) {
if (image.complete) {
return; // Already loaded
}
var src = image.src,
def = $.Deferred();
image.onload = def.resolve;
image.onerror = image.onabort = def.reject;
image.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///ywAAAAAAQABAAACAUwAOw==';
image.src = src;
promises.push(def.promise());
});
$.when.apply($, promises).always(this.render.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q51170
|
train
|
function() {
var item,
span,
size,
l = this.items.length;
this.matrix = [];
for (var i = 0; i < l; i++) {
item = this.items.eq(i);
size = item.data('matrix-column-width');
// How many columns does this item span?
span = Math.max(Math.round(size / this.colWidth), 1);
// Span cannot be larger than the total number of columns
if (span > this.colCount) {
span = this.colCount;
}
this.matrix.push({
item: item,
span: span
});
// Multiple columns
if (span > 1) {
for (var s = 1; s < span; s++) {
if (this.matrix) {
this.matrix.push({
item: item,
span: false // Indicates an empty space
});
}
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51171
|
train
|
function() {
var gutter = this.options.gutter,
items = this.matrix,
item,
span,
dir = this.options.rtl ? 'right' : 'left',
y = [], // The top position values indexed by column
c = 0, // Current column in the loop
h = 0, // Smallest height column
i, // Items loop counter
l, // Items length
s, // Current span column in the loop
top,
pos = { margin: 0, position: 'absolute' };
for (i = 0; i < this.colCount; i++) {
y.push(0);
}
for (i = 0, l = items.length; i < l; i++) {
item = items[i];
span = item.span;
// Place the item in the smallest column
h = -1;
for (s = 0; s < this.colCount; s++) {
if (h === -1 || y[s] < h) {
h = y[s];
c = s;
}
}
// If the item extends too far out, move it to the next column
// Or if the last column has been reached
if ((c >= this.colCount) || ((span + c) > this.colCount)) {
c = 0;
}
// Item spans a column or multiple columns
if (span) {
top = 0;
// If the item spans multiple columns
// Get the largest height from the previous row
for (s = 0; s < span; s++) {
if (y[c + s] > top) {
top = y[c + s];
}
}
// Position the item
pos.top = top;
pos[dir] = (this.colWidth + gutter) * c;
pos.width = ((this.colWidth + gutter) * span) - gutter;
item.item.css(pos).reveal();
// Loop again to add the value to each columns Y top value
// This must be done after positioning so we can calculate a new size
for (s = 0; s < span; s++) {
y[c + s] = item.item.outerHeight() + gutter + top;
}
}
this.colHeights[c] = y[c];
c++;
}
// Set height of wrapper
this.element.css('height', Math.max.apply(Math, y));
}
|
javascript
|
{
"resource": ""
}
|
|
q51172
|
train
|
function(element, options) {
var items, self = this;
element = this.setElement(element);
options = this.setOptions(options, element);
// Set animation and ARIA
element
.aria('live', options.autoCycle ? 'assertive' : 'off')
.addClass(options.animation);
// Find the item container and disable transitions for initial load
this.container = element.find(this.ns('items'))
.addClass('no-transition');
// Find all the items and set ARIA attributes
this.items = items = this.container.find('> li').each(function(index) {
$(this)
.attr({
role: 'tabpanel',
id: self.id('item', index)
})
.data('carousel-index', index)
.aria('hidden', (index > 0));
});
// Find all tabs and set ARIA attributes
this.tabs = element.find(this.ns('tabs'))
.attr('role', 'tablist')
.find('a').each(function(index) {
$(this)
.data('carousel-index', index)
.attr({
role: 'tab',
id: self.id('tab', index)
})
.aria({
controls: self.id('item', index),
selected: false,
expanded: false
});
});
// Set events
this.addEvents([
['resize', 'window', $.throttle(this.calculate.bind(this), 50)],
['keydown', 'window', 'onKeydown'],
['click', 'element', 'onJump', this.ns('tabs') + ' a'],
['click', 'element', 'next', this.ns('next')],
['click', 'element', 'prev', this.ns('prev')],
['click', 'element', 'start', this.ns('start')],
['click', 'element', 'stop', this.ns('stop')]
]);
if (options.swipe) {
this.addEvents([
['swipeleft', 'element', 'next'],
['swipeup', 'element', 'next'],
['swiperight', 'element', 'prev'],
['swipedown', 'element', 'prev']
]);
}
if (options.stopOnHover) {
this.addEvents([
['mouseenter', 'element', 'stop'],
['mouseleave', 'element', 'start']
]);
}
// Initialize
this.initialize();
// Prepare the carousel
this._setupState();
this._buildClones();
// Start the carousel
this.calculate();
this.start();
this.jump(options.defaultIndex);
}
|
javascript
|
{
"resource": ""
}
|
|
q51173
|
train
|
function() {
this.stop();
// Go to first item
this.jump(0);
// Remove clones
var dir = this._position || 'left';
this.container.transitionend(function() {
$(this)
.addClass('no-transition')
.css(dir, 0)
.find('li.is-cloned')
.remove();
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51174
|
train
|
function() {
if (this.options.animation === 'fade') {
return;
}
var dimension = this._dimension, // height or width
containerSize = 0,
sizes = [];
this.container.removeAttr('style');
this.items.each(function() {
var item = $(this).removeAttr('style'),
size = item[dimension](),
marginStart = parseInt(item.css('margin-' + (dimension === 'width' ? 'left' : 'top')), 10),
marginEnd = parseInt(item.css('margin-' + (dimension === 'width' ? 'right' : 'bottom')), 10),
totalSize = size + marginStart + marginEnd;
containerSize += totalSize;
sizes.push({
size: size,
totalSize: totalSize,
marginStart: marginStart,
marginEnd: marginEnd,
clone: item.hasClass('is-cloned')
});
// Set the size of the item explicitly
item.css(dimension, size);
});
// Store the sizes
this._sizes = sizes;
// Set the container width/height
this.container.css(dimension, containerSize);
}
|
javascript
|
{
"resource": ""
}
|
|
q51175
|
train
|
function(index) {
if (this.animating) {
return;
}
var indexes = this._getIndex(index),
cloneIndex = indexes[0], // The index including clones
visualIndex = indexes[1]; // The index excluding clones
// Exit early if jumping to same index
if (visualIndex === this.index) {
return;
}
this.fireEvent('jumping', [this.index]);
// Update tabs and items state
this._updateTabs(visualIndex);
this._updateItems(cloneIndex);
// Animate and move the items
this._beforeCycle();
if (this.options.animation === 'fade') {
this.items
.conceal(true)
.eq(visualIndex)
.transitionend(this._afterCycle.bind(this))
.reveal(true);
} else {
this.container
.transitionend(this._afterCycle.bind(this))
.css(this._position, -this._getSizeSum(cloneIndex));
}
// Store the index
this.index = visualIndex;
this.reset();
this.fireEvent('jumped', [visualIndex]);
}
|
javascript
|
{
"resource": ""
}
|
|
q51176
|
train
|
function() {
if (this.options.autoCycle) {
clearInterval(this.timer);
this.timer = setInterval(this.onCycle.bind(this), this.options.duration);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51177
|
train
|
function() {
this.animating = false;
var container = this.container,
resetTo = this._resetTo;
// Reset the currently shown item to a specific index
// This achieves the circular infinite scrolling effect
if (resetTo !== null) {
container
.addClass('no-transition')
.css(this._position, -this._getSizeSum(resetTo));
this._updateItems(resetTo);
this._resetTo = null;
}
// Set in a timeout or transition will still occur
setTimeout(function() {
container.removeClass('no-transition');
this.fireEvent('cycled');
}.bind(this), 15); // IE needs a minimum of 15
}
|
javascript
|
{
"resource": ""
}
|
|
q51178
|
train
|
function() {
var options = this.options,
items = this.items,
container = this.container,
itemsToShow = options.itemsToShow;
if (!options.infinite) {
return;
}
// Append the first items
items.slice(0, itemsToShow)
.clone()
.addClass('is-cloned')
.removeAttr('id')
.removeAttr('role')
.appendTo(container);
// Prepend the last items
items.slice(-itemsToShow)
.clone()
.addClass('is-cloned')
.removeAttr('id')
.removeAttr('role')
.prependTo(container);
// Refresh items list
this.items = container.find('> li');
}
|
javascript
|
{
"resource": ""
}
|
|
q51179
|
train
|
function(index) {
var sum = 0;
$.each(this._sizes, function(i, value) {
if (i < index) {
sum += value.totalSize;
}
});
return sum;
}
|
javascript
|
{
"resource": ""
}
|
|
q51180
|
train
|
function() {
var options = this.options,
animation = options.animation;
// Cycling more than the show amount causes unexpected issues
if (options.itemsToCycle > options.itemsToShow) {
options.itemsToCycle = options.itemsToShow;
}
// Fade animations can only display 1 at a time
if (animation === 'fade') {
options.itemsToShow = options.itemsToCycle = 1;
options.infinite = false;
// Determine the dimension and position based on animation
} else if (animation === 'slide-up') {
this._dimension = 'height';
this._position = 'top';
} else if (animation === 'slide') {
this._dimension = 'width';
this._position = options.rtl ? 'right' : 'left';
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51181
|
train
|
function(index) {
this.items
.removeClass('is-active')
.aria('hidden', true)
.slice(index, index + this.options.itemsToShow)
.addClass('is-active')
.aria('hidden', false);
}
|
javascript
|
{
"resource": ""
}
|
|
q51182
|
train
|
function(start) {
var itemsToShow = this.options.itemsToShow,
length = this.items.length,
stop = start + itemsToShow,
set = $([]),
tabs = this.tabs
.removeClass('is-active')
.aria('toggled', false);
if (!tabs.length) {
return;
}
if (this.options.infinite) {
length = length - (itemsToShow * 2);
}
if (start >= 0) {
set = set.add(tabs.slice(start, stop));
} else {
set = set.add(tabs.slice(0, stop));
set = set.add(tabs.slice(start));
}
if (stop > length) {
set = set.add(tabs.slice(0, stop - length));
}
set
.addClass('is-active')
.aria('toggled', true);
}
|
javascript
|
{
"resource": ""
}
|
|
q51183
|
train
|
function(nodes, options) {
var element;
options = this.setOptions(options);
this.element = element = this.createElement();
// Nodes found in the page on initialization
this.nodes = $(nodes);
// The wrapping items element
this.items = element.find(this.ns('items'));
// The wrapping tabs element
this.tabs = element.find(this.ns('tabs'));
// The caption element
this.caption = element.find(this.ns('caption'));
// Blackout element if enabled
if (options.blackout) {
this.blackout = Blackout.instance();
}
// Initialize events
this.addEvents([
['keydown', 'window', 'onKeydown'],
['click', 'document', 'onShow', '{selector}'],
['click', 'element', 'hide', this.ns('close')],
['click', 'element', 'next', this.ns('next')],
['click', 'element', 'prev', this.ns('prev')],
['click', 'element', 'onJump', this.ns('tabs') + ' a']
]);
if (options.clickout) {
this.addEvents([
['clickout', 'document', 'onHide', '{selector}'],
['clickout', 'element', 'onHide']
]);
}
if (options.swipe) {
this.addEvents([
['swipeleft', 'element', 'next'],
['swiperight', 'element', 'prev']
]);
}
// Stop `transitionend` events from bubbling up when the showcase is resized
this.addEvent(Toolkit.transitionEnd, 'element', function(e) {
e.stopPropagation();
}, this.ns('items'));
this.initialize();
}
|
javascript
|
{
"resource": ""
}
|
|
q51184
|
train
|
function(index) {
if (this.animating) {
return;
}
index = $.bound(index, this.data.length);
// Exit since transitions don't occur
if (index === this.index) {
return;
}
var self = this,
element = this.element,
caption = this.caption,
list = this.items,
listItems = list.children('li'),
listItem = listItems.eq(index),
items = this.data,
item = items[index],
deferred = $.Deferred();
this.fireEvent('jumping', [this.index]);
// Update tabs
this.tabs.find('a')
.removeClass('is-active')
.eq(index)
.addClass('is-active');
// Reset previous styles
listItems.conceal(true);
caption.conceal(true);
element
.addClass('is-loading')
.aria('busy', true)
.reveal();
// Setup deferred callbacks
this.animating = true;
deferred.always(function(width, height) {
list.transitionend(function() {
caption.html(item.title).reveal(true);
listItem.reveal(true);
self.position();
self.animating = false;
});
self._resize(width, height);
element
.removeClass('is-loading')
.aria('busy', false);
listItem
.data('width', width)
.data('height', height);
});
deferred.fail(function() {
element.addClass('has-failed');
listItem.html(Toolkit.messages.error);
});
// Image already exists
if (listItem.data('width')) {
deferred.resolve(listItem.data('width'), listItem.data('height'));
// Create image and animate
} else {
var img = new Image();
img.src = item.image;
img.onerror = function() {
deferred.reject(150, 150);
};
img.onload = function() {
deferred.resolve(this.width, this.height);
listItem.append(img);
};
}
// Hide loader
if (this.blackout) {
this.blackout.hideLoader();
}
// Save state
this.index = index;
this.fireEvent('jumped', [index]);
}
|
javascript
|
{
"resource": ""
}
|
|
q51185
|
train
|
function(node) {
this.node = node = $(node);
this.index = -1;
var options = this.inheritOptions(this.options, node),
read = this.readValue,
category = read(node, options.getCategory),
items = [],
index = 0;
// Multiple items based on category
if (category) {
for (var i = 0, x = 0, n; n = this.nodes[i]; i++) {
if (read(n, options.getCategory) === category) {
if (node.is(n)) {
index = x;
}
items.push({
title: read(n, options.getTitle),
category: category,
image: read(n, options.getImage)
});
x++;
}
}
// Single item
} else {
items.push({
title: read(node, options.getTitle),
category: category,
image: read(node, options.getImage)
});
}
if (this.blackout) {
this.blackout.show();
}
if (options.stopScroll) {
$('body').addClass('no-scroll');
}
this._buildItems(items);
this.jump(index);
}
|
javascript
|
{
"resource": ""
}
|
|
q51186
|
train
|
function(items) {
this.data = items;
this.items.empty();
this.tabs.empty();
for (var li, a, item, i = 0; item = items[i]; i++) {
li = $('<li/>');
li.appendTo(this.items);
a = $('<a/>')
.attr('href', 'javascript:;')
.data('showcase-index', i);
li = $('<li/>');
li.appendTo(this.tabs).append(a);
}
if (items.length <= 1) {
this.element.addClass('is-single');
}
this.fireEvent('load', [items]);
}
|
javascript
|
{
"resource": ""
}
|
|
q51187
|
train
|
function(width, height) {
var gutter = (this.options.gutter * 2),
wWidth = $(window).width() - gutter,
wHeight = $(window).height() - gutter,
ratio,
diff;
// Resize if the width is larger
if (width > wWidth) {
ratio = (width / height);
diff = (width - wWidth);
width = wWidth;
height -= Math.round(diff / ratio);
}
// Resize again if the height is larger
if (height > wHeight) {
ratio = (height / width);
diff = (height - wHeight);
width -= Math.round(diff / ratio);
height = wHeight;
}
this.items.css({
width: width,
height: height
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51188
|
train
|
function(plugin, callback, collection) {
var name = plugin;
// Prefix with toolkit to avoid collisions
if ($.fn[name]) {
name = 'toolkit' + name.charAt(0).toUpperCase() + name.slice(1);
}
$.fn[name] = collection ?
// Apply the instance to a collection of elements
function() {
var instance = Toolkit.cache[plugin + ':' + this.selector] = callback.apply(this, arguments);
return this.each(function() {
$(this).cache('toolkit.' + plugin, instance);
});
} :
// Apply the instance per element
function() {
var args = arguments;
return this.each(function() {
$(this).cache('toolkit.' + plugin, callback.apply(this, args));
});
};
}
|
javascript
|
{
"resource": ""
}
|
|
q51189
|
train
|
function() {
var instance = Toolkit.cache[plugin + ':' + this.selector] = callback.apply(this, arguments);
return this.each(function() {
$(this).cache('toolkit.' + plugin, instance);
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51190
|
train
|
function(event, context, callback, selector) {
var options = this.options;
// Replace tokens
if (event === '{mode}') {
event = options.mode;
}
if (selector === '{selector}') {
selector = this.nodes ? this.nodes.selector : '';
}
// Find and bind the function
if ($.type(callback) === 'string') {
callback = this[callback].bind(this);
}
this.__events.push([event, context, callback, selector]);
}
|
javascript
|
{
"resource": ""
}
|
|
q51191
|
train
|
function(type, callback) {
var list = this.__hooks[type] || [];
list.push(callback);
this.__hooks[type] = list;
}
|
javascript
|
{
"resource": ""
}
|
|
q51192
|
train
|
function(type, callbacks) {
$.each(callbacks, function(i, callback) {
this.addHook(type, callback);
}.bind(this));
}
|
javascript
|
{
"resource": ""
}
|
|
q51193
|
train
|
function(type) {
var self = this,
event,
context,
func,
selector,
win = $(window),
doc = $(document);
$.each(this.__events, function(i, value) {
event = value[0];
context = value[1];
func = value[2];
selector = value[3];
// Determine the correct context
if (self[context]) {
context = self[context];
} else if (context === 'window') {
context = win;
} else if (context === 'document') {
context = doc;
}
// Ready events
if (event === 'ready') {
doc.ready(func);
// Delegated events
} else if (selector) {
$(context)[type](event, selector, func);
// Regular events
} else {
$(context)[type](event, func);
}
});
}
|
javascript
|
{
"resource": ""
}
|
|
q51194
|
train
|
function(type, args) {
var debug = this.options.debug || Toolkit.debug;
if (debug) {
console.log(this.name + '#' + this.uid, new Date().getMilliseconds(), type, args || []);
if (debug === 'verbose') {
console.dir(this);
}
}
var hooks = this.__hooks[type];
if (hooks) {
$.each(hooks, function(i, hook) {
hook.apply(this, args || []);
}.bind(this));
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51195
|
train
|
function(type, callback) {
if (!callback) {
delete this.__hooks[type];
return;
}
var hooks = this.__hooks[type];
if (hooks) {
$.each(hooks, function(i, hook) {
if (hook === callback) {
hooks = hooks.splice(i, 1);
}
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51196
|
train
|
function(options) {
var opts = $.extend(true, {}, Toolkit[this.name].options, options || {}),
key;
// Inherit options based on responsive media queries
if (opts.responsive && window.matchMedia) {
$.each(opts.responsive, function(key, resOpts) {
if (matchMedia(resOpts.breakpoint).matches) {
$.extend(opts, resOpts);
}
});
}
// Set hooks that start with `on`
for (key in opts) {
if (key.match(/^on[A-Z]/)) {
this.addHook(key.substr(2).toLowerCase(), opts[key]);
delete opts[key];
}
}
this.options = opts;
return opts;
}
|
javascript
|
{
"resource": ""
}
|
|
q51197
|
doAria
|
train
|
function doAria(element, key, value) {
if ($.type(value) === 'undefined') {
return element.getAttribute('aria-' + key);
}
if (value === true) {
value = 'true';
} else if (value === false) {
value = 'false';
}
element.setAttribute('aria-' + key, value);
}
|
javascript
|
{
"resource": ""
}
|
q51198
|
train
|
function(type, args) {
Base.prototype.fireEvent.call(this, type, args);
var element = this.element,
node = this.node,
event = $.Event(type + '.toolkit.' + this.keyName);
event.context = this;
// Trigger event on the element and the node
if (element) {
element.trigger(event, args || []);
}
if (node) {
node.trigger(event, args || []);
}
}
|
javascript
|
{
"resource": ""
}
|
|
q51199
|
train
|
function(options, element) {
var key, value, obj = {};
for (key in options) {
if (key === 'context' || key === 'template') {
continue;
}
value = element.data((this.keyName + '-' + key).toLowerCase());
if ($.type(value) !== 'undefined') {
obj[key] = value;
}
}
return $.extend(true, {}, options, obj);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.