language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | offset(offset) {
this.query.offset = offset;
return this;
} | offset(offset) {
this.query.offset = offset;
return this;
} |
JavaScript | sort(column, descending) {
this.query.sort.push({
column: column,
descending: descending
});
return this;
} | sort(column, descending) {
this.query.sort.push({
column: column,
descending: descending
});
return this;
} |
JavaScript | createSshTunnel(config) {
// The tunnel must only be created, nothing is to be checked.
return tunnel({
username: config.ssh.username,
password: config.ssh['password'] ? config.ssh.password : null,
privateKey: config.ssh['privateKey'] ? require('fs').readFileSync(config.ssh.privateKey) : null,
host: config.ssh.host,
port: config.ssh.port,
dstHost: config.host,
dstPort: config.port,
localHost: config.host,
localPort: config.port = config.port + 1,
keepAlive: true
});
} | createSshTunnel(config) {
// The tunnel must only be created, nothing is to be checked.
return tunnel({
username: config.ssh.username,
password: config.ssh['password'] ? config.ssh.password : null,
privateKey: config.ssh['privateKey'] ? require('fs').readFileSync(config.ssh.privateKey) : null,
host: config.ssh.host,
port: config.ssh.port,
dstHost: config.host,
dstPort: config.port,
localHost: config.host,
localPort: config.port = config.port + 1,
keepAlive: true
});
} |
JavaScript | execute(query) {
var method = query['type'] ? (query.type.charAt(0).toUpperCase() + query.type.slice(1)) : 'Select',
self = this;
query = query['type'] ? this.getBuilder().build(query) : query;
return this.getConnection()
.then(function(connection) {
return self['execute' + method](connection, query)
.then(function(result) {
self.releaseConnection(connection);
return result;
})
.catch(function(err) {
self.releaseConnection(connection);
throw err;
});
});
} | execute(query) {
var method = query['type'] ? (query.type.charAt(0).toUpperCase() + query.type.slice(1)) : 'Select',
self = this;
query = query['type'] ? this.getBuilder().build(query) : query;
return this.getConnection()
.then(function(connection) {
return self['execute' + method](connection, query)
.then(function(result) {
self.releaseConnection(connection);
return result;
})
.catch(function(err) {
self.releaseConnection(connection);
throw err;
});
});
} |
JavaScript | releaseConnection(connection) {
this.connection.release(connection);
return this;
} | releaseConnection(connection) {
this.connection.release(connection);
return this;
} |
JavaScript | into(table) {
this.query.table = table;
return this;
} | into(table) {
this.query.table = table;
return this;
} |
JavaScript | _getConstraint(constraint, value) {
switch(constraint) {
case 'equals':
constraint = '= ' + this.escape(value);
break;
case 'like':
constraint = 'LIKE ' + this.escape(value);
break;
case 'in':
constraint = 'IN (' + value + ')';
break;
case 'between':
constraint = 'BETWEEN ' + this.escape(value.start) + ' AND ' + this.escape(value.end)
break;
case 'gt':
constraint = '> ' + this.escape(value);
break;
case 'lt':
constraint = '< ' + this.escape(value);
break;
}
return constraint;
} | _getConstraint(constraint, value) {
switch(constraint) {
case 'equals':
constraint = '= ' + this.escape(value);
break;
case 'like':
constraint = 'LIKE ' + this.escape(value);
break;
case 'in':
constraint = 'IN (' + value + ')';
break;
case 'between':
constraint = 'BETWEEN ' + this.escape(value.start) + ' AND ' + this.escape(value.end)
break;
case 'gt':
constraint = '> ' + this.escape(value);
break;
case 'lt':
constraint = '< ' + this.escape(value);
break;
}
return constraint;
} |
JavaScript | _buildWhereClause(wheres) {
var sql = '';
if(wheres.length) {
sql += ' WHERE';
var last = (wheres.length - 1);
for(var where of wheres) {
sql += ' (' + this.quoteName(where.column) + ' ' + this._getConstraint(where.type, where.value) + ')';
if(wheres.indexOf(where) < last) {
sql += ' ' + where.next.toUpperCase();
}
}
}
return sql;
} | _buildWhereClause(wheres) {
var sql = '';
if(wheres.length) {
sql += ' WHERE';
var last = (wheres.length - 1);
for(var where of wheres) {
sql += ' (' + this.quoteName(where.column) + ' ' + this._getConstraint(where.type, where.value) + ')';
if(wheres.indexOf(where) < last) {
sql += ' ' + where.next.toUpperCase();
}
}
}
return sql;
} |
JavaScript | _buildHavingClause(havings) {
var sql = '';
if(havings.length) {
sql += ' HAVING';
var last = (havings.length - 1);
for(var having of havings) {
sql += ' (' + this.quoteName(having.column) + ' ' + this._getConstraint(having.type, having.value) + ')';
if(havings.indexOf(having) < last) {
sql += ' ' + having.next.toUpperCase();
}
}
}
return sql;
} | _buildHavingClause(havings) {
var sql = '';
if(havings.length) {
sql += ' HAVING';
var last = (havings.length - 1);
for(var having of havings) {
sql += ' (' + this.quoteName(having.column) + ' ' + this._getConstraint(having.type, having.value) + ')';
if(havings.indexOf(having) < last) {
sql += ' ' + having.next.toUpperCase();
}
}
}
return sql;
} |
JavaScript | buildSelect(query) {
var sql = 'SELECT ',
columns = query.query.columns,
cols = [],
joins = query.query.join;
if(!query.query.count.column) {
for (var column of columns) {
cols.push(this.quoteName(column.name) + (column.alias ? ' AS ' + this.quoteName(column.alias) : ''));
}
} else {
var count = query.query.count;
cols.push('COUNT(' + this.quoteName(count.column) + ')' + (count.alias ? ' AS ' + this.quoteName(count.alias) : ''));
}
sql += cols.join(', ') + ' FROM ' + this.quoteName(query.query.from.table + (query.query.from.alias ? ' AS ' + query.query.from.alias : ''));
if(joins.length) {
for(var join of joins) {
sql += ' ' + join.type.toUpperCase() + ' JOIN ' + this.quoteName(join.table + (join.alias ? ' AS ' + join.alias : '')) + ' ON (' + this.quoteName(join.set.source) + ' = ' + this.quoteName(join.set.target) + ')';
}
}
sql += this._buildWhereClause(query.query.where);
if(query.query.group.length) {
sql += ' GROUP BY ' + query.query.group.join(',');
}
sql += this._buildHavingClause(query.query.having);
if(query.query.sort.length) {
sql += ' ORDER BY ' + query.query.sort.map(function(sort) {
return this.quoteName(sort.column) + (sort.descending ? ' DESC' : '');
}.bind(this)).join(', ');
}
if(query.query.limit) {
sql += ' LIMIT ' + query.query.limit;
if(query.query.offset) {
sql += ',' + query.query.offset;
}
}
return sql;
} | buildSelect(query) {
var sql = 'SELECT ',
columns = query.query.columns,
cols = [],
joins = query.query.join;
if(!query.query.count.column) {
for (var column of columns) {
cols.push(this.quoteName(column.name) + (column.alias ? ' AS ' + this.quoteName(column.alias) : ''));
}
} else {
var count = query.query.count;
cols.push('COUNT(' + this.quoteName(count.column) + ')' + (count.alias ? ' AS ' + this.quoteName(count.alias) : ''));
}
sql += cols.join(', ') + ' FROM ' + this.quoteName(query.query.from.table + (query.query.from.alias ? ' AS ' + query.query.from.alias : ''));
if(joins.length) {
for(var join of joins) {
sql += ' ' + join.type.toUpperCase() + ' JOIN ' + this.quoteName(join.table + (join.alias ? ' AS ' + join.alias : '')) + ' ON (' + this.quoteName(join.set.source) + ' = ' + this.quoteName(join.set.target) + ')';
}
}
sql += this._buildWhereClause(query.query.where);
if(query.query.group.length) {
sql += ' GROUP BY ' + query.query.group.join(',');
}
sql += this._buildHavingClause(query.query.having);
if(query.query.sort.length) {
sql += ' ORDER BY ' + query.query.sort.map(function(sort) {
return this.quoteName(sort.column) + (sort.descending ? ' DESC' : '');
}.bind(this)).join(', ');
}
if(query.query.limit) {
sql += ' LIMIT ' + query.query.limit;
if(query.query.offset) {
sql += ',' + query.query.offset;
}
}
return sql;
} |
JavaScript | buildInsert(query) {
var keys = [],
values = [],
sql = 'INSERT INTO ' + this.quoteName(query.query.table);
for(var set of query.query.set) {
keys.push(set.column);
values.push(set.value);
}
if(keys.length && values.length) {
sql += ' (' + keys.map(this.quoteName).join(',') + ') VALUES (' + values.map(this.escape).join(',') + ')';
}
return sql;
} | buildInsert(query) {
var keys = [],
values = [],
sql = 'INSERT INTO ' + this.quoteName(query.query.table);
for(var set of query.query.set) {
keys.push(set.column);
values.push(set.value);
}
if(keys.length && values.length) {
sql += ' (' + keys.map(this.quoteName).join(',') + ') VALUES (' + values.map(this.escape).join(',') + ')';
}
return sql;
} |
JavaScript | buildUpdate(query) {
var sql = 'UPDATE ' + this.quoteName(query.query.table),
sets = [];
if(query.query.set.length) {
sql += ' SET';
for(var set of query.query.set) {
sets.push(' ' + this.quoteName(set.column) + ' = ' + this.escape(set.value));
}
sql += sets.join(', ');
}
sql += this._buildWhereClause(query.query.where);
sql += this._buildHavingClause(query.query.having);
return sql;
} | buildUpdate(query) {
var sql = 'UPDATE ' + this.quoteName(query.query.table),
sets = [];
if(query.query.set.length) {
sql += ' SET';
for(var set of query.query.set) {
sets.push(' ' + this.quoteName(set.column) + ' = ' + this.escape(set.value));
}
sql += sets.join(', ');
}
sql += this._buildWhereClause(query.query.where);
sql += this._buildHavingClause(query.query.having);
return sql;
} |
JavaScript | buildDelete(query) {
var sql = 'DELETE FROM ' + this.quoteName(query.query.table),
wheres = query.query.where;
sql += this._buildWhereClause(wheres);
return sql;
} | buildDelete(query) {
var sql = 'DELETE FROM ' + this.quoteName(query.query.table),
wheres = query.query.where;
sql += this._buildWhereClause(wheres);
return sql;
} |
JavaScript | table(table) {
this.query.table = table;
return this;
} | table(table) {
this.query.table = table;
return this;
} |
JavaScript | select(columns) {
var builder = this.getBuilder('select');
if(columns) {
builder.select(columns);
}
return builder;
} | select(columns) {
var builder = this.getBuilder('select');
if(columns) {
builder.select(columns);
}
return builder;
} |
JavaScript | update(table) {
var builder = this.getBuilder('update');
if(table) {
builder.table(table);
}
return builder;
} | update(table) {
var builder = this.getBuilder('update');
if(table) {
builder.table(table);
}
return builder;
} |
JavaScript | connect() {
return new Promise(function(resolve, reject) {
try {
return resolve(new sqlite.Database(this.config.host));
} catch(err) {
return reject(err);
}
}.bind(this));
} | connect() {
return new Promise(function(resolve, reject) {
try {
return resolve(new sqlite.Database(this.config.host));
} catch(err) {
return reject(err);
}
}.bind(this));
} |
JavaScript | close(connection) {
return new Promise(function(resolve, reject) {
connection.close(function(err) {
if(err) {
return reject(err);
}
return resolve();
});
});
} | close(connection) {
return new Promise(function(resolve, reject) {
connection.close(function(err) {
if(err) {
return reject(err);
}
return resolve();
});
});
} |
JavaScript | executeSelect(connection, query) {
return new Promise(function(resolve, reject) {
connection.all(query, function(err, results) {
if(err) {
return reject(err);
}
return resolve(results);
});
});
} | executeSelect(connection, query) {
return new Promise(function(resolve, reject) {
connection.all(query, function(err, results) {
if(err) {
return reject(err);
}
return resolve(results);
});
});
} |
JavaScript | executeInsert(connection, query) {
return new Promise(function(resolve, reject) {
connection.run(query, function(err) {
if(err) {
return reject(err);
}
return resolve(this);
});
});
} | executeInsert(connection, query) {
return new Promise(function(resolve, reject) {
connection.run(query, function(err) {
if(err) {
return reject(err);
}
return resolve(this);
});
});
} |
JavaScript | connect() {
return mysql.createConnection({
connectionLimit: this.config.pool,
host: this.config.host,
user: this.config.username,
password: this.config.password,
port: this.config.port || 3306,
database: this.config.database,
Promise: Promise
});
} | connect() {
return mysql.createConnection({
connectionLimit: this.config.pool,
host: this.config.host,
user: this.config.username,
password: this.config.password,
port: this.config.port || 3306,
database: this.config.database,
Promise: Promise
});
} |
JavaScript | createSshTunnel(config) {
config.port = config.port || 3306;
return super.createSshTunnel(config);
} | createSshTunnel(config) {
config.port = config.port || 3306;
return super.createSshTunnel(config);
} |
JavaScript | executeSelect(connection, query) {
return connection.query(query)
.then(function(result) {
return result[0];
});
} | executeSelect(connection, query) {
return connection.query(query)
.then(function(result) {
return result[0];
});
} |
JavaScript | _buildQwhereClause(query, wheres, from) {
for(var where of wheres) {
if(from && from.alias) {
where.column = where.column.replace(from.alias + '.', '');
}
if(where.column === '_id') {
if(Array.isArray(where.value)) {
where.value = where.value.map(function(value) {
return new ObjectID(value);
});
} else {
where.value = new ObjectID(where.value);
}
}
switch(where.type) {
case 'equals':
query[where.column] = where.value;
break;
case 'in':
query[where.column] = {$in: (Array.isArray(where.value) ? where.value : [where.value])};
break;
case 'like':
query[where.column] = {$regex: where.value};
break;
case 'between':
query[where.column] = {$gte: where.value.start, $lte: where.value.end};
break;
case 'gt':
query[where.column] = {$gte: where.value};
break;
case 'lt':
query[where.column] = {$lte: where.value};
break;
}
}
} | _buildQwhereClause(query, wheres, from) {
for(var where of wheres) {
if(from && from.alias) {
where.column = where.column.replace(from.alias + '.', '');
}
if(where.column === '_id') {
if(Array.isArray(where.value)) {
where.value = where.value.map(function(value) {
return new ObjectID(value);
});
} else {
where.value = new ObjectID(where.value);
}
}
switch(where.type) {
case 'equals':
query[where.column] = where.value;
break;
case 'in':
query[where.column] = {$in: (Array.isArray(where.value) ? where.value : [where.value])};
break;
case 'like':
query[where.column] = {$regex: where.value};
break;
case 'between':
query[where.column] = {$gte: where.value.start, $lte: where.value.end};
break;
case 'gt':
query[where.column] = {$gte: where.value};
break;
case 'lt':
query[where.column] = {$lte: where.value};
break;
}
}
} |
JavaScript | buildSelect(query) {
// we will return a few things in an object.
var result = {
method: 'find',
collection: query.query.from.table,
query: {},
limit: query.query.limit || 20,
offset: query.query.offset
};
// Loop throught the wheres.
this._buildQwhereClause(result.query, query.query.where, query.query.from);
return result;
} | buildSelect(query) {
// we will return a few things in an object.
var result = {
method: 'find',
collection: query.query.from.table,
query: {},
limit: query.query.limit || 20,
offset: query.query.offset
};
// Loop throught the wheres.
this._buildQwhereClause(result.query, query.query.where, query.query.from);
return result;
} |
JavaScript | buildInsert(query) {
// we will return a few things in an object.
var result = {
method: 'insert',
collection: query.query.table,
query: {}
};
// Loop throught the wheres.
for(var set of query.query.set) {
result.query[set.column] = set.value;
}
return result;
} | buildInsert(query) {
// we will return a few things in an object.
var result = {
method: 'insert',
collection: query.query.table,
query: {}
};
// Loop throught the wheres.
for(var set of query.query.set) {
result.query[set.column] = set.value;
}
return result;
} |
JavaScript | buildUpdate(query) {
var result = {
method: 'update',
collection: query.query.table,
filter: {},
set: {}
};
// Loop throught the wheres.
for(var set of query.query.set) {
result.set[set.column] = set.value;
}
this._buildQwhereClause(result.filter, query.query.where, false);
return result;
} | buildUpdate(query) {
var result = {
method: 'update',
collection: query.query.table,
filter: {},
set: {}
};
// Loop throught the wheres.
for(var set of query.query.set) {
result.set[set.column] = set.value;
}
this._buildQwhereClause(result.filter, query.query.where, false);
return result;
} |
JavaScript | buildDelete(query) {
var result = {
method: 'delete',
collection: query.query.table,
query: {}
};
this._buildQwhereClause(result.query, query.query.where, false);
return result;
} | buildDelete(query) {
var result = {
method: 'delete',
collection: query.query.table,
query: {}
};
this._buildQwhereClause(result.query, query.query.where, false);
return result;
} |
JavaScript | connect() {
var auth = (this.config.username && this.config.password) ? this.config.username + ':' + this.config.password + '@' : '',
url = 'mongodb://' + auth + this.config.host + ':' + (this.config.port || 27017) + '/' + this.config.database;
return MongoClient.connect(url);
} | connect() {
var auth = (this.config.username && this.config.password) ? this.config.username + ':' + this.config.password + '@' : '',
url = 'mongodb://' + auth + this.config.host + ':' + (this.config.port || 27017) + '/' + this.config.database;
return MongoClient.connect(url);
} |
JavaScript | createSshTunnel(config) {
config.port = config.port || 27017;
return super.createSshTunnel(config);
} | createSshTunnel(config) {
config.port = config.port || 27017;
return super.createSshTunnel(config);
} |
JavaScript | execute(query) {
query = this.getBuilder().build(query);
// Execute specialized method.
var method = query.method.substr(0, 1).toUpperCase() + query.method.substr(1),
self = this;
return this.getConnection()
.then(function(connection) {
return self['execute' + method](connection, query)
.then(function(result) {
self.releaseConnection(connection);
return result;
})
.catch(function(err) {
self.releaseConnection(connection);
throw err;
});
});
} | execute(query) {
query = this.getBuilder().build(query);
// Execute specialized method.
var method = query.method.substr(0, 1).toUpperCase() + query.method.substr(1),
self = this;
return this.getConnection()
.then(function(connection) {
return self['execute' + method](connection, query)
.then(function(result) {
self.releaseConnection(connection);
return result;
})
.catch(function(err) {
self.releaseConnection(connection);
throw err;
});
});
} |
JavaScript | executeFind(connection, query) {
return connection
.collection(query.collection)
.find(query.query)
.limit(query.limit)
.skip(query.offset)
.toArray();
} | executeFind(connection, query) {
return connection
.collection(query.collection)
.find(query.query)
.limit(query.limit)
.skip(query.offset)
.toArray();
} |
JavaScript | executeUpdate(connection, query) {
return connection.collection(query.collection).updateOne(query.filter, {
$set: query.set
});
} | executeUpdate(connection, query) {
return connection.collection(query.collection).updateOne(query.filter, {
$set: query.set
});
} |
JavaScript | build(query) {
var method = 'build' + (query.type.charAt(0).toUpperCase() + query.type.slice(1));
return this[method](query);
} | build(query) {
var method = 'build' + (query.type.charAt(0).toUpperCase() + query.type.slice(1));
return this[method](query);
} |
JavaScript | async function main () {
const run = new Run({ network: 'mock', owner: new TwoPlusTwoKey() })
class Dragon extends Jig { setName(name) { this.name = name } }
const dragon = new Dragon()
await dragon.sync()
dragon.setName('Victoria')
await dragon.sync()
console.log('Unlocked the custom lock')
} | async function main () {
const run = new Run({ network: 'mock', owner: new TwoPlusTwoKey() })
class Dragon extends Jig { setName(name) { this.name = name } }
const dragon = new Dragon()
await dragon.sync()
dragon.setName('Victoria')
await dragon.sync()
console.log('Unlocked the custom lock')
} |
JavaScript | formatString(string, replacements) {
return string.replace(/:(\w+)/g, (match, word) => {
if (this[word]) {
return '<span class="f-string-em">' + this[word] + '</span>'
} else if (replacements && replacements[word]) {
return replacements[word]
}
return match
})
} | formatString(string, replacements) {
return string.replace(/:(\w+)/g, (match, word) => {
if (this[word]) {
return '<span class="f-string-em">' + this[word] + '</span>'
} else if (replacements && replacements[word]) {
return replacements[word]
}
return match
})
} |
JavaScript | function textRepNewChat(phoneNum, question) {
var message = 'You have been assigned to help a customer with the following question: "' +
question + '" Please reply with an answer or a follow-up question.' +
" When the customer is satisfied, reply COMPLETE to end the chat.";
// Send message to rep if not locally testing
if (!appEnv.isLocal)
twilioHelper.sendTextMessage(twilioClient, twiloNumber, phoneNum, message);
} | function textRepNewChat(phoneNum, question) {
var message = 'You have been assigned to help a customer with the following question: "' +
question + '" Please reply with an answer or a follow-up question.' +
" When the customer is satisfied, reply COMPLETE to end the chat.";
// Send message to rep if not locally testing
if (!appEnv.isLocal)
twilioHelper.sendTextMessage(twilioClient, twiloNumber, phoneNum, message);
} |
JavaScript | function stabalizeDataStore() {
dbHelper.dbExists(nano, dbName, function (err,res) {
if (err) {
console.error("Cannot stabalize data store - error getting DB list");
}
else if (!res) {
console.log("DB does not exist - skip datastore stabalization");
}
else {
// Retrieve all open chats and mark them as Terminated
setTimeout(function(){}, 3000);
if (db) {
console.log("Terminating all open chats and notifying associated users")
dbHelper.getRecords(db, 'chats', 'chats_index', function(result) {
var chats = JSON.parse(result),
userMessage = "The server has shut down unexpectedly and your chat session has been closed as a result. We apologize for the inconvenience!",
repMessage = "Due to an unexpected server outage, we have ended your chat.",
chat;
for (var i=0; i < chats.length; i++) {
chat = chats[i];
if (chat.chatStatus !== "Completed" && chat.chatStatus !== "Terminated") {
// Update chat record in DB
saveChatRecord("Terminated", chat.bttn, chat.rep, chat.uniqueId, chat.revNum, chat.startTime, (new Date()).toString());
// Emit a notify socket event to client saying session closed
var notifySockCall = "notify_" + chat.bttn;
for (var value in sockets) {
sockets[value].emit(notifySockCall, {
message : userMessage
});
}
// If a rep has been assigned, update their status and send them a text
if (chat.rep) {
dbHelper.getDoc(db, 'reps', 'reps_index', 'uniqueId', chat.rep, function(rep) {
if (rep.phoneNumber) {
// Notify rep of server shut down
if (!appEnv.isLocal)
twilioHelper.sendTextMessage(twilioClient, twiloNumber, rep.phoneNumber, repMessage);
// Update rep record in DB
saveRepRecord(rep.name, rep.phoneNumber, "Available", rep.uniqueId, rep.revNum);
}
else {
console.log("Rep associated with chat " + chat.uniqueId + " was not found")
}
});
}
}
}
});
}
}
});
} | function stabalizeDataStore() {
dbHelper.dbExists(nano, dbName, function (err,res) {
if (err) {
console.error("Cannot stabalize data store - error getting DB list");
}
else if (!res) {
console.log("DB does not exist - skip datastore stabalization");
}
else {
// Retrieve all open chats and mark them as Terminated
setTimeout(function(){}, 3000);
if (db) {
console.log("Terminating all open chats and notifying associated users")
dbHelper.getRecords(db, 'chats', 'chats_index', function(result) {
var chats = JSON.parse(result),
userMessage = "The server has shut down unexpectedly and your chat session has been closed as a result. We apologize for the inconvenience!",
repMessage = "Due to an unexpected server outage, we have ended your chat.",
chat;
for (var i=0; i < chats.length; i++) {
chat = chats[i];
if (chat.chatStatus !== "Completed" && chat.chatStatus !== "Terminated") {
// Update chat record in DB
saveChatRecord("Terminated", chat.bttn, chat.rep, chat.uniqueId, chat.revNum, chat.startTime, (new Date()).toString());
// Emit a notify socket event to client saying session closed
var notifySockCall = "notify_" + chat.bttn;
for (var value in sockets) {
sockets[value].emit(notifySockCall, {
message : userMessage
});
}
// If a rep has been assigned, update their status and send them a text
if (chat.rep) {
dbHelper.getDoc(db, 'reps', 'reps_index', 'uniqueId', chat.rep, function(rep) {
if (rep.phoneNumber) {
// Notify rep of server shut down
if (!appEnv.isLocal)
twilioHelper.sendTextMessage(twilioClient, twiloNumber, rep.phoneNumber, repMessage);
// Update rep record in DB
saveRepRecord(rep.name, rep.phoneNumber, "Available", rep.uniqueId, rep.revNum);
}
else {
console.log("Rep associated with chat " + chat.uniqueId + " was not found")
}
});
}
}
}
});
}
}
});
} |
JavaScript | function saveRepRecord(name, phoneNum, state, uniqueId, revNum) {
var repRecord = {
'type' : "rep",
'repName' : name,
'repPhoneNum' : phoneNum,
'state' : state,
'_id' : uniqueId,
'_rev' : revNum
};
dbHelper.insertRecord(db, repRecord, function(result) {});
} | function saveRepRecord(name, phoneNum, state, uniqueId, revNum) {
var repRecord = {
'type' : "rep",
'repName' : name,
'repPhoneNum' : phoneNum,
'state' : state,
'_id' : uniqueId,
'_rev' : revNum
};
dbHelper.insertRecord(db, repRecord, function(result) {});
} |
JavaScript | function saveChatRecord(status, bttn, rep, uniqueId, revNum, start, end) {
var chatRecord = {
'type' : "chat",
'startTime' : start,
'chatStatus' : status,
'bttnId' : bttn,
'repId' : rep,
'_id' : uniqueId,
'_rev' : revNum
};
if (end) chatRecord.endTime = end;
dbHelper.insertRecord(db, chatRecord, function(result) {});
} | function saveChatRecord(status, bttn, rep, uniqueId, revNum, start, end) {
var chatRecord = {
'type' : "chat",
'startTime' : start,
'chatStatus' : status,
'bttnId' : bttn,
'repId' : rep,
'_id' : uniqueId,
'_rev' : revNum
};
if (end) chatRecord.endTime = end;
dbHelper.insertRecord(db, chatRecord, function(result) {});
} |
JavaScript | function saveMessageRecord(text, time, chat, subType) {
var msgRecord = {
'type' : "message",
'chatId' : chat,
'msgText' : text,
'msgTime' : time,
'subType' : subType
};
dbHelper.insertRecord(db, msgRecord, function(result) {});
} | function saveMessageRecord(text, time, chat, subType) {
var msgRecord = {
'type' : "message",
'chatId' : chat,
'msgText' : text,
'msgTime' : time,
'subType' : subType
};
dbHelper.insertRecord(db, msgRecord, function(result) {});
} |
JavaScript | function seedDB() {
// Create design docs and insert them
var designDocs = [
{
"_id": "_design/reps",
views: {
reps_index: {
map: function(doc) {
if (doc.type === 'rep') {
emit (doc._id, {
uniqueId : doc._id,
revNum : doc._rev,
name : doc.repName,
phoneNumber : doc.repPhoneNum,
state : doc.state
});
}
}
}
}
},
{
"_id": "_design/bttns",
views: {
bttns_index: {
map: function(doc) {
if (doc.type === 'bttn') {
emit (doc._id, {
uniqueId : doc._id,
revNum : doc._rev,
name : doc.bttnName,
bttnId : doc.bttnId
});
}
}
}
}
},
{
"_id": "_design/chats",
views: {
chats_index: {
map: function(doc) {
if (doc.type === 'chat') {
emit (doc._id, {
uniqueId : doc._id,
revNum : doc._rev,
startTime : doc.startTime,
chatStatus : doc.chatStatus,
bttn : doc.bttnId,
rep : doc.repId
});
}
}
}
}
},
{
"_id": "_design/messages",
views: {
messages_index: {
map: function(doc) {
if (doc.type === 'message') {
emit (doc._id, {
uniqueId : doc._id,
revNum : doc._rev,
chatId : doc.chatId,
message : doc.messageText,
date : doc.dateTime,
subType : doc.subType
});
}
}
}
}
},
];
designDocs.forEach(function(doc) {
db.insert(doc, doc._id, function(err, body) {
if (!err)
console.log(body);
});
});
// Create rep doc and insert it
var initialRep = {
"type" : "rep",
"repName" : "John Doe",
"repPhoneNum" : "15555555555",
"state" : "Available"
}
dbHelper.insertRecord(db, initialRep, function (res) {});
} | function seedDB() {
// Create design docs and insert them
var designDocs = [
{
"_id": "_design/reps",
views: {
reps_index: {
map: function(doc) {
if (doc.type === 'rep') {
emit (doc._id, {
uniqueId : doc._id,
revNum : doc._rev,
name : doc.repName,
phoneNumber : doc.repPhoneNum,
state : doc.state
});
}
}
}
}
},
{
"_id": "_design/bttns",
views: {
bttns_index: {
map: function(doc) {
if (doc.type === 'bttn') {
emit (doc._id, {
uniqueId : doc._id,
revNum : doc._rev,
name : doc.bttnName,
bttnId : doc.bttnId
});
}
}
}
}
},
{
"_id": "_design/chats",
views: {
chats_index: {
map: function(doc) {
if (doc.type === 'chat') {
emit (doc._id, {
uniqueId : doc._id,
revNum : doc._rev,
startTime : doc.startTime,
chatStatus : doc.chatStatus,
bttn : doc.bttnId,
rep : doc.repId
});
}
}
}
}
},
{
"_id": "_design/messages",
views: {
messages_index: {
map: function(doc) {
if (doc.type === 'message') {
emit (doc._id, {
uniqueId : doc._id,
revNum : doc._rev,
chatId : doc.chatId,
message : doc.messageText,
date : doc.dateTime,
subType : doc.subType
});
}
}
}
}
},
];
designDocs.forEach(function(doc) {
db.insert(doc, doc._id, function(err, body) {
if (!err)
console.log(body);
});
});
// Create rep doc and insert it
var initialRep = {
"type" : "rep",
"repName" : "John Doe",
"repPhoneNum" : "15555555555",
"state" : "Available"
}
dbHelper.insertRecord(db, initialRep, function (res) {});
} |
JavaScript | function showBubble(isQuestion, text) {
// Establish classes for new elements
var columnClass, borderClass, borderTipClass, borderTextClass;
if (isQuestion) {
columnClass = "col-lg-offset-7 col-md-offset-6 col-sm-offset-5 col-xs-offset-4 col-lg-5 col-md-6 col-sm-7 col-xs-8";
borderClass = "question-border";
borderTipClass = "question-border-tip";
borderTextClass = "question-text";
}
else {
columnClass = "col-lg-5 col-md-6 col-sm-7 col-xs-8";
borderClass = "answer-border";
borderTipClass = "answer-border-tip";
borderTextClass = "answer-text";
}
// Create HTML element for displaying question/answer
var row = document.createElement('div');
row.setAttribute('class', "row");
document.getElementById('conversation').appendChild(row);
var column = document.createElement('div');
column.setAttribute('class', columnClass);
row.appendChild(column);
var bubble = document.createElement('div');
bubble.setAttribute('class', borderClass);
column.appendChild(bubble);
var bubbleTip = document.createElement('div');
bubbleTip.setAttribute('class', borderTipClass);
bubble.appendChild(bubbleTip);
var outputText = document.createElement('p');
outputText.setAttribute('class', borderTextClass);
outputText.innerHTML = text;
bubbleTip.appendChild(outputText);
// If the first posted question, move the chat bubble tips into place
if (!questionExists)
{
alignBubbleTipElements(true, 90, -8.8, -53);
alignBubbleTipElements(false, 10, -1.9, 19);
}
} | function showBubble(isQuestion, text) {
// Establish classes for new elements
var columnClass, borderClass, borderTipClass, borderTextClass;
if (isQuestion) {
columnClass = "col-lg-offset-7 col-md-offset-6 col-sm-offset-5 col-xs-offset-4 col-lg-5 col-md-6 col-sm-7 col-xs-8";
borderClass = "question-border";
borderTipClass = "question-border-tip";
borderTextClass = "question-text";
}
else {
columnClass = "col-lg-5 col-md-6 col-sm-7 col-xs-8";
borderClass = "answer-border";
borderTipClass = "answer-border-tip";
borderTextClass = "answer-text";
}
// Create HTML element for displaying question/answer
var row = document.createElement('div');
row.setAttribute('class', "row");
document.getElementById('conversation').appendChild(row);
var column = document.createElement('div');
column.setAttribute('class', columnClass);
row.appendChild(column);
var bubble = document.createElement('div');
bubble.setAttribute('class', borderClass);
column.appendChild(bubble);
var bubbleTip = document.createElement('div');
bubbleTip.setAttribute('class', borderTipClass);
bubble.appendChild(bubbleTip);
var outputText = document.createElement('p');
outputText.setAttribute('class', borderTextClass);
outputText.innerHTML = text;
bubbleTip.appendChild(outputText);
// If the first posted question, move the chat bubble tips into place
if (!questionExists)
{
alignBubbleTipElements(true, 90, -8.8, -53);
alignBubbleTipElements(false, 10, -1.9, 19);
}
} |
JavaScript | function parseRequest(req) {
try {
let params = {
// check if query is valid
valid: true,
// if query is empty, send default greetings message
greet: false,
// service providers
source: [],
// query keys (feed link for RSS; username or slug for others)
queryKey: [],
}
const url = new URL(req)
const query = qs.parse(url.search, { ignoreQueryPrefix: true })
// empty query, send greetings
if (Object.keys(query).length === 0) {
params.greet = true
return params
}
// if source is null or query key is null, send invalid request
if (
query.source === '' ||
typeof query.source === 'undefined' ||
query.queryKey === '' ||
typeof query.queryKey === 'undefined'
) {
params.valid = false
return params
}
// parse source and queryString in query string
if (typeof query.source === 'string' && typeof query.queryKey === 'string') {
// single query key, maybe multiple sources
params.source = query.source.split('|')
// populate query key list
params.source.forEach(() => {
params.queryKey.push(query.queryKey)
})
} else if (query.source.length > 1 || query.queryKey.length > 1) {
// multiple query key, multiple sources
if (query.source.length === query.queryKey.length) {
params.source = query.source
params.queryKey = query.queryKey
} else {
// source and queryKey index doesn't match
params.valid = false
}
} else {
params.valid = false
}
console.log(params)
return params
} catch (error) {
return null
}
} | function parseRequest(req) {
try {
let params = {
// check if query is valid
valid: true,
// if query is empty, send default greetings message
greet: false,
// service providers
source: [],
// query keys (feed link for RSS; username or slug for others)
queryKey: [],
}
const url = new URL(req)
const query = qs.parse(url.search, { ignoreQueryPrefix: true })
// empty query, send greetings
if (Object.keys(query).length === 0) {
params.greet = true
return params
}
// if source is null or query key is null, send invalid request
if (
query.source === '' ||
typeof query.source === 'undefined' ||
query.queryKey === '' ||
typeof query.queryKey === 'undefined'
) {
params.valid = false
return params
}
// parse source and queryString in query string
if (typeof query.source === 'string' && typeof query.queryKey === 'string') {
// single query key, maybe multiple sources
params.source = query.source.split('|')
// populate query key list
params.source.forEach(() => {
params.queryKey.push(query.queryKey)
})
} else if (query.source.length > 1 || query.queryKey.length > 1) {
// multiple query key, multiple sources
if (query.source.length === query.queryKey.length) {
params.source = query.source
params.queryKey = query.queryKey
} else {
// source and queryKey index doesn't match
params.valid = false
}
} else {
params.valid = false
}
console.log(params)
return params
} catch (error) {
return null
}
} |
JavaScript | async function fetchStats(sources, queryKey) {
// function's returning value
let fetchStatsRes = {
totalSubs: 0,
subsInEachSource: {},
failedSources: {},
}
// result from upstream service provider
let res = {
subs: 0,
failed: false,
failedMsg: '',
}
// iterate over sources list and queryKey list, we use for loop to accommodate
// the await functions more easily
for (let i = 0; i < sources.length; i += 1) {
switch (sources[i]) {
case 'feedly':
res = await feedlyHandler(queryKey[i])
break
case 'github':
res = await gitHubHandler(queryKey[i])
break
case 'instagram':
res = await instagramHandler(queryKey[i])
break
case 'medium':
res = await mediumHandler(queryKey[i])
break
case 'sspai':
res = await sspaiHandler(queryKey[i])
break
case 'twitter':
res = await twitterHandler(queryKey[i])
break
case 'zhihu':
res = await zhihuHandler(queryKey[i])
break
case 'weibo':
res = await weiboHandler(queryKey[i])
break
default:
// not implemented
res.subs = 0
res.failed = true
res.failedMsg = 'Not implemented'
break
}
// populate returned result
if (res.failed) {
fetchStatsRes.failedSources[sources[i]] = res.failedMsg
}
fetchStatsRes.totalSubs += res.subs
fetchStatsRes.subsInEachSource[sources[i]] = res.subs
}
return fetchStatsRes
} | async function fetchStats(sources, queryKey) {
// function's returning value
let fetchStatsRes = {
totalSubs: 0,
subsInEachSource: {},
failedSources: {},
}
// result from upstream service provider
let res = {
subs: 0,
failed: false,
failedMsg: '',
}
// iterate over sources list and queryKey list, we use for loop to accommodate
// the await functions more easily
for (let i = 0; i < sources.length; i += 1) {
switch (sources[i]) {
case 'feedly':
res = await feedlyHandler(queryKey[i])
break
case 'github':
res = await gitHubHandler(queryKey[i])
break
case 'instagram':
res = await instagramHandler(queryKey[i])
break
case 'medium':
res = await mediumHandler(queryKey[i])
break
case 'sspai':
res = await sspaiHandler(queryKey[i])
break
case 'twitter':
res = await twitterHandler(queryKey[i])
break
case 'zhihu':
res = await zhihuHandler(queryKey[i])
break
case 'weibo':
res = await weiboHandler(queryKey[i])
break
default:
// not implemented
res.subs = 0
res.failed = true
res.failedMsg = 'Not implemented'
break
}
// populate returned result
if (res.failed) {
fetchStatsRes.failedSources[sources[i]] = res.failedMsg
}
fetchStatsRes.totalSubs += res.subs
fetchStatsRes.subsInEachSource[sources[i]] = res.subs
}
return fetchStatsRes
} |
JavaScript | handleProgress(batch, numSources) {
if (this.showProgress) {
const progress = new ProgressBar('[:bar] :percent', {
total: numSources,
width: 40
})
batch.on('progress', () => progress.tick())
}
} | handleProgress(batch, numSources) {
if (this.showProgress) {
const progress = new ProgressBar('[:bar] :percent', {
total: numSources,
width: 40
})
batch.on('progress', () => progress.tick())
}
} |
JavaScript | output(bucket, prefix, rename) {
rename = rename || null
this.target = {
bucket,
prefix,
rename
}
return this
} | output(bucket, prefix, rename) {
rename = rename || null
this.target = {
bucket,
prefix,
rename
}
return this
} |
JavaScript | each(func, isAsync, concurrency) {
isAsync = isAsync || this.opts.async
const batch = new Batch().concurrency(concurrency || this.opts.concurrency)
return new Promise((success, fail) => {
this.resolveSources().then((sources) => {
this.handleProgress(batch, sources.length)
const lastKey = sources[sources.length - 1]
// Loop over sources, apply function to each
sources.forEach((source) => {
const bucket = source.bucket
const key = source.key
const encoding = this.opts.encoding
const transformer = this.opts.transformer
batch.push((done) => {
this.s3.get(bucket, key, encoding, transformer).then((body) => {
if (isAsync) {
func(body, key).then(done).catch(done)
} else {
func(body, key)
done()
}
}).catch(done)
})
})
// Resolve error or last key processed.
batch.end((err) => {
if (err) {
fail(err)
} else {
success(lastKey)
}
})
}).catch(fail)
})
} | each(func, isAsync, concurrency) {
isAsync = isAsync || this.opts.async
const batch = new Batch().concurrency(concurrency || this.opts.concurrency)
return new Promise((success, fail) => {
this.resolveSources().then((sources) => {
this.handleProgress(batch, sources.length)
const lastKey = sources[sources.length - 1]
// Loop over sources, apply function to each
sources.forEach((source) => {
const bucket = source.bucket
const key = source.key
const encoding = this.opts.encoding
const transformer = this.opts.transformer
batch.push((done) => {
this.s3.get(bucket, key, encoding, transformer).then((body) => {
if (isAsync) {
func(body, key).then(done).catch(done)
} else {
func(body, key)
done()
}
}).catch(done)
})
})
// Resolve error or last key processed.
batch.end((err) => {
if (err) {
fail(err)
} else {
success(lastKey)
}
})
}).catch(fail)
})
} |
JavaScript | map(func, isAsync) {
if (this.target == null && this.destructive !== true) {
throw new Error('must use target() or inplace() for destructive operations (map, filter)')
}
isAsync = isAsync || this.opts.async
// Used to output from the map function (S3Lambda.context.output.map)
const mapOutput = (bucket, key, prefix, body, done) => {
if (body == null) {
throw new Error('mapper function must return a value')
}
if (this.target == null) {
this.s3.put(bucket, key, body, this.opts.encoding).then(() => {
done()
}).catch(done)
} else {
const outputBucket = this.target.bucket
let outputKey = key.replace(prefix, this.target.prefix)
// Rename output key (if necessary)
outputKey = this.target.rename ? this.rename(outputKey) : outputKey
this.s3.put(outputBucket, outputKey, body, this.opts.encoding).then(() => {
done()
}).catch((e) => {
done(e)
})
}
}
const batch = new Batch()
batch.concurrency(this.opts.concurrency)
return new Promise((success, fail) => {
this.resolveSources().then((sources) => {
this.handleProgress(batch, sources.length)
const lastKey = sources[sources.length - 1]
// Loop over sources, apply mapper function to each
sources.forEach((source) => {
const bucket = source.bucket
const key = source.key
const encoding = this.opts.encoding
const transformer = this.opts.transformer
batch.push((done) => {
this.s3.get(bucket, key, encoding, transformer).then((val) => {
if (isAsync) {
func(val, source.key).then((newval) => {
mapOutput(bucket, key, source.prefix, newval, done)
}).catch(done)
} else {
const newval = func(val, source.key)
mapOutput(bucket, key, source.prefix, newval, done)
}
}).catch(done)
})
})
// Resolve error or last key processed
batch.end((err) => {
if (err) {
fail(err)
}
success(lastKey)
})
}).catch(fail)
})
} | map(func, isAsync) {
if (this.target == null && this.destructive !== true) {
throw new Error('must use target() or inplace() for destructive operations (map, filter)')
}
isAsync = isAsync || this.opts.async
// Used to output from the map function (S3Lambda.context.output.map)
const mapOutput = (bucket, key, prefix, body, done) => {
if (body == null) {
throw new Error('mapper function must return a value')
}
if (this.target == null) {
this.s3.put(bucket, key, body, this.opts.encoding).then(() => {
done()
}).catch(done)
} else {
const outputBucket = this.target.bucket
let outputKey = key.replace(prefix, this.target.prefix)
// Rename output key (if necessary)
outputKey = this.target.rename ? this.rename(outputKey) : outputKey
this.s3.put(outputBucket, outputKey, body, this.opts.encoding).then(() => {
done()
}).catch((e) => {
done(e)
})
}
}
const batch = new Batch()
batch.concurrency(this.opts.concurrency)
return new Promise((success, fail) => {
this.resolveSources().then((sources) => {
this.handleProgress(batch, sources.length)
const lastKey = sources[sources.length - 1]
// Loop over sources, apply mapper function to each
sources.forEach((source) => {
const bucket = source.bucket
const key = source.key
const encoding = this.opts.encoding
const transformer = this.opts.transformer
batch.push((done) => {
this.s3.get(bucket, key, encoding, transformer).then((val) => {
if (isAsync) {
func(val, source.key).then((newval) => {
mapOutput(bucket, key, source.prefix, newval, done)
}).catch(done)
} else {
const newval = func(val, source.key)
mapOutput(bucket, key, source.prefix, newval, done)
}
}).catch(done)
})
})
// Resolve error or last key processed
batch.end((err) => {
if (err) {
fail(err)
}
success(lastKey)
})
}).catch(fail)
})
} |
JavaScript | reduce(func, initialValue, isAsync) {
isAsync = isAsync || this.opts.async
initialValue = initialValue || null
const batch = new Batch()
batch.concurrency(this.opts.concurrency)
return new Promise((success, fail) => {
this.resolveSources().then((sources) => {
this.handleProgress(batch, sources.length)
let accumulator = initialValue
// Loop over sources, update `accumulator`
sources.forEach((source) => {
const bucket = source.bucket
const key = source.key
const encoding = this.opts.encoding
const transformer = this.opts.transformer
batch.push((done) => {
this.s3.get(bucket, key, encoding, transformer).then((body) => {
if (isAsync) {
func(accumulator, body, key).then((newval) => {
accumulator = newval
done()
}).catch(done)
} else {
accumulator = func(accumulator, body, key)
done()
}
}).catch(done)
})
})
// Resolve error or reducer result `accumulator`
batch.end((err) => {
if (err) {
fail(err)
} else {
success(accumulator)
}
})
}).catch(fail)
})
} | reduce(func, initialValue, isAsync) {
isAsync = isAsync || this.opts.async
initialValue = initialValue || null
const batch = new Batch()
batch.concurrency(this.opts.concurrency)
return new Promise((success, fail) => {
this.resolveSources().then((sources) => {
this.handleProgress(batch, sources.length)
let accumulator = initialValue
// Loop over sources, update `accumulator`
sources.forEach((source) => {
const bucket = source.bucket
const key = source.key
const encoding = this.opts.encoding
const transformer = this.opts.transformer
batch.push((done) => {
this.s3.get(bucket, key, encoding, transformer).then((body) => {
if (isAsync) {
func(accumulator, body, key).then((newval) => {
accumulator = newval
done()
}).catch(done)
} else {
accumulator = func(accumulator, body, key)
done()
}
}).catch(done)
})
})
// Resolve error or reducer result `accumulator`
batch.end((err) => {
if (err) {
fail(err)
} else {
success(accumulator)
}
})
}).catch(fail)
})
} |
JavaScript | filter(func, isAsync) {
if (this.target == null && this.destructive !== true) {
throw new Error('must use target() or inplace() for destructive operations (map, filter)')
}
isAsync = isAsync || this.opts.async
const batch = new Batch()
// Keep a file when filtering
const keep = source => new Promise((success, fail) => {
if (this.target == null) {
// Since we are keeping the file and there is no output, there is
// nothing else to do
success()
} else {
const bucket = source.bucket
const key = source.key
const targetBucket = this.target.bucket
let targetKey = key.replace(source.prefix, this.target.prefix)
// Rename output key (if necessary)
targetKey = this.target.rename ? this.rename(targetKey) : targetKey
this.s3.copy(bucket, key, targetBucket, targetKey)
.then(() => success())
.catch(fail)
}
})
// Remove a file when filtering
const remove = source => new Promise((success, fail) => {
if (this.target == null) {
// For inplace filtering, we remove the actual file
this.s3.delete(source.bucket, source.key)
.then(() => success())
.catch(fail)
} else {
// If output is specified, there is nothing else to do, since we are
// simply not copying the file anywhere
success()
}
})
// Ensure the filter function returns a boolean
const check = (result) => {
if (typeof result !== 'boolean') {
throw new TypeError('filter function must return a boolean')
}
}
return new Promise((success, fail) => {
this.resolveSources().then((sources) => {
this.handleProgress(batch, sources.length)
const lastKey = sources[sources.length - 1]
// Loop over every key and run the filter function on each object. keep
// track of files to keep and remove.
sources.forEach((source) => {
const bucket = source.bucket
const key = source.key
const encoding = this.opts.encoding
const transformer = this.opts.transformer
batch.push((done) => {
this.s3.get(bucket, key, encoding, transformer).then((body) => {
if (isAsync) {
func(body, source).then((result) => {
check(result)
if (result) {
keep(source).then(() => done()).catch(done)
} else {
remove(source).then(() => done()).catch(done)
}
}).catch(done)
} else {
let result = null
result = func(body, source)
check(result)
if (result) {
keep(source).then(() => done()).catch(done)
} else {
remove(source).then(() => done()).catch(done)
}
}
}).catch(done)
})
})
// Resolve error or last source processed
batch.end((err) => {
if (err) {
fail(err)
} else {
success(lastKey)
}
})
}).catch(fail)
})
} | filter(func, isAsync) {
if (this.target == null && this.destructive !== true) {
throw new Error('must use target() or inplace() for destructive operations (map, filter)')
}
isAsync = isAsync || this.opts.async
const batch = new Batch()
// Keep a file when filtering
const keep = source => new Promise((success, fail) => {
if (this.target == null) {
// Since we are keeping the file and there is no output, there is
// nothing else to do
success()
} else {
const bucket = source.bucket
const key = source.key
const targetBucket = this.target.bucket
let targetKey = key.replace(source.prefix, this.target.prefix)
// Rename output key (if necessary)
targetKey = this.target.rename ? this.rename(targetKey) : targetKey
this.s3.copy(bucket, key, targetBucket, targetKey)
.then(() => success())
.catch(fail)
}
})
// Remove a file when filtering
const remove = source => new Promise((success, fail) => {
if (this.target == null) {
// For inplace filtering, we remove the actual file
this.s3.delete(source.bucket, source.key)
.then(() => success())
.catch(fail)
} else {
// If output is specified, there is nothing else to do, since we are
// simply not copying the file anywhere
success()
}
})
// Ensure the filter function returns a boolean
const check = (result) => {
if (typeof result !== 'boolean') {
throw new TypeError('filter function must return a boolean')
}
}
return new Promise((success, fail) => {
this.resolveSources().then((sources) => {
this.handleProgress(batch, sources.length)
const lastKey = sources[sources.length - 1]
// Loop over every key and run the filter function on each object. keep
// track of files to keep and remove.
sources.forEach((source) => {
const bucket = source.bucket
const key = source.key
const encoding = this.opts.encoding
const transformer = this.opts.transformer
batch.push((done) => {
this.s3.get(bucket, key, encoding, transformer).then((body) => {
if (isAsync) {
func(body, source).then((result) => {
check(result)
if (result) {
keep(source).then(() => done()).catch(done)
} else {
remove(source).then(() => done()).catch(done)
}
}).catch(done)
} else {
let result = null
result = func(body, source)
check(result)
if (result) {
keep(source).then(() => done()).catch(done)
} else {
remove(source).then(() => done()).catch(done)
}
}
}).catch(done)
})
})
// Resolve error or last source processed
batch.end((err) => {
if (err) {
fail(err)
} else {
success(lastKey)
}
})
}).catch(fail)
})
} |
JavaScript | function dict_iterator_next(self){
if(self.len_func() != self.len){
throw RuntimeError.$factory("dictionary changed size during iteration")
}
self.counter++
if(self.counter < self.items.length){
return self.items[self.counter]
}
throw _b_.StopIteration.$factory("StopIteration")
} | function dict_iterator_next(self){
if(self.len_func() != self.len){
throw RuntimeError.$factory("dictionary changed size during iteration")
}
self.counter++
if(self.counter < self.items.length){
return self.items[self.counter]
}
throw _b_.StopIteration.$factory("StopIteration")
} |
JavaScript | function photosSizeDistribution(dist) {
var $details = $("#details-stats");
$details.children().remove();
$details.empty();
var resolution = dist.resolution;
var dist = dist.data;
var minW, maxW, minH, maxH, maxCount;
for (var i=0; i<dist.length; i++) {
var d = dist[i];
if (!d.width || !d.height || !d.count) continue;
if (minW === undefined || d.width < minW) minW = d.width;
if (minH === undefined || d.height < minH) minH = d.height;
if (maxW === undefined || d.width > maxW) maxW = d.width;
if (maxH === undefined || d.height > maxH) maxH = d.height;
if (maxCount === undefined || d.count > maxCount) maxCount = d.count;
}
var rangeW = [];
var rangeH = [];
for (var i=minW; i<maxW; i+=resolution) { rangeW.push(i); }
for (var i=minH; i<maxH; i+=resolution) { rangeH.push(i); }
var data = [];
for (var i=0; i<dist.length; i++) {
var d = dist[i];
if (!d.width || !d.height || !d.count) continue;
data.push([d.width/resolution, d.height/resolution, d.count]);
}
$details.highcharts({
chart: { type: 'heatmap' },
title: { text: 'Distribution des images par taille' },
xAxis: { categories: rangeW, title:null },
yAxis: { categories: rangeH, title:null },
colorAxis: {
min: 0,
max: maxCount,
stops: [
[0, '#fffbbc'],
[0.1, '#3060cf'],
[0.7, '#c4463a'],
[1, '#c4463a']
],
},
tooltip: {
formatter: function () {
return '' + this.series.xAxis.categories[this.point.x] + ' x ' + this.series.yAxis.categories[this.point.y] + ' <br/>' +
'<b>Count: ' + this.point.value + '</b>';
}
},
series: [{
name: 'Image Count',
borderWidth: 1,
data: data,
dataLabels: { enabled: true, color: 'black', style: { textShadow: 'none' } }
}]
});
} | function photosSizeDistribution(dist) {
var $details = $("#details-stats");
$details.children().remove();
$details.empty();
var resolution = dist.resolution;
var dist = dist.data;
var minW, maxW, minH, maxH, maxCount;
for (var i=0; i<dist.length; i++) {
var d = dist[i];
if (!d.width || !d.height || !d.count) continue;
if (minW === undefined || d.width < minW) minW = d.width;
if (minH === undefined || d.height < minH) minH = d.height;
if (maxW === undefined || d.width > maxW) maxW = d.width;
if (maxH === undefined || d.height > maxH) maxH = d.height;
if (maxCount === undefined || d.count > maxCount) maxCount = d.count;
}
var rangeW = [];
var rangeH = [];
for (var i=minW; i<maxW; i+=resolution) { rangeW.push(i); }
for (var i=minH; i<maxH; i+=resolution) { rangeH.push(i); }
var data = [];
for (var i=0; i<dist.length; i++) {
var d = dist[i];
if (!d.width || !d.height || !d.count) continue;
data.push([d.width/resolution, d.height/resolution, d.count]);
}
$details.highcharts({
chart: { type: 'heatmap' },
title: { text: 'Distribution des images par taille' },
xAxis: { categories: rangeW, title:null },
yAxis: { categories: rangeH, title:null },
colorAxis: {
min: 0,
max: maxCount,
stops: [
[0, '#fffbbc'],
[0.1, '#3060cf'],
[0.7, '#c4463a'],
[1, '#c4463a']
],
},
tooltip: {
formatter: function () {
return '' + this.series.xAxis.categories[this.point.x] + ' x ' + this.series.yAxis.categories[this.point.y] + ' <br/>' +
'<b>Count: ' + this.point.value + '</b>';
}
},
series: [{
name: 'Image Count',
borderWidth: 1,
data: data,
dataLabels: { enabled: true, color: 'black', style: { textShadow: 'none' } }
}]
});
} |
JavaScript | function updatePhotosStats(stats) {
var $photos = $("#stats-photos");
$photos.children().remove();
$photos.empty();
if (!stats.photos) return;
$("<div class='stats-module-title'>").text("photos").appendTo($photos);
// Statistics on the number of photos
if (stats.photos.counts) {
$("<div class='stats-attr'>").text("" + stats.photos.counts.images + " photos").appendTo($photos);
$("<div class='stats-attr'>").text("" + stats.photos.counts.errors + " scan errors").appendTo($photos);
$("<div class='stats-attr'>").text("" + stats.photos.counts.images + " hotos without a onwer").appendTo($photos);
}
// Last time collection was scanned
var lastScanned = stats.photos.lastScanned;
if (!lastScanned || lastScanned==='') lastScanned = 'Never scanned';
else lastScanned = "Updated " + moment(lastScanned).fromNow();
$("<div class='stats-attr'>").text("" + lastScanned).appendTo($photos);
// Distribution of images per date
var $buttons = $("<div class='stats-buttons'>").appendTo($photos);
$("<button class='stats-button'>").text("Images distribution over time").appendTo($buttons).click(function() { photosDateDistribution(stats.photos.distByDate); });
$("<button class='stats-button'>").text("Images size distribution").appendTo($buttons).click(function() { photosSizeDistribution(stats.photos.distBySize); });
// Keyboard shortcuts
var $shortcuts = $("<div class='stats-shortcuts'>").appendTo($photos);
shortcut($shortcuts, "z", "Force thumbnails and exif regeneration for selection");
shortcut($shortcuts, "h", "Hide image");
shortcut($shortcuts, "c", "Set image as cover");
shortcut($shortcuts, "t + <key>", "Toggle a tag for the selection");
} | function updatePhotosStats(stats) {
var $photos = $("#stats-photos");
$photos.children().remove();
$photos.empty();
if (!stats.photos) return;
$("<div class='stats-module-title'>").text("photos").appendTo($photos);
// Statistics on the number of photos
if (stats.photos.counts) {
$("<div class='stats-attr'>").text("" + stats.photos.counts.images + " photos").appendTo($photos);
$("<div class='stats-attr'>").text("" + stats.photos.counts.errors + " scan errors").appendTo($photos);
$("<div class='stats-attr'>").text("" + stats.photos.counts.images + " hotos without a onwer").appendTo($photos);
}
// Last time collection was scanned
var lastScanned = stats.photos.lastScanned;
if (!lastScanned || lastScanned==='') lastScanned = 'Never scanned';
else lastScanned = "Updated " + moment(lastScanned).fromNow();
$("<div class='stats-attr'>").text("" + lastScanned).appendTo($photos);
// Distribution of images per date
var $buttons = $("<div class='stats-buttons'>").appendTo($photos);
$("<button class='stats-button'>").text("Images distribution over time").appendTo($buttons).click(function() { photosDateDistribution(stats.photos.distByDate); });
$("<button class='stats-button'>").text("Images size distribution").appendTo($buttons).click(function() { photosSizeDistribution(stats.photos.distBySize); });
// Keyboard shortcuts
var $shortcuts = $("<div class='stats-shortcuts'>").appendTo($photos);
shortcut($shortcuts, "z", "Force thumbnails and exif regeneration for selection");
shortcut($shortcuts, "h", "Hide image");
shortcut($shortcuts, "c", "Set image as cover");
shortcut($shortcuts, "t + <key>", "Toggle a tag for the selection");
} |
JavaScript | function updateCoreStats(stats) {
var $core = $("#stats-core");
$core.children().remove();
$core.empty();
if (!stats.core) return;
$("<div class='stats-module-title'>").text("core").appendTo($core);
// Distribution of images per date
var $buttons = $("<div class='stats-buttons'>").appendTo($core);
$("<button class='stats-button'>").text("Show curent jobs").appendTo($buttons).click(function() { coreJobs(); });
} | function updateCoreStats(stats) {
var $core = $("#stats-core");
$core.children().remove();
$core.empty();
if (!stats.core) return;
$("<div class='stats-module-title'>").text("core").appendTo($core);
// Distribution of images per date
var $buttons = $("<div class='stats-buttons'>").appendTo($core);
$("<button class='stats-button'>").text("Show curent jobs").appendTo($buttons).click(function() { coreJobs(); });
} |
JavaScript | function updateTreeregisterStats(stats) {
var $treeRegister = $("#stats-treeregister");
$treeRegister.children().remove();
$treeRegister.empty();
if (!stats.treeRegister) return;
$("<div class='stats-module-title'>").text("treeregister").appendTo($treeRegister);
} | function updateTreeregisterStats(stats) {
var $treeRegister = $("#stats-treeregister");
$treeRegister.children().remove();
$treeRegister.empty();
if (!stats.treeRegister) return;
$("<div class='stats-module-title'>").text("treeregister").appendTo($treeRegister);
} |
JavaScript | function updateMiouzikStats(stats) {
var $miouzik = $("#stats-miouzik");
$miouzik.children().remove();
$miouzik.empty();
if (!stats.miouzik) return;
$("<div class='stats-module-title'>").text("miouzik").appendTo($miouzik);
$("<div class='stats-attr'>").text("" + stats.miouzik.counts.songCount + " songs").appendTo($miouzik);
$("<div class='stats-attr'>").text("" + stats.miouzik.counts.artistCount + " artists").appendTo($miouzik);
$("<div class='stats-attr'>").text("" + stats.miouzik.counts.albumCount + " albums").appendTo($miouzik);
// Distribution of songs per date
var $buttons = $("<div class='stats-buttons'>").appendTo($miouzik);
$("<button class='stats-button'>").text("Songs distribution over time").appendTo($buttons).click(function() { miouzikDateDistribution(stats.miouzik.distByYear); });
$("<button class='stats-button'>").text("Songs distribution by genre").appendTo($buttons).click(function() { miouzikGenreDistribution(stats.miouzik.distByGenre); });
} | function updateMiouzikStats(stats) {
var $miouzik = $("#stats-miouzik");
$miouzik.children().remove();
$miouzik.empty();
if (!stats.miouzik) return;
$("<div class='stats-module-title'>").text("miouzik").appendTo($miouzik);
$("<div class='stats-attr'>").text("" + stats.miouzik.counts.songCount + " songs").appendTo($miouzik);
$("<div class='stats-attr'>").text("" + stats.miouzik.counts.artistCount + " artists").appendTo($miouzik);
$("<div class='stats-attr'>").text("" + stats.miouzik.counts.albumCount + " albums").appendTo($miouzik);
// Distribution of songs per date
var $buttons = $("<div class='stats-buttons'>").appendTo($miouzik);
$("<button class='stats-button'>").text("Songs distribution over time").appendTo($buttons).click(function() { miouzikDateDistribution(stats.miouzik.distByYear); });
$("<button class='stats-button'>").text("Songs distribution by genre").appendTo($buttons).click(function() { miouzikGenreDistribution(stats.miouzik.distByGenre); });
} |
JavaScript | function authenticate(db, userContext, credentials, callback) {
if (credentials.accessToken)
return _authenticateWithAccessToken(db, userContext, credentials.accessToken, callback);
if (credentials.login)
return _authenticateWithLoginPassword(db, userContext, credentials.login, credentials.password, callback);
return callback("Invalid credentials");
} | function authenticate(db, userContext, credentials, callback) {
if (credentials.accessToken)
return _authenticateWithAccessToken(db, userContext, credentials.accessToken, callback);
if (credentials.login)
return _authenticateWithLoginPassword(db, userContext, credentials.login, credentials.password, callback);
return callback("Invalid credentials");
} |
JavaScript | function _authenticateWithAccessToken(db, userContext, accessToken, callback) {
log.debug({ accessToken:accessToken }, "Authenticating");
return database.loadSessionByAccessToken(db, userContext, accessToken, function(err, session) {
if (err) return callback(err);
if (!session) {
log.debug({ accessToken:accessToken}, "Access token not found");
return callback(new AuthError(AUTH_ACCESS_TOKEN_NOT_FOUND, "Access token not found", { accessToken:accessToken }));
}
return _checkSession(db, userContext, session, function(err, newSession) {
return callback(err, newSession);
});
});
} | function _authenticateWithAccessToken(db, userContext, accessToken, callback) {
log.debug({ accessToken:accessToken }, "Authenticating");
return database.loadSessionByAccessToken(db, userContext, accessToken, function(err, session) {
if (err) return callback(err);
if (!session) {
log.debug({ accessToken:accessToken}, "Access token not found");
return callback(new AuthError(AUTH_ACCESS_TOKEN_NOT_FOUND, "Access token not found", { accessToken:accessToken }));
}
return _checkSession(db, userContext, session, function(err, newSession) {
return callback(err, newSession);
});
});
} |
JavaScript | function beforeAfter() {
// Called once before executing tests
before(function(done) {
// Longer timeout because database creation can take a few seconds
this.timeout(15000);
return recreateDatabase(function(err) {
return done(err);
});
});
// Called once after executing tests
after(function(done) {
log.warn("Shutting down database");
return Database.shutdown(function(err, stats) {
if (err) log.warn({err:err}, "Failed to shutdown database");
return done();
});
});
// Executed before each test
beforeEach(function(done) {
return asNobody(function() {
done();
});
});
} | function beforeAfter() {
// Called once before executing tests
before(function(done) {
// Longer timeout because database creation can take a few seconds
this.timeout(15000);
return recreateDatabase(function(err) {
return done(err);
});
});
// Called once after executing tests
after(function(done) {
log.warn("Shutting down database");
return Database.shutdown(function(err, stats) {
if (err) log.warn({err:err}, "Failed to shutdown database");
return done();
});
});
// Executed before each test
beforeEach(function(done) {
return asNobody(function() {
done();
});
});
} |
JavaScript | function _httpGet(url, callback) {
return http.get(url, function(res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function(d) { body += d; });
res.on('end', function() { return callback(undefined, body); });
res.on('error', function(err) { return callback(new Exception({url:url}, "Failed to execute HTTP request", err)); });
});
} | function _httpGet(url, callback) {
return http.get(url, function(res) {
res.setEncoding('utf8');
var body = '';
res.on('data', function(d) { body += d; });
res.on('end', function() { return callback(undefined, body); });
res.on('error', function(err) { return callback(new Exception({url:url}, "Failed to execute HTTP request", err)); });
});
} |
JavaScript | function formatSize(bytes) {
if (bytes < 1024) return "" + bytes + " b";
bytes = Math.floor(bytes/512)/2;
if (bytes < 1024) return "" + bytes + " Kb";
bytes = Math.floor(bytes/512)/2;
return "" + bytes + " Mb";
} | function formatSize(bytes) {
if (bytes < 1024) return "" + bytes + " b";
bytes = Math.floor(bytes/512)/2;
if (bytes < 1024) return "" + bytes + " Kb";
bytes = Math.floor(bytes/512)/2;
return "" + bytes + " Mb";
} |
JavaScript | function runWithWait(run, $body, callback) {
var running = true; // function is running
var $wait = undefined; // wait component
// Show timeout after .5 second, centered in $body
setTimeout(function() {
if (running) {
$('.nav-wait').remove();
var width = $body.width();
var height = $body.height();
$wait = $('<img class="nav-wait" src="images/wait-630.gif"></img>');
$wait.css({
position: 'absolute',
top: (height-80)/2,
left: (width-80)/2,
width: 80,
height: 80,
zIndex: 5000
});
$wait.appendTo($body);
}
}, 500);
// Execute function
run.call(this, function() {
var args = arguments;
running = false;
$('.nav-wait').remove();
return callback.apply(this, args);
});
} | function runWithWait(run, $body, callback) {
var running = true; // function is running
var $wait = undefined; // wait component
// Show timeout after .5 second, centered in $body
setTimeout(function() {
if (running) {
$('.nav-wait').remove();
var width = $body.width();
var height = $body.height();
$wait = $('<img class="nav-wait" src="images/wait-630.gif"></img>');
$wait.css({
position: 'absolute',
top: (height-80)/2,
left: (width-80)/2,
width: 80,
height: 80,
zIndex: 5000
});
$wait.appendTo($body);
}
}, 500);
// Execute function
run.call(this, function() {
var args = arguments;
running = false;
$('.nav-wait').remove();
return callback.apply(this, args);
});
} |
JavaScript | function openLoginDialog(initialMessage, callback) {
var configurationManager = new ConfigurationManager();
var userContext = document.userContext;
var modal = openDialog({ css: {height:520} }, function($body) {
var html = '<div class="login-frame"></div>' +
' <div class="login-user-avatar">' +
' <div class="login-user-avatar-circle-mask" style="background-image: none;">' +
' <img class="login-user-avatar-circle" width="96" height="96"></img>' +
' </div>' +
' </div>' +
' <div class="login-user-name"></div>' +
' <div class="login-user-email"></div>' +
' <input id="login" name="login" class="login-input-login" spellcheck="false" placeholder="Enter your login">' +
' <input id="password" type="password" spellcheck="false" name="password" class="login-input-password">' +
' <div class="login-error-message"></div>' +
' <button class="login-login">Login</button>'
var $login = $(html).appendTo($body);
if (initialMessage) $('.login-error-message').text(initialMessage);
$body.keydown(function(e) {
switch(e.which) {
case KEY_RETURN: { e.stopPropagation(); $(".login-login").click(); }
default: e.stopPropagation();
}
});
var avatar;
if (userContext && userContext.user) {
avatar = userContext.user.avatar;
if (!avatar || avatar.length===0) avatar = "/images/anonymous.jpg";
$(".login-user-avatar-circle").attr("src", avatar);
$(".login-user-name").text(userContext.user.name);
$(".login-user-email").text(userContext.user.email);
}
$(".login-input-login").blur(function() {
var login = $(".login-input-login").val();
var user = configurationManager.loadUser(login);
if (user) {
if (user.avatar && user.avatar.length > 0) $(".login-user-avatar-circle").attr("src", user.avatar);
if (user.name && user.name.length > 0) $(".login-user-name").text(user.name);
if (user.email && user.email.length > 0) $(".login-user-email").text(user.email);
}
});
$(".login-input-login").focus();
var $login = $(".login-login");
$login.click(function() {
var login = $(".login-input-login").val();
var password = $(".login-input-password").val();
return ajax({
type: 'POST',
url: '/login',
data: { login:login, password:password },
dataType: 'json',
success: function(userContext) {
document.userContext = userContext;
configurationManager.saveUserContext(userContext);
configurationManager.saveUser(userContext.user.login, userContext.user);
modal.close();
if (callback) callback.call(this);
else location.reload();
},
error: function(jqxhr, textStatus, error) {
if (jqxhr && jqxhr.status === 401) {
try {
var res = JSON.parse(jqxhr.responseText);
var message = res.message;
if (message && message.length > 0) {
$('.login-error-message').text(message);
}
}
finally {}
}
}
});
});
});
} | function openLoginDialog(initialMessage, callback) {
var configurationManager = new ConfigurationManager();
var userContext = document.userContext;
var modal = openDialog({ css: {height:520} }, function($body) {
var html = '<div class="login-frame"></div>' +
' <div class="login-user-avatar">' +
' <div class="login-user-avatar-circle-mask" style="background-image: none;">' +
' <img class="login-user-avatar-circle" width="96" height="96"></img>' +
' </div>' +
' </div>' +
' <div class="login-user-name"></div>' +
' <div class="login-user-email"></div>' +
' <input id="login" name="login" class="login-input-login" spellcheck="false" placeholder="Enter your login">' +
' <input id="password" type="password" spellcheck="false" name="password" class="login-input-password">' +
' <div class="login-error-message"></div>' +
' <button class="login-login">Login</button>'
var $login = $(html).appendTo($body);
if (initialMessage) $('.login-error-message').text(initialMessage);
$body.keydown(function(e) {
switch(e.which) {
case KEY_RETURN: { e.stopPropagation(); $(".login-login").click(); }
default: e.stopPropagation();
}
});
var avatar;
if (userContext && userContext.user) {
avatar = userContext.user.avatar;
if (!avatar || avatar.length===0) avatar = "/images/anonymous.jpg";
$(".login-user-avatar-circle").attr("src", avatar);
$(".login-user-name").text(userContext.user.name);
$(".login-user-email").text(userContext.user.email);
}
$(".login-input-login").blur(function() {
var login = $(".login-input-login").val();
var user = configurationManager.loadUser(login);
if (user) {
if (user.avatar && user.avatar.length > 0) $(".login-user-avatar-circle").attr("src", user.avatar);
if (user.name && user.name.length > 0) $(".login-user-name").text(user.name);
if (user.email && user.email.length > 0) $(".login-user-email").text(user.email);
}
});
$(".login-input-login").focus();
var $login = $(".login-login");
$login.click(function() {
var login = $(".login-input-login").val();
var password = $(".login-input-password").val();
return ajax({
type: 'POST',
url: '/login',
data: { login:login, password:password },
dataType: 'json',
success: function(userContext) {
document.userContext = userContext;
configurationManager.saveUserContext(userContext);
configurationManager.saveUser(userContext.user.login, userContext.user);
modal.close();
if (callback) callback.call(this);
else location.reload();
},
error: function(jqxhr, textStatus, error) {
if (jqxhr && jqxhr.status === 401) {
try {
var res = JSON.parse(jqxhr.responseText);
var message = res.message;
if (message && message.length > 0) {
$('.login-error-message').text(message);
}
}
finally {}
}
}
});
});
});
} |
JavaScript | function ajax(data) {
var successFn = data.success;
var errorFn = data.error;
var completeFn = data.complete;
data.complete = function() {
if (completeFn)
return completeFn.apply(this, arguments);
}
data.success = function() {
if (successFn)
return successFn.apply(this, arguments);
}
data.error = function(jqxhr, textStatus, error) {
// HTTP error
if (jqxhr.readyState === 4) {
if (jqxhr.status === 401) {
if (jqxhr.responseJSON && jqxhr.responseJSON.code === 13) {
// Token expired
return openLoginDialog('Session expired, please login again', function() {
// Retry operation
return ajax(data);
});
}
}
if (errorFn)
return errorFn.call(this, jqxhr, textStatus, error);
}
// Network error (i.e. connection refused, access denied due to CORS, etc.)
else if (jqxhr.readyState === 0) {
flashError("Server unreachable");
return
}
// Other errors (should not happen)
else {
flashError("Unknown error");
return
}
}
return $.ajax(data);
} | function ajax(data) {
var successFn = data.success;
var errorFn = data.error;
var completeFn = data.complete;
data.complete = function() {
if (completeFn)
return completeFn.apply(this, arguments);
}
data.success = function() {
if (successFn)
return successFn.apply(this, arguments);
}
data.error = function(jqxhr, textStatus, error) {
// HTTP error
if (jqxhr.readyState === 4) {
if (jqxhr.status === 401) {
if (jqxhr.responseJSON && jqxhr.responseJSON.code === 13) {
// Token expired
return openLoginDialog('Session expired, please login again', function() {
// Retry operation
return ajax(data);
});
}
}
if (errorFn)
return errorFn.call(this, jqxhr, textStatus, error);
}
// Network error (i.e. connection refused, access denied due to CORS, etc.)
else if (jqxhr.readyState === 0) {
flashError("Server unreachable");
return
}
// Other errors (should not happen)
else {
flashError("Unknown error");
return
}
}
return $.ajax(data);
} |
JavaScript | function classes(root) {
var classes = [];
function recurse(name, node) {
if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
else classes.push({packageName: name, className: node.name, value: node.size});
}
recurse(null, root);
return {children: classes};
} | function classes(root) {
var classes = [];
function recurse(name, node) {
if (node.children) node.children.forEach(function(child) { recurse(node.name, child); });
else classes.push({packageName: name, className: node.name, value: node.size});
}
recurse(null, root);
return {children: classes};
} |
JavaScript | function createShader(gl, type, source) {
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw new Error(gl.getShaderInfoLog(shader));
}
return shader;
} | function createShader(gl, type, source) {
var shader = gl.createShader(type);
gl.shaderSource(shader, source);
gl.compileShader(shader);
if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
throw new Error(gl.getShaderInfoLog(shader));
}
return shader;
} |
JavaScript | function createTexture(gl, filter, data, width, height) {
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
if (data instanceof Uint8Array) {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
console.log('created Uint8 texture');
} else if (data instanceof Float32Array) {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, width, height, 0, gl.RGBA, gl.FLOAT, data);
console.log('created Float32 texture');
} else {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
}
gl.bindTexture(gl.TEXTURE_2D, null);
return texture;
} | function createTexture(gl, filter, data, width, height) {
var texture = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, texture);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filter);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filter);
if (data instanceof Uint8Array) {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
console.log('created Uint8 texture');
} else if (data instanceof Float32Array) {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA32F, width, height, 0, gl.RGBA, gl.FLOAT, data);
console.log('created Float32 texture');
} else {
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, data);
}
gl.bindTexture(gl.TEXTURE_2D, null);
return texture;
} |
JavaScript | function generateChildTree(ulTemp, setupModules) {
// eliminate the undefined types
if (!(typeof setupModules === 'undefined')) {
for (var j= 0, listValue; listValue = setupModules[j++];) {
child = listValue;
if (typeof child === 'string') {
// child is string, append on same level
var liSetupFile=document.createElement('li');
liSetupFile.innerHTML=child;
ulTemp.appendChild(liSetupFile);
} else {
// child is list of dictionaries, create new folder for each with key as folder name and value of list as files
for (var key in child) {
var liFolder = document.createElement('li');
liFolder.innerHTML = key; // root folder
var ulInside = document.createElement('ul');
ulInside.className = 'tree';
// recursive call for list in the directory
generateChildTree(ulInside, child[key]);
liFolder.appendChild(ulInside);
ulTemp.appendChild(liFolder);
}
}
}
}
} | function generateChildTree(ulTemp, setupModules) {
// eliminate the undefined types
if (!(typeof setupModules === 'undefined')) {
for (var j= 0, listValue; listValue = setupModules[j++];) {
child = listValue;
if (typeof child === 'string') {
// child is string, append on same level
var liSetupFile=document.createElement('li');
liSetupFile.innerHTML=child;
ulTemp.appendChild(liSetupFile);
} else {
// child is list of dictionaries, create new folder for each with key as folder name and value of list as files
for (var key in child) {
var liFolder = document.createElement('li');
liFolder.innerHTML = key; // root folder
var ulInside = document.createElement('ul');
ulInside.className = 'tree';
// recursive call for list in the directory
generateChildTree(ulInside, child[key]);
liFolder.appendChild(ulInside);
ulTemp.appendChild(liFolder);
}
}
}
}
} |
JavaScript | function usersReducer(state = initialState.users, action) {
let newState;
switch (action.type) {
case FETCH_USERS:
newState = objectAssign({}, state);
newState.persons = action.persons;
return newState;
default:
return state;
}
} | function usersReducer(state = initialState.users, action) {
let newState;
switch (action.type) {
case FETCH_USERS:
newState = objectAssign({}, state);
newState.persons = action.persons;
return newState;
default:
return state;
}
} |
JavaScript | function postsReducer(state = initialState.posts, action) {
let newState;
switch (action.type) {
case FETCH_POSTS:
newState = objectAssign({}, state);
newState.posts = action.posts;
newState.filteredPosts = action.posts.filter(post =>
post.title.includes(newState.filterKeyword)
|| post.body.includes(newState.filterKeyword));
return newState;
case CHANGE_SEARCH_KEYWORD:
newState = objectAssign({}, state);
newState.filterKeyword = action.keyword;
newState.filteredPosts = newState.posts.filter(post =>
post.title.includes(newState.filterKeyword)
|| post.body.includes(newState.filterKeyword));
return newState;
default:
return state;
}
} | function postsReducer(state = initialState.posts, action) {
let newState;
switch (action.type) {
case FETCH_POSTS:
newState = objectAssign({}, state);
newState.posts = action.posts;
newState.filteredPosts = action.posts.filter(post =>
post.title.includes(newState.filterKeyword)
|| post.body.includes(newState.filterKeyword));
return newState;
case CHANGE_SEARCH_KEYWORD:
newState = objectAssign({}, state);
newState.filterKeyword = action.keyword;
newState.filteredPosts = newState.posts.filter(post =>
post.title.includes(newState.filterKeyword)
|| post.body.includes(newState.filterKeyword));
return newState;
default:
return state;
}
} |
JavaScript | async openChatWindow(chatId) {
await this.pupPage.evaluate(async chatId => {
let chat = await window.Store.Chat.get(chatId);
await window.Store.Cmd.openChatAt(chat);
}, chatId);
} | async openChatWindow(chatId) {
await this.pupPage.evaluate(async chatId => {
let chat = await window.Store.Chat.get(chatId);
await window.Store.Cmd.openChatAt(chat);
}, chatId);
} |
JavaScript | async openChatDrawer(chatId) {
await this.pupPage.evaluate(async chatId => {
let chat = await window.Store.Chat.get(chatId);
await window.Store.Cmd.chatInfoDrawer(chat);
}, chatId);
} | async openChatDrawer(chatId) {
await this.pupPage.evaluate(async chatId => {
let chat = await window.Store.Chat.get(chatId);
await window.Store.Cmd.chatInfoDrawer(chat);
}, chatId);
} |
JavaScript | function stringifyNode($node) {
if (!$node || !$node.length)
return "[nothing]";
switch(nodeType($node)) {
case 'text':
var text = $node.text();
if (text.length > 40)
text = text.substring(0, 37) + "...";
return '"' + text + '"';
default:
var $ = $node.cheerio;
var $clone = $node.clone();
// shorten HTML if necessary
var originalHTML = $clone.html();
if (originalHTML && originalHTML.length > 80)
$clone.html("...");
return $.html($clone);
}
} | function stringifyNode($node) {
if (!$node || !$node.length)
return "[nothing]";
switch(nodeType($node)) {
case 'text':
var text = $node.text();
if (text.length > 40)
text = text.substring(0, 37) + "...";
return '"' + text + '"';
default:
var $ = $node.cheerio;
var $clone = $node.clone();
// shorten HTML if necessary
var originalHTML = $clone.html();
if (originalHTML && originalHTML.length > 80)
$clone.html("...");
return $.html($clone);
}
} |
JavaScript | function compareTags($n1, $n2, heuristic) {
var localChanges = _.compact([getLocalTagChange($n1, $n2)]);
var childChanges = compareChildren($n1, $n2, options);
var diffLevel = heuristic($n1, $n2, childChanges);
if (diffLevel == DiffLevel.IDENTICAL) {
return false;
} else {
return { level: diffLevel, changes: localChanges.concat(childChanges) };
}
} | function compareTags($n1, $n2, heuristic) {
var localChanges = _.compact([getLocalTagChange($n1, $n2)]);
var childChanges = compareChildren($n1, $n2, options);
var diffLevel = heuristic($n1, $n2, childChanges);
if (diffLevel == DiffLevel.IDENTICAL) {
return false;
} else {
return { level: diffLevel, changes: localChanges.concat(childChanges) };
}
} |
JavaScript | function locationInfo($parentNode, $node, index) {
var siblingsInfo = findSiblings($parentNode, $node, index);
return _.extend(siblingsInfo, {
// paths to the node itself and the parent
parentPath: cssPath($parentNode),
path: $node ? cssPath($node) : undefined,
// index of the node (or the point where you'd have to insert it, if it's not in this DOM)
index: index,
// nodes
$node: $node, $parent: $parentNode
});
} | function locationInfo($parentNode, $node, index) {
var siblingsInfo = findSiblings($parentNode, $node, index);
return _.extend(siblingsInfo, {
// paths to the node itself and the parent
parentPath: cssPath($parentNode),
path: $node ? cssPath($node) : undefined,
// index of the node (or the point where you'd have to insert it, if it's not in this DOM)
index: index,
// nodes
$node: $node, $parent: $parentNode
});
} |
JavaScript | function compare(before, after, options) {
// prepare the options object so we don't have to validate everything down the road
options = prepareOptions(options);
// parse both pieces of HTML with cheerio and get the root nodes
var $1 = cheerio.load(before);
var $2 = cheerio.load(after);
var $n1 = node($1, $1.root());
var $n2 = node($2, $2.root());
// prepare input (remove or canonicalize things that produce false positives, strip ignored content)
prepareForDiff($n1, options);
prepareForDiff($n2, options);
// compare the roots recursively
var diffObject = compareNodes($n1, $n2, options);
// create a meaningful object describing the comparison result
return {
// actual results - was it different and what was changed?
different: !!diffObject.changes,
changes: diffObject ? diffObject.changes : [],
// access to the strings that were compared
before: before,
after: after,
// cheerioed copies of the strings, for making working with changes easy
$before: $1,
$after: $2
};
} | function compare(before, after, options) {
// prepare the options object so we don't have to validate everything down the road
options = prepareOptions(options);
// parse both pieces of HTML with cheerio and get the root nodes
var $1 = cheerio.load(before);
var $2 = cheerio.load(after);
var $n1 = node($1, $1.root());
var $n2 = node($2, $2.root());
// prepare input (remove or canonicalize things that produce false positives, strip ignored content)
prepareForDiff($n1, options);
prepareForDiff($n2, options);
// compare the roots recursively
var diffObject = compareNodes($n1, $n2, options);
// create a meaningful object describing the comparison result
return {
// actual results - was it different and what was changed?
different: !!diffObject.changes,
changes: diffObject ? diffObject.changes : [],
// access to the strings that were compared
before: before,
after: after,
// cheerioed copies of the strings, for making working with changes easy
$before: $1,
$after: $2
};
} |
JavaScript | function prepareOptions(options) {
// use defaults
options = _.defaults(options || {}, DEFAULT_OPTIONS);
// disenchant magic values
if (options.ignoreText === true) {
options.ignoreText = ['*'];
}
options.tagComparison = prepareTagHeuristic(options.tagComparison);
// sanitize lists
['ignore', 'ignoreText'].map(function(name) {
options[name] = ensureArray(options[name]);
});
// make a place to store memoized comparison results
options.memo = {};
// return the new object
return options;
} | function prepareOptions(options) {
// use defaults
options = _.defaults(options || {}, DEFAULT_OPTIONS);
// disenchant magic values
if (options.ignoreText === true) {
options.ignoreText = ['*'];
}
options.tagComparison = prepareTagHeuristic(options.tagComparison);
// sanitize lists
['ignore', 'ignoreText'].map(function(name) {
options[name] = ensureArray(options[name]);
});
// make a place to store memoized comparison results
options.memo = {};
// return the new object
return options;
} |
JavaScript | function prepareTagHeuristic(tagComparison) {
if (typeof tagComparison === 'undefined') {
return createTagHeuristic(); // default heuristic
} else if (typeof tagComparison === 'function') {
return tagComparison; // custom, user-provided function
} else if (typeof tagComparison === 'object') {
return createTagHeuristic(tagComparison); // options for the default heuristic
} else {
throw new Error("Invalid 'tagComparison' option provided: " + tagComparison);
}
} | function prepareTagHeuristic(tagComparison) {
if (typeof tagComparison === 'undefined') {
return createTagHeuristic(); // default heuristic
} else if (typeof tagComparison === 'function') {
return tagComparison; // custom, user-provided function
} else if (typeof tagComparison === 'object') {
return createTagHeuristic(tagComparison); // options for the default heuristic
} else {
throw new Error("Invalid 'tagComparison' option provided: " + tagComparison);
}
} |
JavaScript | placeChip({ chip, column }) {
this.columns[column].push(chip);
this.lastPlacedChip = chip;
chip.column = column;
chip.row = this.columns[column].length - 1;
} | placeChip({ chip, column }) {
this.columns[column].push(chip);
this.lastPlacedChip = chip;
chip.column = column;
chip.row = this.columns[column].length - 1;
} |
JavaScript | reset() {
// The cached width of a single chip
this.resetCachedChipWidth();
this.pendingChipColumn = 0;
this.pendingChipRow = this.grid.rowCount;
// Booleans indicating when to transition the pending chip's movement in a
// particular direction (for example, the pending chip should never
// transition when resetting to its initial position after placing a chip)
this.transitionPendingChipX = false;
this.transitionPendingChipY = false;
} | reset() {
// The cached width of a single chip
this.resetCachedChipWidth();
this.pendingChipColumn = 0;
this.pendingChipRow = this.grid.rowCount;
// Booleans indicating when to transition the pending chip's movement in a
// particular direction (for example, the pending chip should never
// transition when resetting to its initial position after placing a chip)
this.transitionPendingChipX = false;
this.transitionPendingChipY = false;
} |
JavaScript | alignPendingChipWithColumn({ column, transitionEnd, emit = false }) {
// The last visited column is the grid column nearest to the cursor at
// any given instant; keep track of the column's X position so the next
// pending chip can instantaneously appear there
if (column !== this.pendingChipColumn) {
if (emit) {
this.emitAlignEvent({ column });
}
this.pendingChipColumn = column;
this.pendingChipRow = this.grid.rowCount;
this.transitionPendingChipX = true;
this.transitionPendingChipY = false;
this.waitForPendingChipTransitionEnd(() => {
this.transitionPendingChipX = false;
this.resetCachedChipWidth();
// Allow the caller of alignPendingChipWithColumn() to provide an
// arbitrary callback to run when the pending chip transition ends
if (transitionEnd) {
transitionEnd();
}
});
}
} | alignPendingChipWithColumn({ column, transitionEnd, emit = false }) {
// The last visited column is the grid column nearest to the cursor at
// any given instant; keep track of the column's X position so the next
// pending chip can instantaneously appear there
if (column !== this.pendingChipColumn) {
if (emit) {
this.emitAlignEvent({ column });
}
this.pendingChipColumn = column;
this.pendingChipRow = this.grid.rowCount;
this.transitionPendingChipX = true;
this.transitionPendingChipY = false;
this.waitForPendingChipTransitionEnd(() => {
this.transitionPendingChipX = false;
this.resetCachedChipWidth();
// Allow the caller of alignPendingChipWithColumn() to provide an
// arbitrary callback to run when the pending chip transition ends
if (transitionEnd) {
transitionEnd();
}
});
}
} |
JavaScript | alignPendingChipViaPointer(mousemoveEvent) {
if (this.game.pendingChip && this.game.currentPlayer.type === 'human' && !this.transitionPendingChipY) {
this.alignPendingChipWithColumn({
column: this.getLastVisitedColumn(mousemoveEvent),
emit: true
});
} else {
mousemoveEvent.redraw = false;
}
} | alignPendingChipViaPointer(mousemoveEvent) {
if (this.game.pendingChip && this.game.currentPlayer.type === 'human' && !this.transitionPendingChipY) {
this.alignPendingChipWithColumn({
column: this.getLastVisitedColumn(mousemoveEvent),
emit: true
});
} else {
mousemoveEvent.redraw = false;
}
} |
JavaScript | placePendingChip({ column }) {
const row = this.grid.getNextAvailableSlot({ column });
// Do not allow user to place chip in column that is already full
if (row === null) {
return;
}
// If pending chip is not currently aligned with chosen column
if (this.pendingChipColumn !== column) {
// First align pending chip with column
this.alignPendingChipWithColumn({
column,
// Only emit for human players
emit: !this.game.currentPlayer.wait,
transitionEnd: () => {
// When it's the AI's turn or any async player's turn, automatically
// place the chip after aligning it with the specified column
if (this.game.currentPlayer.wait) {
this.game.currentPlayer.wait(() => {
this.placePendingChip({ column });
});
}
}
});
} else if (this.transitionPendingChipX) {
// Detect and prevent a race condition where placePendingChip is called
// while the pending chip is still transitioning on the X axis (via
// alignPendingChipWithColumn), causing the chip to travel diagonally
// across the board; to fix this, wait for the current alignment
// transition to finish before starting the placePendingChip transition
this.waitForPendingChipTransitionEnd(() => {
// Make sure to reset transitionPendingChipX back to false to prevent
// the above if statement from executing again upon re-entry of the
// placePendingChip()
this.transitionPendingChipX = false;
this.placePendingChip({ column });
});
} else {
// Otherwise, chip is already aligned; drop chip into place on grid
this.transitionPendingChipX = false;
this.transitionPendingChipY = true;
this.pendingChipColumn = column;
this.pendingChipRow = row;
// Perform insertion on internal game grid once transition has ended
this.finishPlacingPendingChip({ column });
}
m.redraw();
} | placePendingChip({ column }) {
const row = this.grid.getNextAvailableSlot({ column });
// Do not allow user to place chip in column that is already full
if (row === null) {
return;
}
// If pending chip is not currently aligned with chosen column
if (this.pendingChipColumn !== column) {
// First align pending chip with column
this.alignPendingChipWithColumn({
column,
// Only emit for human players
emit: !this.game.currentPlayer.wait,
transitionEnd: () => {
// When it's the AI's turn or any async player's turn, automatically
// place the chip after aligning it with the specified column
if (this.game.currentPlayer.wait) {
this.game.currentPlayer.wait(() => {
this.placePendingChip({ column });
});
}
}
});
} else if (this.transitionPendingChipX) {
// Detect and prevent a race condition where placePendingChip is called
// while the pending chip is still transitioning on the X axis (via
// alignPendingChipWithColumn), causing the chip to travel diagonally
// across the board; to fix this, wait for the current alignment
// transition to finish before starting the placePendingChip transition
this.waitForPendingChipTransitionEnd(() => {
// Make sure to reset transitionPendingChipX back to false to prevent
// the above if statement from executing again upon re-entry of the
// placePendingChip()
this.transitionPendingChipX = false;
this.placePendingChip({ column });
});
} else {
// Otherwise, chip is already aligned; drop chip into place on grid
this.transitionPendingChipX = false;
this.transitionPendingChipY = true;
this.pendingChipColumn = column;
this.pendingChipRow = row;
// Perform insertion on internal game grid once transition has ended
this.finishPlacingPendingChip({ column });
}
m.redraw();
} |
JavaScript | placePendingChipViaPointer(clickEvent) {
if (this.game.pendingChip && this.game.currentPlayer.type === 'human' && !this.transitionPendingChipX && !this.transitionPendingChipY) {
this.placePendingChip({
column: this.getLastVisitedColumn(clickEvent)
});
} else {
clickEvent.redraw = false;
}
} | placePendingChipViaPointer(clickEvent) {
if (this.game.pendingChip && this.game.currentPlayer.type === 'human' && !this.transitionPendingChipX && !this.transitionPendingChipY) {
this.placePendingChip({
column: this.getLastVisitedColumn(clickEvent)
});
} else {
clickEvent.redraw = false;
}
} |
JavaScript | initializePendingChip({ dom }) {
// Ensure that any unfinished pending chip event listeners (from
// previous games) are unbound
this.off('pending-chip:transition-end');
// Listen for whenever a pending chip transition finishes
const eventName = Browser.getNormalizedEventName('transitionend');
dom.addEventListener(eventName, (event) => {
// The transitionend DOM event can fire multiple times (undesirably) if
// the children also have transitions; ensure that the
// pending-chip:transition-end event is only emitted for the parent's
// transition; see https://stackoverflow.com/q/26309838/560642
if (event.target === dom) {
this.emit('pending-chip:transition-end');
}
});
} | initializePendingChip({ dom }) {
// Ensure that any unfinished pending chip event listeners (from
// previous games) are unbound
this.off('pending-chip:transition-end');
// Listen for whenever a pending chip transition finishes
const eventName = Browser.getNormalizedEventName('transitionend');
dom.addEventListener(eventName, (event) => {
// The transitionend DOM event can fire multiple times (undesirably) if
// the children also have transitions; ensure that the
// pending-chip:transition-end event is only emitted for the parent's
// transition; see https://stackoverflow.com/q/26309838/560642
if (event.target === dom) {
this.emit('pending-chip:transition-end');
}
});
} |
JavaScript | broadcast(eventName, data) {
this.players.forEach((player) => {
if (player !== this) {
player.emit(eventName, player.injectLocalPlayer(data));
}
});
} | broadcast(eventName, data) {
this.players.forEach((player) => {
if (player !== this) {
player.emit(eventName, player.injectLocalPlayer(data));
}
});
} |
JavaScript | function addBranch() {
if (contextObject.userType === 'trainer') {
return (
<TouchableOpacity style={styles.addBranchButton} onPress={() => setBranchModalVisible(true)}>
<Text style={styles.addBranchButtonText}>+</Text>
</TouchableOpacity>
);
}
} | function addBranch() {
if (contextObject.userType === 'trainer') {
return (
<TouchableOpacity style={styles.addBranchButton} onPress={() => setBranchModalVisible(true)}>
<Text style={styles.addBranchButtonText}>+</Text>
</TouchableOpacity>
);
}
} |
JavaScript | function addExercise(eID) {
if (addRemove == false && contextObject.workoutList.findIndex(y => y.exerciseID === eID)) {
contextObject.workoutList.push({ exerciseID: eID, title: title, description: description, picture: picture });
setAddRemove(true);
setAddRemoveButton(<Image source={require('../assets/MinusIcon.png')} />);
} else {
var index = contextObject.workoutList.findIndex(y => y.exerciseID === eID);
if (index !== -1) {
contextObject.workoutList.splice(index, 1);
}
setAddRemove(false);
setAddRemoveButton(<Image source={require('../assets/PlusIcon.png')} />);
}
} | function addExercise(eID) {
if (addRemove == false && contextObject.workoutList.findIndex(y => y.exerciseID === eID)) {
contextObject.workoutList.push({ exerciseID: eID, title: title, description: description, picture: picture });
setAddRemove(true);
setAddRemoveButton(<Image source={require('../assets/MinusIcon.png')} />);
} else {
var index = contextObject.workoutList.findIndex(y => y.exerciseID === eID);
if (index !== -1) {
contextObject.workoutList.splice(index, 1);
}
setAddRemove(false);
setAddRemoveButton(<Image source={require('../assets/PlusIcon.png')} />);
}
} |
JavaScript | function goToPastWorkout(pastWorkout, notes, workoutID) {
contextObject.pastWorkout = pastWorkout;
contextObject.pastNotes = notes;
contextObject.pastWorkoutID = workoutID;
navigation.navigate('PastWorkout');
} | function goToPastWorkout(pastWorkout, notes, workoutID) {
contextObject.pastWorkout = pastWorkout;
contextObject.pastNotes = notes;
contextObject.pastWorkoutID = workoutID;
navigation.navigate('PastWorkout');
} |
JavaScript | function monthDays() {
if (numDays === 28) {
return (
<View style={styles.scrollContainer} >
{daysButton(5)}
{daysButton(10)}
{daysButton(15)}
{daysButton(20)}
{daysButton(25)}
<View style={styles.dayButtonView}>
{dayButton(26)}
{dayButton(27)}
{dayButton(28)}
</View>
</View>
);
} else if (numDays === 29) {
return (
<View style={styles.scrollContainer} >
{daysButton(5)}
{daysButton(10)}
{daysButton(15)}
{daysButton(20)}
{daysButton(25)}
<View style={styles.dayButtonView}>
{dayButton(26)}
{dayButton(27)}
{dayButton(28)}
{dayButton(29)}
</View>
</View>
);
} else if (numDays === 31) {
return (
<View style={styles.scrollContainer} >
{daysButton(5)}
{daysButton(10)}
{daysButton(15)}
{daysButton(20)}
{daysButton(25)}
{daysButton(30)}
<View style={styles.dayButtonView}>
{dayButton(31)}
</View>
</View>
);
} else {
return (
<View style={styles.scrollContainer} >
{daysButton(5)}
{daysButton(10)}
{daysButton(15)}
{daysButton(20)}
{daysButton(25)}
{daysButton(30)}
</View>
);
}
} | function monthDays() {
if (numDays === 28) {
return (
<View style={styles.scrollContainer} >
{daysButton(5)}
{daysButton(10)}
{daysButton(15)}
{daysButton(20)}
{daysButton(25)}
<View style={styles.dayButtonView}>
{dayButton(26)}
{dayButton(27)}
{dayButton(28)}
</View>
</View>
);
} else if (numDays === 29) {
return (
<View style={styles.scrollContainer} >
{daysButton(5)}
{daysButton(10)}
{daysButton(15)}
{daysButton(20)}
{daysButton(25)}
<View style={styles.dayButtonView}>
{dayButton(26)}
{dayButton(27)}
{dayButton(28)}
{dayButton(29)}
</View>
</View>
);
} else if (numDays === 31) {
return (
<View style={styles.scrollContainer} >
{daysButton(5)}
{daysButton(10)}
{daysButton(15)}
{daysButton(20)}
{daysButton(25)}
{daysButton(30)}
<View style={styles.dayButtonView}>
{dayButton(31)}
</View>
</View>
);
} else {
return (
<View style={styles.scrollContainer} >
{daysButton(5)}
{daysButton(10)}
{daysButton(15)}
{daysButton(20)}
{daysButton(25)}
{daysButton(30)}
</View>
);
}
} |
JavaScript | function daysButton(day) {
return (
<View style={styles.dayButtonView}>
{dayButton(day - 4)}
{dayButton(day - 3)}
{dayButton(day - 2)}
{dayButton(day - 1)}
{dayButton(day)}
</View>
);
} | function daysButton(day) {
return (
<View style={styles.dayButtonView}>
{dayButton(day - 4)}
{dayButton(day - 3)}
{dayButton(day - 2)}
{dayButton(day - 1)}
{dayButton(day)}
</View>
);
} |
JavaScript | function dayButton(day) {
if (tempArray.includes(day)) {
return (
<TouchableOpacity style={styles.dayButton} disabled={false} onPress={() => getWorkout(day)}>
<Text style={styles.dayButtonTextEnabled}>{day}</Text>
</TouchableOpacity>
);
} else {
return (
<TouchableOpacity style={styles.dayButton} disabled={true}>
<Text style={styles.dayButtonTextDisabled}>{day}</Text>
</TouchableOpacity>
);
};
} | function dayButton(day) {
if (tempArray.includes(day)) {
return (
<TouchableOpacity style={styles.dayButton} disabled={false} onPress={() => getWorkout(day)}>
<Text style={styles.dayButtonTextEnabled}>{day}</Text>
</TouchableOpacity>
);
} else {
return (
<TouchableOpacity style={styles.dayButton} disabled={true}>
<Text style={styles.dayButtonTextDisabled}>{day}</Text>
</TouchableOpacity>
);
};
} |
JavaScript | function monthButton() {
return (
<View style={styles.monthButtonView}>
<TouchableOpacity style={styles.monthButton} onPress={() => goBack()}>
<Text style={styles.monthButtonText}>{tempMonth}</Text>
</TouchableOpacity>
</View>
);
} | function monthButton() {
return (
<View style={styles.monthButtonView}>
<TouchableOpacity style={styles.monthButton} onPress={() => goBack()}>
<Text style={styles.monthButtonText}>{tempMonth}</Text>
</TouchableOpacity>
</View>
);
} |
JavaScript | function loggedIn(myjwt, userType, name) {
contextObject.name = name;
contextObject.username = username;
contextObject.userType = userType;
contextObject.jwt = myjwt;
axios.get('http://68.172.33.6:9083/exercises/allRoots', { headers: { "Authorization": `Bearer ${myjwt}` } })
.then(response => navigation.navigate('Home', { branches: response.data, childrenType: 'branch', parentID: 'root', })).catch(e => console.log(e));
} | function loggedIn(myjwt, userType, name) {
contextObject.name = name;
contextObject.username = username;
contextObject.userType = userType;
contextObject.jwt = myjwt;
axios.get('http://68.172.33.6:9083/exercises/allRoots', { headers: { "Authorization": `Bearer ${myjwt}` } })
.then(response => navigation.navigate('Home', { branches: response.data, childrenType: 'branch', parentID: 'root', })).catch(e => console.log(e));
} |
JavaScript | function addMenu() {
if (route.params.childrenType === 'branch') {
return (
<View style={styles.branchModalView}>
<TouchableOpacity style={styles.modalButton} onPress={() => addBranchFunction()}>
<Text style={styles.modalButtonText}>Add Branch</Text>
</TouchableOpacity >
<TouchableOpacity style={styles.modalButton} onPress={() => setBranchModalVisible(false)}>
<Text style={styles.modalButtonText}>Cancel</Text>
</TouchableOpacity>
</View>
);
} else {
return (
<View style={styles.branchModalView}>
<TouchableOpacity style={styles.modalButton} onPress={() => addBranchFunction()}>
<Text style={styles.modalButtonText}>Add Branch</Text>
</TouchableOpacity >
<TouchableOpacity style={styles.modalButton} onPress={() => addExerciseFunction()}>
<Text style={styles.modalButtonText}>Add Exercise</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.modalButton} onPress={() => setBranchModalVisible(false)}>
<Text style={styles.modalButtonText}>Cancel</Text>
</TouchableOpacity>
</View>
);
}
} | function addMenu() {
if (route.params.childrenType === 'branch') {
return (
<View style={styles.branchModalView}>
<TouchableOpacity style={styles.modalButton} onPress={() => addBranchFunction()}>
<Text style={styles.modalButtonText}>Add Branch</Text>
</TouchableOpacity >
<TouchableOpacity style={styles.modalButton} onPress={() => setBranchModalVisible(false)}>
<Text style={styles.modalButtonText}>Cancel</Text>
</TouchableOpacity>
</View>
);
} else {
return (
<View style={styles.branchModalView}>
<TouchableOpacity style={styles.modalButton} onPress={() => addBranchFunction()}>
<Text style={styles.modalButtonText}>Add Branch</Text>
</TouchableOpacity >
<TouchableOpacity style={styles.modalButton} onPress={() => addExerciseFunction()}>
<Text style={styles.modalButtonText}>Add Exercise</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.modalButton} onPress={() => setBranchModalVisible(false)}>
<Text style={styles.modalButtonText}>Cancel</Text>
</TouchableOpacity>
</View>
);
}
} |
JavaScript | function CurrentExerciseName(exerciseName) {
return (
<View style={styles.titleContainer}>
<Text style={styles.currentExerciseText}>{exerciseName}</Text>
</View>
);
} | function CurrentExerciseName(exerciseName) {
return (
<View style={styles.titleContainer}>
<Text style={styles.currentExerciseText}>{exerciseName}</Text>
</View>
);
} |
JavaScript | function postExercise() {
var objectID = 'ObjectId(' + route.params.parentID + ')';
axios.post('http://68.172.33.6:9083/exercises/addExercise', {
exerciseName: exerciseName,
description: description,
parentNode: objectID,
base64: testImage.base64
}, { headers: { "Authorization": `Bearer ${contextObject.jwt}` } }).then(err => console.log(err))
axios.get('http://68.172.33.6:9083/exercises/descending/' + route.params.parentID, { headers: { "Authorization": `Bearer ${contextObject.jwt}` } })
.then(response => navigation.navigate('Exercise', { exercises: response.data, parentID: route.params.parentID, parentTitle: route.params.parentTitle })).catch(e => console.log(e));
} | function postExercise() {
var objectID = 'ObjectId(' + route.params.parentID + ')';
axios.post('http://68.172.33.6:9083/exercises/addExercise', {
exerciseName: exerciseName,
description: description,
parentNode: objectID,
base64: testImage.base64
}, { headers: { "Authorization": `Bearer ${contextObject.jwt}` } }).then(err => console.log(err))
axios.get('http://68.172.33.6:9083/exercises/descending/' + route.params.parentID, { headers: { "Authorization": `Bearer ${contextObject.jwt}` } })
.then(response => navigation.navigate('Exercise', { exercises: response.data, parentID: route.params.parentID, parentTitle: route.params.parentTitle })).catch(e => console.log(e));
} |
JavaScript | function goToWorkout() {
if (contextObject.workoutStarted === false) {
navigation.navigate('StartWorkout')
} else {
navigation.navigate('Workout')
}
} | function goToWorkout() {
if (contextObject.workoutStarted === false) {
navigation.navigate('StartWorkout')
} else {
navigation.navigate('Workout')
}
} |
JavaScript | function logout() {
setContextObject({
name: '',
username: '',
workoutList: [],
jwt: '',
userType: '',
workout: [],
notes: [],
workoutPosition: 0,
setPosition: 0,
pastWorkout: [],
pastNotes: [],
pastWorkoutPosition: 0,
workoutStarted: false
});
navigation.navigate('Login');
} | function logout() {
setContextObject({
name: '',
username: '',
workoutList: [],
jwt: '',
userType: '',
workout: [],
notes: [],
workoutPosition: 0,
setPosition: 0,
pastWorkout: [],
pastNotes: [],
pastWorkoutPosition: 0,
workoutStarted: false
});
navigation.navigate('Login');
} |
Subsets and Splits