language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function longestName(x) {
var max = (x[0].name.first + x[0].name.last).length;
var loo = 0;
for (var i = 1; i < x.length; i++) { // x.length-1
if (max < (x[i].name.first + x[i].name.last).length) {
max = (x[i].name.first + x[i].name.last).length;
loo = i;
}
}
return x[loo].name.first + " " + x[loo].name.last;
} | function longestName(x) {
var max = (x[0].name.first + x[0].name.last).length;
var loo = 0;
for (var i = 1; i < x.length; i++) { // x.length-1
if (max < (x[i].name.first + x[i].name.last).length) {
max = (x[i].name.first + x[i].name.last).length;
loo = i;
}
}
return x[loo].name.first + " " + x[loo].name.last;
} |
JavaScript | function _onCloseHelper(e) {
e.preventDefault();
e.stopPropagation();
if ($(e.currentTarget).parents(".selecter").length === 0) {
_onClose(e);
}
} | function _onCloseHelper(e) {
e.preventDefault();
e.stopPropagation();
if ($(e.currentTarget).parents(".selecter").length === 0) {
_onClose(e);
}
} |
JavaScript | function handleResolved(resolvedValues) {
const saved = [];
const errors = [];
resolvedValues.forEach(value => {
if (value.err) {
errors.push(value);
} else {
saved.push(value[0]);
}
});
if (saved.length) {
logger.info(chalk.green('\n✓ Reports saved:'));
logger.info(
saved.map(savedFile => `${chalk.underline(savedFile)}`).join('\n')
);
}
if (errors.length) {
logger.info(chalk.red('\n✘ Some files could not be processed:'));
logger.info(
errors
.map(e => `${chalk.underline(e.filename)}\n${chalk.dim(e.err)}`)
.join('\n\n')
);
process.exitCode = 1;
}
if (!validFiles && !errors.length) {
logger.info(chalk.yellow('\nDid not find any JSON files to process.'));
process.exitCode = 1;
}
return resolvedValues;
} | function handleResolved(resolvedValues) {
const saved = [];
const errors = [];
resolvedValues.forEach(value => {
if (value.err) {
errors.push(value);
} else {
saved.push(value[0]);
}
});
if (saved.length) {
logger.info(chalk.green('\n✓ Reports saved:'));
logger.info(
saved.map(savedFile => `${chalk.underline(savedFile)}`).join('\n')
);
}
if (errors.length) {
logger.info(chalk.red('\n✘ Some files could not be processed:'));
logger.info(
errors
.map(e => `${chalk.underline(e.filename)}\n${chalk.dim(e.err)}`)
.join('\n\n')
);
process.exitCode = 1;
}
if (!validFiles && !errors.length) {
logger.info(chalk.yellow('\nDid not find any JSON files to process.'));
process.exitCode = 1;
}
return resolvedValues;
} |
JavaScript | function processArgs(args, files = []) {
return args.reduce((acc, arg) => {
let stats;
try {
stats = fs.statSync(arg);
} catch (err) {
// Do nothing
}
// If argument is a directory, process the files inside
if (stats && stats.isDirectory()) {
return processArgs(
fs.readdirSync(arg).map(file => path.join(arg, file)),
files
);
}
// If `statSync` failed, validating will handle the error
// If the argument is a file, check if its a JSON file before validating
if (!stats || JsonFileRegex.test(arg)) {
acc.push(validateFile(arg));
}
return acc;
}, files);
} | function processArgs(args, files = []) {
return args.reduce((acc, arg) => {
let stats;
try {
stats = fs.statSync(arg);
} catch (err) {
// Do nothing
}
// If argument is a directory, process the files inside
if (stats && stats.isDirectory()) {
return processArgs(
fs.readdirSync(arg).map(file => path.join(arg, file)),
files
);
}
// If `statSync` failed, validating will handle the error
// If the argument is a file, check if its a JSON file before validating
if (!stats || JsonFileRegex.test(arg)) {
acc.push(validateFile(arg));
}
return acc;
}, files);
} |
JavaScript | function marge(args) {
// Reset valid files count
validFiles = 0;
const newArgs = Object.assign({}, args);
// Get the array of JSON files to process
const files = processArgs(args._);
// When there are multiple valid files OR the timestamp option is set
// we must force `overwrite` to `false` to ensure all reports are created
/* istanbul ignore else */
if (validFiles > 1 || args.timestamp !== false) {
newArgs.overwrite = false;
}
const promises = files.map(file => {
// Files with errors we just resolve
if (file.err) {
return Promise.resolve(file);
}
// Valid files get created but first we need to pass correct filename option
// Default value is name of file
// If a filename option was provided, all files get that name
const reportFilename = getReportFilename(file, newArgs);
return report.create(
file.data,
Object.assign({}, newArgs, { reportFilename })
);
});
return Promise.all(promises)
.then(handleResolved)
.catch(handleError);
} | function marge(args) {
// Reset valid files count
validFiles = 0;
const newArgs = Object.assign({}, args);
// Get the array of JSON files to process
const files = processArgs(args._);
// When there are multiple valid files OR the timestamp option is set
// we must force `overwrite` to `false` to ensure all reports are created
/* istanbul ignore else */
if (validFiles > 1 || args.timestamp !== false) {
newArgs.overwrite = false;
}
const promises = files.map(file => {
// Files with errors we just resolve
if (file.err) {
return Promise.resolve(file);
}
// Valid files get created but first we need to pass correct filename option
// Default value is name of file
// If a filename option was provided, all files get that name
const reportFilename = getReportFilename(file, newArgs);
return report.create(
file.data,
Object.assign({}, newArgs, { reportFilename })
);
});
return Promise.all(promises)
.then(handleResolved)
.catch(handleError);
} |
JavaScript | function makeReport(suites, mochawesomeOpts = {}, margeOpts = {}) {
const rootSuite = Array.isArray(suites)
? makeSuite(parseSuite(suites, true))
: suites;
return {
stats: stats(rootSuite),
results: [rootSuite],
meta: {
mocha: {
version: fakeVersion(),
},
mochawesome: {
options: mochawesomeOpts,
version: fakeVersion(),
},
marge: {
options: margeOpts,
version: fakeVersion(),
},
},
};
} | function makeReport(suites, mochawesomeOpts = {}, margeOpts = {}) {
const rootSuite = Array.isArray(suites)
? makeSuite(parseSuite(suites, true))
: suites;
return {
stats: stats(rootSuite),
results: [rootSuite],
meta: {
mocha: {
version: fakeVersion(),
},
mochawesome: {
options: mochawesomeOpts,
version: fakeVersion(),
},
marge: {
options: margeOpts,
version: fakeVersion(),
},
},
};
} |
JavaScript | function assignVal(obj, prop, userVal, defaultVal) {
const val = userVal !== undefined ? userVal : defaultVal;
if (val !== undefined) {
obj[prop] = val; // eslint-disable-line
}
} | function assignVal(obj, prop, userVal, defaultVal) {
const val = userVal !== undefined ? userVal : defaultVal;
if (val !== undefined) {
obj[prop] = val; // eslint-disable-line
}
} |
JavaScript | async init() {
for (let i = 0; i < this.config.minAvailable; i++) {
const newConn = await this._createConnection();
this.free_connections.push(newConn);
}
this.state = Pool.STATE_RUNNING;
} | async init() {
for (let i = 0; i < this.config.minAvailable; i++) {
const newConn = await this._createConnection();
this.free_connections.push(newConn);
}
this.state = Pool.STATE_RUNNING;
} |
JavaScript | _connectionBelongs(connection) {
if (this.all_connections[connection._id] === undefined) {
return false;
}
if (this.all_connections[connection._id].connection === undefined) {
return false;
}
return connection === this.all_connections[connection._id].connection;
} | _connectionBelongs(connection) {
if (this.all_connections[connection._id] === undefined) {
return false;
}
if (this.all_connections[connection._id].connection === undefined) {
return false;
}
return connection === this.all_connections[connection._id].connection;
} |
JavaScript | async _livelinessCheck() {
if (this.livelinessStatus === Pool.LIVELINESS_RUNNING) {
return;
}
if (this.free_connections.length === 0) {
return;
}
this.livelinessStatus = Pool.LIVELINESS_RUNNING;
const checked = {};
while (this.free_connections.length > 0) {
let toCheck = this.free_connections.shift();
this.all_connections[toCheck._id].inUse = true;
if (checked[toCheck._id] === true) {
await this.releaseConnection(toCheck);
return;
}
checked[toCheck._id] = true;
await this.releaseConnection(toCheck);
}
this.livelinessStatus = Pool.LIVELINESS_NOT_RUNNING;
} | async _livelinessCheck() {
if (this.livelinessStatus === Pool.LIVELINESS_RUNNING) {
return;
}
if (this.free_connections.length === 0) {
return;
}
this.livelinessStatus = Pool.LIVELINESS_RUNNING;
const checked = {};
while (this.free_connections.length > 0) {
let toCheck = this.free_connections.shift();
this.all_connections[toCheck._id].inUse = true;
if (checked[toCheck._id] === true) {
await this.releaseConnection(toCheck);
return;
}
checked[toCheck._id] = true;
await this.releaseConnection(toCheck);
}
this.livelinessStatus = Pool.LIVELINESS_NOT_RUNNING;
} |
JavaScript | function main() {
var atten = [];
// for (var x = 1; x <= 5; x++) {
while(checkIn !== 'q'){
var checkIn = prompt('Is a teacher, student, or parent checking in?');
switch (checkIn) {
case "teacher":
case "Teacher":
atten.push("teacher");
console.log(atten);
// console.log("teacher");
break;
case "student":
case "Student":
atten.push("student");
console.log(atten);
// console.log("student");
break;
case "parent":
case "Parent":
atten.push("parent");
console.log(atten);
// console.log("parent");
break;
default:
if(checkIn === 'q'){
console.log("Entries registered.");
}
else{
console.log('Sorry, not a valid entry.');
}
}
}
} | function main() {
var atten = [];
// for (var x = 1; x <= 5; x++) {
while(checkIn !== 'q'){
var checkIn = prompt('Is a teacher, student, or parent checking in?');
switch (checkIn) {
case "teacher":
case "Teacher":
atten.push("teacher");
console.log(atten);
// console.log("teacher");
break;
case "student":
case "Student":
atten.push("student");
console.log(atten);
// console.log("student");
break;
case "parent":
case "Parent":
atten.push("parent");
console.log(atten);
// console.log("parent");
break;
default:
if(checkIn === 'q'){
console.log("Entries registered.");
}
else{
console.log('Sorry, not a valid entry.');
}
}
}
} |
JavaScript | function main() {
var num = parseInt(prompt('Enter a number'));
switch(num){
case 1:
console.log(1);
break;
case 2:
console.log(2);
break;
case 3:
console.log(3);
break;
case 4:
console.log(4);
break;
case 5:
console.log(5);
break;
default:
console.log('ERROR');
}
} | function main() {
var num = parseInt(prompt('Enter a number'));
switch(num){
case 1:
console.log(1);
break;
case 2:
console.log(2);
break;
case 3:
console.log(3);
break;
case 4:
console.log(4);
break;
case 5:
console.log(5);
break;
default:
console.log('ERROR');
}
} |
JavaScript | async function callReddit(func, data, client) {
client = client || getR()
try {
return await client[func](data)
} catch (exc) {
utils.log(`${exc.name} - Failed to execute ${func} with data:`, data)
}
} | async function callReddit(func, data, client) {
client = client || getR()
try {
return await client[func](data)
} catch (exc) {
utils.log(`${exc.name} - Failed to execute ${func} with data:`, data)
}
} |
JavaScript | function formatMessage(txt) {
return txt +
'\n\n\n\n' +
'[Deposit](https://www.reddit.com/user/stellar_bot/comments/7o2ex9/deposit/) | ' +
`[Withdraw](https://np.reddit.com/message/compose/?to=${process.env.REDDIT_USER}&subject=Withdraw&message=Amount%20XLM%0Aaddress%20here) | ` +
`[Balance](https://np.reddit.com/message/compose/?to=${process.env.REDDIT_USER}&subject=Balance&message=Tell%20me%20my%20XLM%20Balance!) | ` +
'[Help](https://www.reddit.com/user/stellar_bot/comments/7o2gnd/help/) | ' +
'[Donate](https://www.reddit.com/user/stellar_bot/comments/7o2ffl/donate/) | ' +
'[About Stellar](https://www.stellar.org/)'
} | function formatMessage(txt) {
return txt +
'\n\n\n\n' +
'[Deposit](https://www.reddit.com/user/stellar_bot/comments/7o2ex9/deposit/) | ' +
`[Withdraw](https://np.reddit.com/message/compose/?to=${process.env.REDDIT_USER}&subject=Withdraw&message=Amount%20XLM%0Aaddress%20here) | ` +
`[Balance](https://np.reddit.com/message/compose/?to=${process.env.REDDIT_USER}&subject=Balance&message=Tell%20me%20my%20XLM%20Balance!) | ` +
'[Help](https://www.reddit.com/user/stellar_bot/comments/7o2gnd/help/) | ' +
'[Donate](https://www.reddit.com/user/stellar_bot/comments/7o2ffl/donate/) | ' +
'[About Stellar](https://www.stellar.org/)'
} |
JavaScript | async pollComments (subreddit, lastBatch) {
lastBatch = lastBatch || []
const comments = await callReddit('getNewComments', subreddit)
if (comments === undefined) {
return this.pollComments(subreddit, lastBatch)
}
comments.filter((comment) => {
return lastBatch.every(batch => batch.id != comment.id)
}).forEach(async (comment) => {
const tipAmount = this.extractTipAmount(comment.body)
if (tipAmount) {
const targetComment = await callReddit('getComment', comment.parent_id)
if (targetComment) {
this.receivePotentialTip({
adapter: this.name,
sourceId: comment.author.name,
targetId: await targetComment.author.name,
amount: tipAmount,
original: comment,
hash: comment.id
})
}
}
})
lastBatch = comments
await utils.sleep((60 / (60 / this.subreddits.length)) * 1000)
this.pollComments(subreddit, lastBatch)
} | async pollComments (subreddit, lastBatch) {
lastBatch = lastBatch || []
const comments = await callReddit('getNewComments', subreddit)
if (comments === undefined) {
return this.pollComments(subreddit, lastBatch)
}
comments.filter((comment) => {
return lastBatch.every(batch => batch.id != comment.id)
}).forEach(async (comment) => {
const tipAmount = this.extractTipAmount(comment.body)
if (tipAmount) {
const targetComment = await callReddit('getComment', comment.parent_id)
if (targetComment) {
this.receivePotentialTip({
adapter: this.name,
sourceId: comment.author.name,
targetId: await targetComment.author.name,
amount: tipAmount,
original: comment,
hash: comment.id
})
}
}
})
lastBatch = comments
await utils.sleep((60 / (60 / this.subreddits.length)) * 1000)
this.pollComments(subreddit, lastBatch)
} |
JavaScript | async pollMessages () {
const messages = await callReddit('getUnreadMessages') || []
let processedMessages = []
await messages
.filter(m => ['Withdraw', 'Balance', 'memoId'].indexOf(m.subject) > -1 && !m.was_comment)
.forEach(async (m) => {
// Check the balance of the user
if (m.subject === 'Balance') {
const balance = await this.requestBalance(this.name, m.author.name)
await callReddit('composeMessage', {
to: m.author.name,
subject: 'XLM Balance',
text: formatMessage(`Your current balance is **${balance} XLM**.`)
})
await callReddit('markMessagesAsRead', [m])
}
if (m.subject === 'Withdraw') {
const extract = this.extractWithdrawal(m.body_html)
if (!extract) {
utils.log(`XLM withdrawal failed - unparsable message from ${m.author.name}.`)
await callReddit('composeMessage', {
to: m.author.name,
subject: 'XLM Withdrawal failed',
text: formatMessage(`I could not withdraw. Please make sure that the first line of the body is withdrawal amount and the second line your public key.`)
})
} else {
await callReddit('markMessagesAsRead', [m])
this.receiveWithdrawalRequest({
adapter: this.name,
uniqueId: m.author.name,
amount: extract.amount,
address: extract.address,
hash: m.id
})
}
}
if (m.subject === 'memoId') {
const options = await this.setAccountOptions(this.name, m.author.name, {refreshMemoId: true})
const newMemoId = options.refreshMemoId
await callReddit('composeMessage', {
to: m.author.name,
subject: 'memoId refreshed',
text: formatMessage(`Your new memoId is **${newMemoId}**. Please use it for subsequent deposits.`)
})
}
await callReddit('markMessagesAsRead', [m])
})
await utils.sleep(2000)
this.pollMessages()
} | async pollMessages () {
const messages = await callReddit('getUnreadMessages') || []
let processedMessages = []
await messages
.filter(m => ['Withdraw', 'Balance', 'memoId'].indexOf(m.subject) > -1 && !m.was_comment)
.forEach(async (m) => {
// Check the balance of the user
if (m.subject === 'Balance') {
const balance = await this.requestBalance(this.name, m.author.name)
await callReddit('composeMessage', {
to: m.author.name,
subject: 'XLM Balance',
text: formatMessage(`Your current balance is **${balance} XLM**.`)
})
await callReddit('markMessagesAsRead', [m])
}
if (m.subject === 'Withdraw') {
const extract = this.extractWithdrawal(m.body_html)
if (!extract) {
utils.log(`XLM withdrawal failed - unparsable message from ${m.author.name}.`)
await callReddit('composeMessage', {
to: m.author.name,
subject: 'XLM Withdrawal failed',
text: formatMessage(`I could not withdraw. Please make sure that the first line of the body is withdrawal amount and the second line your public key.`)
})
} else {
await callReddit('markMessagesAsRead', [m])
this.receiveWithdrawalRequest({
adapter: this.name,
uniqueId: m.author.name,
amount: extract.amount,
address: extract.address,
hash: m.id
})
}
}
if (m.subject === 'memoId') {
const options = await this.setAccountOptions(this.name, m.author.name, {refreshMemoId: true})
const newMemoId = options.refreshMemoId
await callReddit('composeMessage', {
to: m.author.name,
subject: 'memoId refreshed',
text: formatMessage(`Your new memoId is **${newMemoId}**. Please use it for subsequent deposits.`)
})
}
await callReddit('markMessagesAsRead', [m])
})
await utils.sleep(2000)
this.pollMessages()
} |
JavaScript | extractWithdrawal (body) {
const parts = body.slice(body.indexOf('<p>') + 3, body.indexOf('</p>')).split('\n')
if (parts.length === 2) {
const amount = parts[0].match(/([\d\.]*)/)[0]
const address = parts[1]
if (amount && address) {
return {
amount, address
}
}
return undefined
}
} | extractWithdrawal (body) {
const parts = body.slice(body.indexOf('<p>') + 3, body.indexOf('</p>')).split('\n')
if (parts.length === 2) {
const amount = parts[0].match(/([\d\.]*)/)[0]
const address = parts[1]
if (amount && address) {
return {
amount, address
}
}
return undefined
}
} |
JavaScript | function onError(err) {
if (!called) {
called = true;
self.logger.fatal('cannot bootstrap hyperbahn', {
err: err
});
cb(err);
}
} | function onError(err) {
if (!called) {
called = true;
self.logger.fatal('cannot bootstrap hyperbahn', {
err: err
});
cb(err);
}
} |
JavaScript | aly(val) {
return mec.aly[val.show]
// If it does not exist, take a normalized template
|| { get scl() { return 1 }, type: 'num', name: val.show, unit: val.unit || '' };
} | aly(val) {
return mec.aly[val.show]
// If it does not exist, take a normalized template
|| { get scl() { return 1 }, type: 'num', name: val.show, unit: val.unit || '' };
} |
JavaScript | preview() {
let previewMode = false, tmax = 0;
for (const view of this.views) {
if (view.mode === 'preview') {
tmax = view.t0 + view.Dt;
view.reset(previewMode = true);
}
}
if (previewMode) {
this.reset();
this.state.preview = true;
this.timer.dt = 1/30;
for (this.timer.t = 0; this.timer.t <= tmax; this.timer.t += this.timer.dt) {
this.pre().itr().post();
for (const view of this.views)
if (view.preview)
view.preview();
}
this.timer.dt = 1/60;
this.state.preview = false;
this.reset();
}
return this;
} | preview() {
let previewMode = false, tmax = 0;
for (const view of this.views) {
if (view.mode === 'preview') {
tmax = view.t0 + view.Dt;
view.reset(previewMode = true);
}
}
if (previewMode) {
this.reset();
this.state.preview = true;
this.timer.dt = 1/30;
for (this.timer.t = 0; this.timer.t <= tmax; this.timer.t += this.timer.dt) {
this.pre().itr().post();
for (const view of this.views)
if (view.preview)
view.preview();
}
this.timer.dt = 1/60;
this.state.preview = false;
this.reset();
}
return this;
} |
JavaScript | function model(key, value){
if( key === null || key === undefined ){
throw "Invalid key, must be string, object or array";
}
var dt = (new Date()).toString();
return {
key: key,
value: value,
created: dt,
modified: dt
};
}//model | function model(key, value){
if( key === null || key === undefined ){
throw "Invalid key, must be string, object or array";
}
var dt = (new Date()).toString();
return {
key: key,
value: value,
created: dt,
modified: dt
};
}//model |
JavaScript | function vault(key, memOnly){
var key = key,
storage = !!memOnly ? localStorage : sessionStorage,
items = load(key);
/**
* fetch item from localStorage or create localStorage item
* @param {String} key to load
*/
function load(key){
var loaded = storage.getItem(key),
ret = [];
if(!loaded){
loaded = JSON.stringify(ret);
}
var parsed = JSON.parse(loaded);
for(var v in parsed){
ret.push(new model(parsed[v]));
}
return ret;
}//load
/**
* put items in storage
*/
function store(){
items.length > 0 ?
storage.setItem(key, JSON.stringify(items)) :
storage.removeItem(key);
}//store
/**
* find the model for this key
* @param {Any} key any JSON.stringify string, object, array value
*/
function findModel(key){
for(var v in items){
if(key === items[v].key){
return items[v];
}
}
return false;
}//find
/**
* return all stored keys
* @return {Array}
*/
function keys(){
ret = [];
for(var v in items){
ret.push(items[v].key);
}
return ret;
}//key
/**
* store key value pair
* @param {Any} key to store
* @param {Any} value to store
*
*/
function set(key, value){
var m = findModel(key);
if(!m){
m = new model(key, value);
items.push(m);
}else{
m.data = value;
m.modified = new Date();
}
store();
}//set
/**
* get data for this key
* @param {Any} key to get value
*/
function get(key){
var m = findModel(key);
return m ? m.value : m;
}
/**
* remove this key, return value for key removed
* @param {Any} key to remove
* @return {Any}
*/
function remove(key){
var m = false;
for(var v in items){
if(items[v].key === key){
m = items[v].value;
items.splice(v, 1);
}
}
store();
return m;
}
/**
* fetch items modified since date provided
* @param {Date} dt date to fetch newer items
* @return {Array} array of objects {key: key, value: value}
*/
function since(dt){
var ret = [];
for(var v in items){
if(dt < new Date(items[v].created)){
ret.push({
key: items[v].key,
value: items[v].value
});
}
}
return ret;
}
return {
keys: keys,
set: set,
get: get,
remove: remove,
since: since
};
}//vault | function vault(key, memOnly){
var key = key,
storage = !!memOnly ? localStorage : sessionStorage,
items = load(key);
/**
* fetch item from localStorage or create localStorage item
* @param {String} key to load
*/
function load(key){
var loaded = storage.getItem(key),
ret = [];
if(!loaded){
loaded = JSON.stringify(ret);
}
var parsed = JSON.parse(loaded);
for(var v in parsed){
ret.push(new model(parsed[v]));
}
return ret;
}//load
/**
* put items in storage
*/
function store(){
items.length > 0 ?
storage.setItem(key, JSON.stringify(items)) :
storage.removeItem(key);
}//store
/**
* find the model for this key
* @param {Any} key any JSON.stringify string, object, array value
*/
function findModel(key){
for(var v in items){
if(key === items[v].key){
return items[v];
}
}
return false;
}//find
/**
* return all stored keys
* @return {Array}
*/
function keys(){
ret = [];
for(var v in items){
ret.push(items[v].key);
}
return ret;
}//key
/**
* store key value pair
* @param {Any} key to store
* @param {Any} value to store
*
*/
function set(key, value){
var m = findModel(key);
if(!m){
m = new model(key, value);
items.push(m);
}else{
m.data = value;
m.modified = new Date();
}
store();
}//set
/**
* get data for this key
* @param {Any} key to get value
*/
function get(key){
var m = findModel(key);
return m ? m.value : m;
}
/**
* remove this key, return value for key removed
* @param {Any} key to remove
* @return {Any}
*/
function remove(key){
var m = false;
for(var v in items){
if(items[v].key === key){
m = items[v].value;
items.splice(v, 1);
}
}
store();
return m;
}
/**
* fetch items modified since date provided
* @param {Date} dt date to fetch newer items
* @return {Array} array of objects {key: key, value: value}
*/
function since(dt){
var ret = [];
for(var v in items){
if(dt < new Date(items[v].created)){
ret.push({
key: items[v].key,
value: items[v].value
});
}
}
return ret;
}
return {
keys: keys,
set: set,
get: get,
remove: remove,
since: since
};
}//vault |
JavaScript | function load(key){
var loaded = storage.getItem(key),
ret = [];
if(!loaded){
loaded = JSON.stringify(ret);
}
var parsed = JSON.parse(loaded);
for(var v in parsed){
ret.push(new model(parsed[v]));
}
return ret;
}//load | function load(key){
var loaded = storage.getItem(key),
ret = [];
if(!loaded){
loaded = JSON.stringify(ret);
}
var parsed = JSON.parse(loaded);
for(var v in parsed){
ret.push(new model(parsed[v]));
}
return ret;
}//load |
JavaScript | function findModel(key){
for(var v in items){
if(key === items[v].key){
return items[v];
}
}
return false;
}//find | function findModel(key){
for(var v in items){
if(key === items[v].key){
return items[v];
}
}
return false;
}//find |
JavaScript | function handleCommonErrors(error) {
let message = (error.message || String(error)).toLowerCase();
if (message.includes("eaccess")) {
message = ERROR_MESSAGES.SCRIPT_ACCESS_ERROR;
} else if (message.includes("unsupported key format")) {
message = ERROR_MESSAGES.INVALID_PRIVATE_KEY;
} else if (message.includes("configured authentication methods failed")) {
message = ERROR_MESSAGES.INCORRECT_PRIVATE_KEY;
} else if (message.includes("econnrefused")) {
message = ERROR_MESSAGES.CONNECTION_REFUSED;
}
throw new Error(message);
} | function handleCommonErrors(error) {
let message = (error.message || String(error)).toLowerCase();
if (message.includes("eaccess")) {
message = ERROR_MESSAGES.SCRIPT_ACCESS_ERROR;
} else if (message.includes("unsupported key format")) {
message = ERROR_MESSAGES.INVALID_PRIVATE_KEY;
} else if (message.includes("configured authentication methods failed")) {
message = ERROR_MESSAGES.INCORRECT_PRIVATE_KEY;
} else if (message.includes("econnrefused")) {
message = ERROR_MESSAGES.CONNECTION_REFUSED;
}
throw new Error(message);
} |
JavaScript | function parseXML(xml) {
if ( window.DOMParser == undefined && window.ActiveXObject ) {
DOMParser = function() { };
DOMParser.prototype.parseFromString = function( xmlString ) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML( xmlString );
return doc;
};
}
try {
var xmlDoc = ( new DOMParser() ).parseFromString( xml, 'text/xml' );
if ( $.isXMLDoc( xmlDoc ) ) {
var err = $('parsererror', xmlDoc);
if ( err.length == 1 ) {
throw('Error: ' + $(xmlDoc).text() );
}
} else {
throw('Unable to parse XML');
}
return xmlDoc;
} catch( e ) {
var msg = ( e.name == undefined ? e : e.name + ': ' + e.message );
$(document).trigger('xmlParseError', [ msg ]);
return undefined;
}
} | function parseXML(xml) {
if ( window.DOMParser == undefined && window.ActiveXObject ) {
DOMParser = function() { };
DOMParser.prototype.parseFromString = function( xmlString ) {
var doc = new ActiveXObject('Microsoft.XMLDOM');
doc.async = 'false';
doc.loadXML( xmlString );
return doc;
};
}
try {
var xmlDoc = ( new DOMParser() ).parseFromString( xml, 'text/xml' );
if ( $.isXMLDoc( xmlDoc ) ) {
var err = $('parsererror', xmlDoc);
if ( err.length == 1 ) {
throw('Error: ' + $(xmlDoc).text() );
}
} else {
throw('Unable to parse XML');
}
return xmlDoc;
} catch( e ) {
var msg = ( e.name == undefined ? e : e.name + ': ' + e.message );
$(document).trigger('xmlParseError', [ msg ]);
return undefined;
}
} |
JavaScript | function isMockDataEqual( mock, live ) {
var identical = true;
// Test for situations where the data is a querystring (not an object)
if (typeof live === 'string') {
// Querystring may be a regex
return $.isFunction( mock.test ) ? mock.test(live) : mock == live;
}
$.each(mock, function(k) {
if ( live[k] === undefined ) {
identical = false;
return identical;
} else {
if ( typeof live[k] === 'object' && live[k] !== null ) {
if ( identical && $.isArray( live[k] ) ) {
identical = $.isArray( mock[k] ) && live[k].length === mock[k].length;
}
identical = identical && isMockDataEqual(mock[k], live[k]);
} else {
if ( mock[k] && $.isFunction( mock[k].test ) ) {
identical = identical && mock[k].test(live[k]);
} else {
identical = identical && ( mock[k] == live[k] );
}
}
}
});
return identical;
} | function isMockDataEqual( mock, live ) {
var identical = true;
// Test for situations where the data is a querystring (not an object)
if (typeof live === 'string') {
// Querystring may be a regex
return $.isFunction( mock.test ) ? mock.test(live) : mock == live;
}
$.each(mock, function(k) {
if ( live[k] === undefined ) {
identical = false;
return identical;
} else {
if ( typeof live[k] === 'object' && live[k] !== null ) {
if ( identical && $.isArray( live[k] ) ) {
identical = $.isArray( mock[k] ) && live[k].length === mock[k].length;
}
identical = identical && isMockDataEqual(mock[k], live[k]);
} else {
if ( mock[k] && $.isFunction( mock[k].test ) ) {
identical = identical && mock[k].test(live[k]);
} else {
identical = identical && ( mock[k] == live[k] );
}
}
}
});
return identical;
} |
JavaScript | function _xhrSend(mockHandler, requestSettings, origSettings) {
// This is a substitute for < 1.4 which lacks $.proxy
var process = (function(that) {
return function() {
return (function() {
var onReady;
// The request has returned
this.status = mockHandler.status;
this.statusText = mockHandler.statusText;
this.readyState = 4;
// We have an executable function, call it to give
// the mock handler a chance to update it's data
if ( $.isFunction(mockHandler.response) ) {
mockHandler.response(origSettings);
}
// Copy over our mock to our xhr object before passing control back to
// jQuery's onreadystatechange callback
if ( requestSettings.dataType == 'json' && ( typeof mockHandler.responseText == 'object' ) ) {
this.responseText = JSON.stringify(mockHandler.responseText);
} else if ( requestSettings.dataType == 'xml' ) {
if ( typeof mockHandler.responseXML == 'string' ) {
this.responseXML = parseXML(mockHandler.responseXML);
//in jQuery 1.9.1+, responseXML is processed differently and relies on responseText
this.responseText = mockHandler.responseXML;
} else {
this.responseXML = mockHandler.responseXML;
}
} else {
this.responseText = mockHandler.responseText;
}
if( typeof mockHandler.status == 'number' || typeof mockHandler.status == 'string' ) {
this.status = mockHandler.status;
}
if( typeof mockHandler.statusText === "string") {
this.statusText = mockHandler.statusText;
}
// jQuery 2.0 renamed onreadystatechange to onload
onReady = this.onreadystatechange || this.onload;
// jQuery < 1.4 doesn't have onreadystate change for xhr
if ( $.isFunction( onReady ) ) {
if( mockHandler.isTimeout) {
this.status = -1;
}
onReady.call( this, mockHandler.isTimeout ? 'timeout' : undefined );
} else if ( mockHandler.isTimeout ) {
// Fix for 1.3.2 timeout to keep success from firing.
this.status = -1;
}
}).apply(that);
};
})(this);
if ( mockHandler.proxy ) {
// We're proxying this request and loading in an external file instead
_ajax({
global: false,
url: mockHandler.proxy,
type: mockHandler.proxyType,
data: mockHandler.data,
dataType: requestSettings.dataType === "script" ? "text/plain" : requestSettings.dataType,
complete: function(xhr) {
mockHandler.responseXML = xhr.responseXML;
mockHandler.responseText = xhr.responseText;
// Don't override the handler status/statusText if it's specified by the config
if (isDefaultSetting(mockHandler, 'status')) {
mockHandler.status = xhr.status;
}
if (isDefaultSetting(mockHandler, 'statusText')) {
mockHandler.statusText = xhr.statusText;
}
this.responseTimer = setTimeout(process, mockHandler.responseTime || 0);
}
});
} else {
// type == 'POST' || 'GET' || 'DELETE'
if ( requestSettings.async === false ) {
// TODO: Blocking delay
process();
} else {
this.responseTimer = setTimeout(process, mockHandler.responseTime || 50);
}
}
} | function _xhrSend(mockHandler, requestSettings, origSettings) {
// This is a substitute for < 1.4 which lacks $.proxy
var process = (function(that) {
return function() {
return (function() {
var onReady;
// The request has returned
this.status = mockHandler.status;
this.statusText = mockHandler.statusText;
this.readyState = 4;
// We have an executable function, call it to give
// the mock handler a chance to update it's data
if ( $.isFunction(mockHandler.response) ) {
mockHandler.response(origSettings);
}
// Copy over our mock to our xhr object before passing control back to
// jQuery's onreadystatechange callback
if ( requestSettings.dataType == 'json' && ( typeof mockHandler.responseText == 'object' ) ) {
this.responseText = JSON.stringify(mockHandler.responseText);
} else if ( requestSettings.dataType == 'xml' ) {
if ( typeof mockHandler.responseXML == 'string' ) {
this.responseXML = parseXML(mockHandler.responseXML);
//in jQuery 1.9.1+, responseXML is processed differently and relies on responseText
this.responseText = mockHandler.responseXML;
} else {
this.responseXML = mockHandler.responseXML;
}
} else {
this.responseText = mockHandler.responseText;
}
if( typeof mockHandler.status == 'number' || typeof mockHandler.status == 'string' ) {
this.status = mockHandler.status;
}
if( typeof mockHandler.statusText === "string") {
this.statusText = mockHandler.statusText;
}
// jQuery 2.0 renamed onreadystatechange to onload
onReady = this.onreadystatechange || this.onload;
// jQuery < 1.4 doesn't have onreadystate change for xhr
if ( $.isFunction( onReady ) ) {
if( mockHandler.isTimeout) {
this.status = -1;
}
onReady.call( this, mockHandler.isTimeout ? 'timeout' : undefined );
} else if ( mockHandler.isTimeout ) {
// Fix for 1.3.2 timeout to keep success from firing.
this.status = -1;
}
}).apply(that);
};
})(this);
if ( mockHandler.proxy ) {
// We're proxying this request and loading in an external file instead
_ajax({
global: false,
url: mockHandler.proxy,
type: mockHandler.proxyType,
data: mockHandler.data,
dataType: requestSettings.dataType === "script" ? "text/plain" : requestSettings.dataType,
complete: function(xhr) {
mockHandler.responseXML = xhr.responseXML;
mockHandler.responseText = xhr.responseText;
// Don't override the handler status/statusText if it's specified by the config
if (isDefaultSetting(mockHandler, 'status')) {
mockHandler.status = xhr.status;
}
if (isDefaultSetting(mockHandler, 'statusText')) {
mockHandler.statusText = xhr.statusText;
}
this.responseTimer = setTimeout(process, mockHandler.responseTime || 0);
}
});
} else {
// type == 'POST' || 'GET' || 'DELETE'
if ( requestSettings.async === false ) {
// TODO: Blocking delay
process();
} else {
this.responseTimer = setTimeout(process, mockHandler.responseTime || 50);
}
}
} |
JavaScript | function processJsonpMock( requestSettings, mockHandler, origSettings ) {
// Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
// because there isn't an easy hook for the cross domain script tag of jsonp
processJsonpUrl( requestSettings );
requestSettings.dataType = "json";
if(requestSettings.data && CALLBACK_REGEX.test(requestSettings.data) || CALLBACK_REGEX.test(requestSettings.url)) {
createJsonpCallback(requestSettings, mockHandler, origSettings);
// We need to make sure
// that a JSONP style response is executed properly
var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
parts = rurl.exec( requestSettings.url ),
remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
requestSettings.dataType = "script";
if(requestSettings.type.toUpperCase() === "GET" && remote ) {
var newMockReturn = processJsonpRequest( requestSettings, mockHandler, origSettings );
// Check if we are supposed to return a Deferred back to the mock call, or just
// signal success
if(newMockReturn) {
return newMockReturn;
} else {
return true;
}
}
}
return null;
} | function processJsonpMock( requestSettings, mockHandler, origSettings ) {
// Handle JSONP Parameter Callbacks, we need to replicate some of the jQuery core here
// because there isn't an easy hook for the cross domain script tag of jsonp
processJsonpUrl( requestSettings );
requestSettings.dataType = "json";
if(requestSettings.data && CALLBACK_REGEX.test(requestSettings.data) || CALLBACK_REGEX.test(requestSettings.url)) {
createJsonpCallback(requestSettings, mockHandler, origSettings);
// We need to make sure
// that a JSONP style response is executed properly
var rurl = /^(\w+:)?\/\/([^\/?#]+)/,
parts = rurl.exec( requestSettings.url ),
remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
requestSettings.dataType = "script";
if(requestSettings.type.toUpperCase() === "GET" && remote ) {
var newMockReturn = processJsonpRequest( requestSettings, mockHandler, origSettings );
// Check if we are supposed to return a Deferred back to the mock call, or just
// signal success
if(newMockReturn) {
return newMockReturn;
} else {
return true;
}
}
}
return null;
} |
JavaScript | function processJsonpUrl( requestSettings ) {
if ( requestSettings.type.toUpperCase() === "GET" ) {
if ( !CALLBACK_REGEX.test( requestSettings.url ) ) {
requestSettings.url += (/\?/.test( requestSettings.url ) ? "&" : "?") +
(requestSettings.jsonp || "callback") + "=?";
}
} else if ( !requestSettings.data || !CALLBACK_REGEX.test(requestSettings.data) ) {
requestSettings.data = (requestSettings.data ? requestSettings.data + "&" : "") + (requestSettings.jsonp || "callback") + "=?";
}
} | function processJsonpUrl( requestSettings ) {
if ( requestSettings.type.toUpperCase() === "GET" ) {
if ( !CALLBACK_REGEX.test( requestSettings.url ) ) {
requestSettings.url += (/\?/.test( requestSettings.url ) ? "&" : "?") +
(requestSettings.jsonp || "callback") + "=?";
}
} else if ( !requestSettings.data || !CALLBACK_REGEX.test(requestSettings.data) ) {
requestSettings.data = (requestSettings.data ? requestSettings.data + "&" : "") + (requestSettings.jsonp || "callback") + "=?";
}
} |
JavaScript | function processJsonpRequest( requestSettings, mockHandler, origSettings ) {
// Synthesize the mock request for adding a script tag
var callbackContext = origSettings && origSettings.context || requestSettings,
newMock = null;
// If the response handler on the moock is a function, call it
if ( mockHandler.response && $.isFunction(mockHandler.response) ) {
mockHandler.response(origSettings);
} else {
// Evaluate the responseText javascript in a global context
if( typeof mockHandler.responseText === 'object' ) {
$.globalEval( '(' + JSON.stringify( mockHandler.responseText ) + ')');
} else {
$.globalEval( '(' + mockHandler.responseText + ')');
}
}
// Successful response
jsonpSuccess( requestSettings, callbackContext, mockHandler );
jsonpComplete( requestSettings, callbackContext, mockHandler );
// If we are running under jQuery 1.5+, return a deferred object
if($.Deferred){
newMock = new $.Deferred();
if(typeof mockHandler.responseText == "object"){
newMock.resolveWith( callbackContext, [mockHandler.responseText] );
}
else{
newMock.resolveWith( callbackContext, [$.parseJSON( mockHandler.responseText )] );
}
}
return newMock;
} | function processJsonpRequest( requestSettings, mockHandler, origSettings ) {
// Synthesize the mock request for adding a script tag
var callbackContext = origSettings && origSettings.context || requestSettings,
newMock = null;
// If the response handler on the moock is a function, call it
if ( mockHandler.response && $.isFunction(mockHandler.response) ) {
mockHandler.response(origSettings);
} else {
// Evaluate the responseText javascript in a global context
if( typeof mockHandler.responseText === 'object' ) {
$.globalEval( '(' + JSON.stringify( mockHandler.responseText ) + ')');
} else {
$.globalEval( '(' + mockHandler.responseText + ')');
}
}
// Successful response
jsonpSuccess( requestSettings, callbackContext, mockHandler );
jsonpComplete( requestSettings, callbackContext, mockHandler );
// If we are running under jQuery 1.5+, return a deferred object
if($.Deferred){
newMock = new $.Deferred();
if(typeof mockHandler.responseText == "object"){
newMock.resolveWith( callbackContext, [mockHandler.responseText] );
}
else{
newMock.resolveWith( callbackContext, [$.parseJSON( mockHandler.responseText )] );
}
}
return newMock;
} |
JavaScript | function createJsonpCallback( requestSettings, mockHandler, origSettings ) {
var callbackContext = origSettings && origSettings.context || requestSettings;
var jsonp = requestSettings.jsonpCallback || ("jsonp" + jsc++);
// Replace the =? sequence both in the query string and the data
if ( requestSettings.data ) {
requestSettings.data = (requestSettings.data + "").replace(CALLBACK_REGEX, "=" + jsonp + "$1");
}
requestSettings.url = requestSettings.url.replace(CALLBACK_REGEX, "=" + jsonp + "$1");
// Handle JSONP-style loading
window[ jsonp ] = window[ jsonp ] || function( tmp ) {
data = tmp;
jsonpSuccess( requestSettings, callbackContext, mockHandler );
jsonpComplete( requestSettings, callbackContext, mockHandler );
// Garbage collect
window[ jsonp ] = undefined;
try {
delete window[ jsonp ];
} catch(e) {}
if ( head ) {
head.removeChild( script );
}
};
} | function createJsonpCallback( requestSettings, mockHandler, origSettings ) {
var callbackContext = origSettings && origSettings.context || requestSettings;
var jsonp = requestSettings.jsonpCallback || ("jsonp" + jsc++);
// Replace the =? sequence both in the query string and the data
if ( requestSettings.data ) {
requestSettings.data = (requestSettings.data + "").replace(CALLBACK_REGEX, "=" + jsonp + "$1");
}
requestSettings.url = requestSettings.url.replace(CALLBACK_REGEX, "=" + jsonp + "$1");
// Handle JSONP-style loading
window[ jsonp ] = window[ jsonp ] || function( tmp ) {
data = tmp;
jsonpSuccess( requestSettings, callbackContext, mockHandler );
jsonpComplete( requestSettings, callbackContext, mockHandler );
// Garbage collect
window[ jsonp ] = undefined;
try {
delete window[ jsonp ];
} catch(e) {}
if ( head ) {
head.removeChild( script );
}
};
} |
JavaScript | function copyUrlParameters(mockHandler, origSettings) {
//parameters aren't captured if the URL isn't a RegExp
if (!(mockHandler.url instanceof RegExp)) {
return;
}
//if no URL params were defined on the handler, don't attempt a capture
if (!mockHandler.hasOwnProperty('urlParams')) {
return;
}
var captures = mockHandler.url.exec(origSettings.url);
//the whole RegExp match is always the first value in the capture results
if (captures.length === 1) {
return;
}
captures.shift();
//use handler params as keys and capture resuts as values
var i = 0,
capturesLength = captures.length,
paramsLength = mockHandler.urlParams.length,
//in case the number of params specified is less than actual captures
maxIterations = Math.min(capturesLength, paramsLength),
paramValues = {};
for (i; i < maxIterations; i++) {
var key = mockHandler.urlParams[i];
paramValues[key] = captures[i];
}
origSettings.urlParams = paramValues;
} | function copyUrlParameters(mockHandler, origSettings) {
//parameters aren't captured if the URL isn't a RegExp
if (!(mockHandler.url instanceof RegExp)) {
return;
}
//if no URL params were defined on the handler, don't attempt a capture
if (!mockHandler.hasOwnProperty('urlParams')) {
return;
}
var captures = mockHandler.url.exec(origSettings.url);
//the whole RegExp match is always the first value in the capture results
if (captures.length === 1) {
return;
}
captures.shift();
//use handler params as keys and capture resuts as values
var i = 0,
capturesLength = captures.length,
paramsLength = mockHandler.urlParams.length,
//in case the number of params specified is less than actual captures
maxIterations = Math.min(capturesLength, paramsLength),
paramValues = {};
for (i; i < maxIterations; i++) {
var key = mockHandler.urlParams[i];
paramValues[key] = captures[i];
}
origSettings.urlParams = paramValues;
} |
JavaScript | function on(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input, callback + capitalize(node[_type])),
specific = option(input, state + capitalize(node[_type]));
// Prevent unnecessary actions
if (node[state] !== true) {
// Toggle assigned radio buttons
if (!keep && state == _checked && node[_type] == _radio && node.name) {
var form = input.closest('form'),
inputs = 'input[name="' + node.name + '"]';
inputs = form.length ? form.find(inputs) : $(inputs);
inputs.each(function() {
if (this !== node && $(this).data(_iCheck)) {
off($(this), state);
}
});
}
// Indeterminate state
if (indeterminate) {
// Add indeterminate state
node[state] = true;
// Remove checked state
if (node[_checked]) {
off(input, _checked, 'force');
}
// Checked or disabled state
} else {
// Add checked or disabled state
if (!keep) {
node[state] = true;
}
// Remove indeterminate state
if (checked && node[_indeterminate]) {
off(input, _indeterminate, false);
}
}
// Trigger callbacks
callbacks(input, checked, state, keep);
}
// Add proper cursor
if (node[_disabled] && !!option(input, _cursor, true)) {
parent.find('.' + _iCheckHelper).css(_cursor, 'default');
}
// Add state class
parent[_add](specific || option(input, state) || '');
// Set ARIA attribute
if (!!parent.attr('role') && !indeterminate) {
parent.attr('aria-' + (disabled ? _disabled : _checked), 'true');
}
// Remove regular state class
parent[_remove](regular || option(input, callback) || '');
} | function on(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input, callback + capitalize(node[_type])),
specific = option(input, state + capitalize(node[_type]));
// Prevent unnecessary actions
if (node[state] !== true) {
// Toggle assigned radio buttons
if (!keep && state == _checked && node[_type] == _radio && node.name) {
var form = input.closest('form'),
inputs = 'input[name="' + node.name + '"]';
inputs = form.length ? form.find(inputs) : $(inputs);
inputs.each(function() {
if (this !== node && $(this).data(_iCheck)) {
off($(this), state);
}
});
}
// Indeterminate state
if (indeterminate) {
// Add indeterminate state
node[state] = true;
// Remove checked state
if (node[_checked]) {
off(input, _checked, 'force');
}
// Checked or disabled state
} else {
// Add checked or disabled state
if (!keep) {
node[state] = true;
}
// Remove indeterminate state
if (checked && node[_indeterminate]) {
off(input, _indeterminate, false);
}
}
// Trigger callbacks
callbacks(input, checked, state, keep);
}
// Add proper cursor
if (node[_disabled] && !!option(input, _cursor, true)) {
parent.find('.' + _iCheckHelper).css(_cursor, 'default');
}
// Add state class
parent[_add](specific || option(input, state) || '');
// Set ARIA attribute
if (!!parent.attr('role') && !indeterminate) {
parent.attr('aria-' + (disabled ? _disabled : _checked), 'true');
}
// Remove regular state class
parent[_remove](regular || option(input, callback) || '');
} |
JavaScript | function off(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input, callback + capitalize(node[_type])),
specific = option(input, state + capitalize(node[_type]));
// Prevent unnecessary actions
if (node[state] !== false) {
// Toggle state
if (indeterminate || !keep || keep == 'force') {
node[state] = false;
}
// Trigger callbacks
callbacks(input, checked, callback, keep);
}
// Add proper cursor
if (!node[_disabled] && !!option(input, _cursor, true)) {
parent.find('.' + _iCheckHelper).css(_cursor, 'pointer');
}
// Remove state class
parent[_remove](specific || option(input, state) || '');
// Set ARIA attribute
if (!!parent.attr('role') && !indeterminate) {
parent.attr('aria-' + (disabled ? _disabled : _checked), 'false');
}
// Add regular state class
parent[_add](regular || option(input, callback) || '');
} | function off(input, state, keep) {
var node = input[0],
parent = input.parent(),
checked = state == _checked,
indeterminate = state == _indeterminate,
disabled = state == _disabled,
callback = indeterminate ? _determinate : checked ? _unchecked : 'enabled',
regular = option(input, callback + capitalize(node[_type])),
specific = option(input, state + capitalize(node[_type]));
// Prevent unnecessary actions
if (node[state] !== false) {
// Toggle state
if (indeterminate || !keep || keep == 'force') {
node[state] = false;
}
// Trigger callbacks
callbacks(input, checked, callback, keep);
}
// Add proper cursor
if (!node[_disabled] && !!option(input, _cursor, true)) {
parent.find('.' + _iCheckHelper).css(_cursor, 'pointer');
}
// Remove state class
parent[_remove](specific || option(input, state) || '');
// Set ARIA attribute
if (!!parent.attr('role') && !indeterminate) {
parent.attr('aria-' + (disabled ? _disabled : _checked), 'false');
}
// Add regular state class
parent[_add](regular || option(input, callback) || '');
} |
JavaScript | function isBetween(a, b1, b2) {
if ((a >= b1) && (a <= b2)) {
return true;
}
if ((a >= b2) && (a <= b1)) {
return true;
}
return false;
} | function isBetween(a, b1, b2) {
if ((a >= b1) && (a <= b2)) {
return true;
}
if ((a >= b2) && (a <= b1)) {
return true;
}
return false;
} |
JavaScript | function clearSplitLine() {
// Clean up
const splitLine = document.getElementById(SPLITTER_ID);
if (splitLine !== null) {
splitLine.remove();
}
} | function clearSplitLine() {
// Clean up
const splitLine = document.getElementById(SPLITTER_ID);
if (splitLine !== null) {
splitLine.remove();
}
} |
JavaScript | function updateSplitLine(color = 'red') {
if (splitPoints.length >= 2) {
const splitLine = document.getElementById(SPLITTER_ID);
if (splitLine) {
const path = [
'M',
splitPoints[0].x,
splitPoints[0].y,
'L',
splitPoints[1].x,
splitPoints[1].y,
'Z',
].join(' ');
splitLine.setAttribute('d', path);
splitLine.setAttribute('stroke', color);
}
}
} | function updateSplitLine(color = 'red') {
if (splitPoints.length >= 2) {
const splitLine = document.getElementById(SPLITTER_ID);
if (splitLine) {
const path = [
'M',
splitPoints[0].x,
splitPoints[0].y,
'L',
splitPoints[1].x,
splitPoints[1].y,
'Z',
].join(' ');
splitLine.setAttribute('d', path);
splitLine.setAttribute('stroke', color);
}
}
} |
JavaScript | function clearPoly() {
const content = document.getElementById('content');
while (content.firstChild) {
content.removeChild(content.firstChild);
}
} | function clearPoly() {
const content = document.getElementById('content');
while (content.firstChild) {
content.removeChild(content.firstChild);
}
} |
JavaScript | async function handleRequest(request) {
if (request.method !== "POST") {
const body = {
error: "Bad Request",
message: "This API only accepts a request using the POST method.",
};
return new Response(JSON.stringify(body, null, 2), {
headers: { "content-type": "application/json;charset=UTF-8" },
status: 400,
});
} else {
const { headers } = request;
const contentType = headers.get("content-type") || "";
if (contentType.includes("application/json")) {
const json = await request.json();
if (typeof json.id === "undefined") {
const body = {
error: "Bad Request",
message: "The id property was missing from the request body.",
};
return new Response(JSON.stringify(body, null, 2), {
headers: { "content-type": "application/json;charset=UTF-8" },
status: 400,
});
} else {
const cachedImage = await IMAGE_KV.get(json.id);
if (cachedImage === null) {
const url =
"https://api.cloudinary.com/v1_1/bachman-io/resources/image/upload/" +
json.id;
const headers = new Headers({
Authorization:
"Basic " + btoa(CLOUDINARY_API_KEY + ":" + CLOUDINARY_API_SECRET),
});
const init = {
headers,
};
const response = await fetch(url, init);
const data = await response.json();
if (
typeof data.error !== "undefined" &&
data.error.message.includes("Resource not found")
) {
const body = {
error: true,
message: data.error.message,
};
return new Response(JSON.stringify(body, null, 2), {
headers: { "content-type": "application/json;charset=UTF-8" },
status: 404,
});
} else {
await IMAGE_KV.put(json.id, JSON.stringify(data), {
expirationTtl: 86400,
});
const body = {
error: false,
message: "Image fetched from Cloudinary and cached to KV.",
data,
};
return new Response(JSON.stringify(body, null, 2), {
headers: { "content-type": "application/json;charset=UTF-8" },
status: 200,
});
}
} else {
const data = JSON.parse(cachedImage);
const body = {
error: false,
message: "Image fetched from KV.",
data,
};
return new Response(JSON.stringify(body, null, 2), {
headers: { "content-type": "application/json;charset=UTF-8" },
status: 200,
});
}
}
} else {
const data = {
error: "Bad Request",
message: "The request body must be JSON..",
};
return new Response(JSON.stringify(data, null, 2), {
headers: { "content-type": "application/json;charset=UTF-8" },
status: 400,
});
}
}
} | async function handleRequest(request) {
if (request.method !== "POST") {
const body = {
error: "Bad Request",
message: "This API only accepts a request using the POST method.",
};
return new Response(JSON.stringify(body, null, 2), {
headers: { "content-type": "application/json;charset=UTF-8" },
status: 400,
});
} else {
const { headers } = request;
const contentType = headers.get("content-type") || "";
if (contentType.includes("application/json")) {
const json = await request.json();
if (typeof json.id === "undefined") {
const body = {
error: "Bad Request",
message: "The id property was missing from the request body.",
};
return new Response(JSON.stringify(body, null, 2), {
headers: { "content-type": "application/json;charset=UTF-8" },
status: 400,
});
} else {
const cachedImage = await IMAGE_KV.get(json.id);
if (cachedImage === null) {
const url =
"https://api.cloudinary.com/v1_1/bachman-io/resources/image/upload/" +
json.id;
const headers = new Headers({
Authorization:
"Basic " + btoa(CLOUDINARY_API_KEY + ":" + CLOUDINARY_API_SECRET),
});
const init = {
headers,
};
const response = await fetch(url, init);
const data = await response.json();
if (
typeof data.error !== "undefined" &&
data.error.message.includes("Resource not found")
) {
const body = {
error: true,
message: data.error.message,
};
return new Response(JSON.stringify(body, null, 2), {
headers: { "content-type": "application/json;charset=UTF-8" },
status: 404,
});
} else {
await IMAGE_KV.put(json.id, JSON.stringify(data), {
expirationTtl: 86400,
});
const body = {
error: false,
message: "Image fetched from Cloudinary and cached to KV.",
data,
};
return new Response(JSON.stringify(body, null, 2), {
headers: { "content-type": "application/json;charset=UTF-8" },
status: 200,
});
}
} else {
const data = JSON.parse(cachedImage);
const body = {
error: false,
message: "Image fetched from KV.",
data,
};
return new Response(JSON.stringify(body, null, 2), {
headers: { "content-type": "application/json;charset=UTF-8" },
status: 200,
});
}
}
} else {
const data = {
error: "Bad Request",
message: "The request body must be JSON..",
};
return new Response(JSON.stringify(data, null, 2), {
headers: { "content-type": "application/json;charset=UTF-8" },
status: 400,
});
}
}
} |
JavaScript | removePlayer(socket) {
const isPlayer = this.teams[socket.id] !== undefined
const isHost = this.host.id === socket.id
if (isPlayer) {
// GET OUTTA HERE
delete this.teams[socket.id]
if (this.state === state.INGAME) {
// if game is in progress, then we probably should pause
this.updateState(state.PAUSED)
} else if (this.state === state.FINISHED) {
// if we're finished, we're pretty much done here
// don't need anything special
}
}
// if host is leaving, we should probably pause because some shit is going on
if (isHost) {
this.updateState(state.PAUSED)
}
socket.leave(this.uniqueName)
delete socket.data.room
delete socket.data.timeJoinedRoom
// tell everyone else that in the room that someone left
socket
.to(this.uniqueName)
.emit(EVENT.ROOM_PLAYER_LEAVE, this.playerInfo())
return Object.keys(this.teams).length === 0
} | removePlayer(socket) {
const isPlayer = this.teams[socket.id] !== undefined
const isHost = this.host.id === socket.id
if (isPlayer) {
// GET OUTTA HERE
delete this.teams[socket.id]
if (this.state === state.INGAME) {
// if game is in progress, then we probably should pause
this.updateState(state.PAUSED)
} else if (this.state === state.FINISHED) {
// if we're finished, we're pretty much done here
// don't need anything special
}
}
// if host is leaving, we should probably pause because some shit is going on
if (isHost) {
this.updateState(state.PAUSED)
}
socket.leave(this.uniqueName)
delete socket.data.room
delete socket.data.timeJoinedRoom
// tell everyone else that in the room that someone left
socket
.to(this.uniqueName)
.emit(EVENT.ROOM_PLAYER_LEAVE, this.playerInfo())
return Object.keys(this.teams).length === 0
} |
JavaScript | attemptToStart(socket) {
// can only start a game if it's in the
// pregame or paused state so stop anything else
if (this.state !== state.PREGAME && this.state !== state.PAUSED) {
return
}
// only the host can start the game
if (this.host.id !== socket.id) {
return
}
const socketIds = Object.keys(this.teams)
// need a full size game to start!
if (socketIds.length < this.teamCount) {
return
}
this.teamData = socketIds.map(socketId => ({
score: 0,
id: socketId,
teamName: this.teams[socketId].data.teamName
}))
this.updateState(state.INGAME)
socket.emit(ACTIONS.GAME_START.RES, this.expandedInfo())
this.addHostListeners()
this.addTeamListeners()
} | attemptToStart(socket) {
// can only start a game if it's in the
// pregame or paused state so stop anything else
if (this.state !== state.PREGAME && this.state !== state.PAUSED) {
return
}
// only the host can start the game
if (this.host.id !== socket.id) {
return
}
const socketIds = Object.keys(this.teams)
// need a full size game to start!
if (socketIds.length < this.teamCount) {
return
}
this.teamData = socketIds.map(socketId => ({
score: 0,
id: socketId,
teamName: this.teams[socketId].data.teamName
}))
this.updateState(state.INGAME)
socket.emit(ACTIONS.GAME_START.RES, this.expandedInfo())
this.addHostListeners()
this.addTeamListeners()
} |
JavaScript | function
syncPanesToNode( node )
{
syncEditorPaneToNode( node );
} | function
syncPanesToNode( node )
{
syncEditorPaneToNode( node );
} |
JavaScript | function createNodeMap(nodes) {
nodes.forEach(function (n) {
nodeMap[String(n.id)] = n;
if (n.type == "memsys") memsysNodes.push(n);
if (n.children) createNodeMap(n.children);
});
} | function createNodeMap(nodes) {
nodes.forEach(function (n) {
nodeMap[String(n.id)] = n;
if (n.type == "memsys") memsysNodes.push(n);
if (n.children) createNodeMap(n.children);
});
} |
JavaScript | function createLinkMap(links) {
links.forEach(function (lnk) {
if (!linkMap[String(lnk.from)]) linkMap[String(lnk.from)] = [];
linkMap[String(lnk.from)].push(lnk);
if (!linkMap[String(lnk.to)]) linkMap[String(lnk.to)] = [];
linkMap[String(lnk.to)].push(lnk);
});
} | function createLinkMap(links) {
links.forEach(function (lnk) {
if (!linkMap[String(lnk.from)]) linkMap[String(lnk.from)] = [];
linkMap[String(lnk.from)].push(lnk);
if (!linkMap[String(lnk.to)]) linkMap[String(lnk.to)] = [];
linkMap[String(lnk.to)].push(lnk);
});
} |
JavaScript | function linkMemory(nodes) {
nodes.forEach(function (n) {
var links = [];
var newLink = {};
n.children.forEach(function (bank) {
if (linkMap[String(bank.id)]) {
linkMap[String(bank.id)].forEach(function (link) {
if (link.from == bank.id) {
if (!flattenedNodes[link.to]) return;
for (var i = 0; i < links.length; i++) {
if (links[i].to == link.to) return;
}
newLink = { from: n.id, to: link.to };
spg.setEdge(String(n.id), String(link.to), { lineInterpolate: "basis" });
if (!flattenedLinks[String(link.to)]) flattenedLinks[String(link.to)] = [];
flattenedLinks[String(link.to)].push(newLink);
} else {
if (!flattenedNodes[link.from]) return;
for (var i = 0; i < links.length; i++) {
if (links[i].from == link.from) return;
}
newLink = { from: link.from, to: n.id };
spg.setEdge(String(link.from), String(n.id), { arrowhead: "normal", lineInterpolate: "basis", weight: 1 });
if (!flattenedLinks[String(link.from)]) flattenedLinks[String(link.from)] = [];
flattenedLinks[String(link.from)].push(newLink);
}
links.push(newLink);
if (!flattenedLinks[String(n.id)]) flattenedLinks[String(n.id)] = [];
flattenedLinks[String(n.id)].push(newLink);
});
}
});
});
} | function linkMemory(nodes) {
nodes.forEach(function (n) {
var links = [];
var newLink = {};
n.children.forEach(function (bank) {
if (linkMap[String(bank.id)]) {
linkMap[String(bank.id)].forEach(function (link) {
if (link.from == bank.id) {
if (!flattenedNodes[link.to]) return;
for (var i = 0; i < links.length; i++) {
if (links[i].to == link.to) return;
}
newLink = { from: n.id, to: link.to };
spg.setEdge(String(n.id), String(link.to), { lineInterpolate: "basis" });
if (!flattenedLinks[String(link.to)]) flattenedLinks[String(link.to)] = [];
flattenedLinks[String(link.to)].push(newLink);
} else {
if (!flattenedNodes[link.from]) return;
for (var i = 0; i < links.length; i++) {
if (links[i].from == link.from) return;
}
newLink = { from: link.from, to: n.id };
spg.setEdge(String(link.from), String(n.id), { arrowhead: "normal", lineInterpolate: "basis", weight: 1 });
if (!flattenedLinks[String(link.from)]) flattenedLinks[String(link.from)] = [];
flattenedLinks[String(link.from)].push(newLink);
}
links.push(newLink);
if (!flattenedLinks[String(n.id)]) flattenedLinks[String(n.id)] = [];
flattenedLinks[String(n.id)].push(newLink);
});
}
});
});
} |
JavaScript | function addClickFunctions(graph) {
var nodes = graph.selectAll("g.node rect, g.nodes .label, g.node circle, g.node polygon")
.on('click', function (d) {
refreshPersistence(graph);
if (clickDown == d) {
clickDown = null;
} else {
highlightNodes(d, graph);
changeDivContent(VIEWS.SPV, 0, detailTable(d));
clickDown = d;
}
// details and editor syncing (reset if no line number)
if (flattenedNodes[d].hasOwnProperty('file') && flattenedNodes[d].file != "" && flattenedNodes[d].file != "0") syncEditorPaneToLine(flattenedNodes[d].line, findFile(flattenedNodes[d].file));
else syncEditorPaneToLine(1, curFile);
});
} | function addClickFunctions(graph) {
var nodes = graph.selectAll("g.node rect, g.nodes .label, g.node circle, g.node polygon")
.on('click', function (d) {
refreshPersistence(graph);
if (clickDown == d) {
clickDown = null;
} else {
highlightNodes(d, graph);
changeDivContent(VIEWS.SPV, 0, detailTable(d));
clickDown = d;
}
// details and editor syncing (reset if no line number)
if (flattenedNodes[d].hasOwnProperty('file') && flattenedNodes[d].file != "" && flattenedNodes[d].file != "0") syncEditorPaneToLine(flattenedNodes[d].line, findFile(flattenedNodes[d].file));
else syncEditorPaneToLine(1, curFile);
});
} |
JavaScript | function findFile(index) {
var filename = "";
Object.keys(mavData.fileIndexMap).forEach(function (fi) {
if (mavData.fileIndexMap[fi] == index) filename = getFilename(fi);
});
return filename;
} | function findFile(index) {
var filename = "";
Object.keys(mavData.fileIndexMap).forEach(function (fi) {
if (mavData.fileIndexMap[fi] == index) filename = getFilename(fi);
});
return filename;
} |
JavaScript | function addHighlighting(graph) {
var highlightColor = "#1d99c1";
var clusterHighlights = graph.selectAll("g.cluster rect")
.on('mouseover', function (d) {
if (!clickDown && flattenedNodes[d] && (flattenedNodes[d].details || flattenedNodes[d].II)) {
changeDivContent(VIEWS.SPV, 0, detailTable(d));
}
});
var nodeHighlights = graph.selectAll("g.node rect, g.label, g.node circle, g.node polygon")
.on('mouseover', function (d) {
highlightNodes(d, graph);
if (!clickDown && flattenedNodes[d] && (flattenedNodes[d].details || flattenedNodes[d].type == "memsys")) {
changeDivContent(VIEWS.SPV, 0, detailTable(d));
}
})
.on('mouseout', function (d) {
if (clickDown != d) {
refreshPersistence(graph);
highlightNodes(clickDown, graph);
}
});
// Highlight link, associated nodes on mouseover
var linkHighlights = graph.selectAll("g.edgePath path")
.on('mouseover', function (d) {
var connections = graph.selectAll("g.edgePath")
.filter(function (k) {
return d.v == k.v && d.w == k.w;
});
connections.selectAll("path")
.style("opacity", 1)
.style("stroke-width", 5)
.style("stroke", highlightColor);
var connectedNodes = graph.selectAll("g.node rect, g.node circle, g.node polygon")
.filter(function (n) {
return n == d.v || n == d.w;
})
.style("stroke-width", 3)
.style("stroke", highlightColor);
connections.selectAll("marker")
.attr({
"markerUnits": "userSpaceOnUse",
"preserveAspectRatio": "none",
"viewBox": "0 0 40 10",
"refX": 6,
"markerWidth": 40,
"markerHeight": 12
})
.style("stroke-width", 0);
connections.selectAll("marker path")
.attr("style", "fill:" + highlightColor + "; opacity: 1; stroke-width:0");
})
.on('mouseout', function (d) {
if (clickDown != d) refreshPersistence(graph);
if (clickDown) highlightNodes(clickDown, graph);
});
} | function addHighlighting(graph) {
var highlightColor = "#1d99c1";
var clusterHighlights = graph.selectAll("g.cluster rect")
.on('mouseover', function (d) {
if (!clickDown && flattenedNodes[d] && (flattenedNodes[d].details || flattenedNodes[d].II)) {
changeDivContent(VIEWS.SPV, 0, detailTable(d));
}
});
var nodeHighlights = graph.selectAll("g.node rect, g.label, g.node circle, g.node polygon")
.on('mouseover', function (d) {
highlightNodes(d, graph);
if (!clickDown && flattenedNodes[d] && (flattenedNodes[d].details || flattenedNodes[d].type == "memsys")) {
changeDivContent(VIEWS.SPV, 0, detailTable(d));
}
})
.on('mouseout', function (d) {
if (clickDown != d) {
refreshPersistence(graph);
highlightNodes(clickDown, graph);
}
});
// Highlight link, associated nodes on mouseover
var linkHighlights = graph.selectAll("g.edgePath path")
.on('mouseover', function (d) {
var connections = graph.selectAll("g.edgePath")
.filter(function (k) {
return d.v == k.v && d.w == k.w;
});
connections.selectAll("path")
.style("opacity", 1)
.style("stroke-width", 5)
.style("stroke", highlightColor);
var connectedNodes = graph.selectAll("g.node rect, g.node circle, g.node polygon")
.filter(function (n) {
return n == d.v || n == d.w;
})
.style("stroke-width", 3)
.style("stroke", highlightColor);
connections.selectAll("marker")
.attr({
"markerUnits": "userSpaceOnUse",
"preserveAspectRatio": "none",
"viewBox": "0 0 40 10",
"refX": 6,
"markerWidth": 40,
"markerHeight": 12
})
.style("stroke-width", 0);
connections.selectAll("marker path")
.attr("style", "fill:" + highlightColor + "; opacity: 1; stroke-width:0");
})
.on('mouseout', function (d) {
if (clickDown != d) refreshPersistence(graph);
if (clickDown) highlightNodes(clickDown, graph);
});
} |
JavaScript | function checkInst(insts, node, isSPG) {
var index = 0;
for (var i = 0; i < insts.length; i++) {
if ( node.type == "inst"
&& node.name == insts[i].name
&& node.line == insts[i].line
&& node.file == insts[i].file
&& verifyLinks(insts[i], node, isSPG)) { return index; }
index++;
}
return -1;
} | function checkInst(insts, node, isSPG) {
var index = 0;
for (var i = 0; i < insts.length; i++) {
if ( node.type == "inst"
&& node.name == insts[i].name
&& node.line == insts[i].line
&& node.file == insts[i].file
&& verifyLinks(insts[i], node, isSPG)) { return index; }
index++;
}
return -1;
} |
JavaScript | function verifyLinks(inst, node, isSPG) {
var instLinks = linkMap[String(inst.id)];
var nodeLinks = linkMap[String(node.id)];
var found = false;
for (var j = 0; j < instLinks.length; j++) {
found = false;
if (instLinks[j].from == inst.id) {
for (var i = 0; i < nodeLinks.length; i++) {
if ( nodeLinks[i].from == node.id
&& (nodeLinks[i].to == instLinks[j].to
|| (isSameLoadStoreTarget(nodeLinks[i].to, instLinks[j].to) && isSPG))
&& nodeLinks[i].from == node.id) {
found = true;
break;
}
}
if (!found) return false;
} else if (instLinks[j].to == inst.id) {
for (var i = 0; i < nodeLinks.length; i++) {
if ( ( nodeLinks[i].from == instLinks[j].from
|| (isSameLoadStoreTarget(nodeLinks[i].from, instLinks[j].from) && isSPG))
&& nodeLinks[i].to == node.id) {
found = true;
break;
}
}
if (!found) return false;
}
}
return true;
} | function verifyLinks(inst, node, isSPG) {
var instLinks = linkMap[String(inst.id)];
var nodeLinks = linkMap[String(node.id)];
var found = false;
for (var j = 0; j < instLinks.length; j++) {
found = false;
if (instLinks[j].from == inst.id) {
for (var i = 0; i < nodeLinks.length; i++) {
if ( nodeLinks[i].from == node.id
&& (nodeLinks[i].to == instLinks[j].to
|| (isSameLoadStoreTarget(nodeLinks[i].to, instLinks[j].to) && isSPG))
&& nodeLinks[i].from == node.id) {
found = true;
break;
}
}
if (!found) return false;
} else if (instLinks[j].to == inst.id) {
for (var i = 0; i < nodeLinks.length; i++) {
if ( ( nodeLinks[i].from == instLinks[j].from
|| (isSameLoadStoreTarget(nodeLinks[i].from, instLinks[j].from) && isSPG))
&& nodeLinks[i].to == node.id) {
found = true;
break;
}
}
if (!found) return false;
}
}
return true;
} |
JavaScript | function createMarker(data) {
// Marker path
var markerPath = 'M403.8,178.4c0.1,0.2,0.1,0.5,0.2,0.7 M407.3,194.5c4.9,29.6,0.2,59.4-13,89.1 c-19.4,43.8-47.5,81.7-81.3,115.3c-15.5,15.4-32.3,29.5-48.6,44c-1.8,1.6-4.2,2.6-6.3,3.9c-1.5,0-3,0-4.5,0 c-6.1-4.6-12.5-8.9-18.3-13.8c-25.1-21.4-48.5-44.4-69-70.1 M144.6,332.9c-14.6-21.9-27.2-45-34.9-70.4 c-11.3-37.2-8.8-73.8,7.9-109.1c16.6-35.1,43-60.3,78.5-75.9c14.8-6.5,30.4-10.5,46.7-11.7c1-0.1,1.9-0.4,2.8-0.6 c6.7,0,13.4,0,20.1,0c7.8,1.2,15.8,1.9,23.5,3.8c47.3,11.4,82.5,38.7,104.1,82.4c1.9,3.9,3.6,7.7,5.2,11.6 M210.4,159.6 c-17.8,13.6-29.4,35.2-29.9,59.6c-0.9,41.1,33,75.5,75,76.2c40.9,0.6,75.1-32.9,75.9-74.5c0.8-41.6-32.9-76-75-76.6 c-9-0.1-17.6,1.4-25.6,4.2';
// Remove current markers from map
removeMarkers();
// Clear markers array
markers = [];
// Info Window
infowindow = new google.maps.InfoWindow();
data.forEach(function(data) {
// Create a marker per location, and put into markers array.
var marker = new google.maps.Marker({
// map: map,
position: {
lat: parseFloat(data.restaurant.location.latitude, 10),
lng: parseFloat(data.restaurant.location.longitude, 10)
},
title: data.restaurant.name,
animation: google.maps.Animation.DROP,
icon: {
path: markerPath,
strokeColor: '#' + data.restaurant.user_rating.rating_color,
strokeOpacity: 1,
strokeWeight: 2,
fillColor: '#18243b',
fillOpacity: 1,
scale: 0.1,
anchor: new google.maps.Point(250, 450)
},
// Marker/List display will be toggled based on this property
display: ko.observable(true),
info: {
url: data.restaurant.url,
avgCost: data.restaurant.average_cost_for_two,
cuisines: data.restaurant.cuisines,
image: data.restaurant.featured_image,
address: data.restaurant.location.address,
rating: data.restaurant.user_rating.aggregate_rating,
ratingText: data.restaurant.user_rating.rating_text,
ratingColor: data.restaurant.user_rating.rating_color
}
});
// Push the marker to the array of markers.
markers.push(marker);
// Create an onclick event to open an infowindow on each marker.
marker.addListener('click', function() {
// Toggle marker bounce animation
toggleBounce(marker);
populateInfoWindow(this);
});
});
// Push the marker to the knockout viewModel.dineList array
viewModel.dineList(markers);
// Show markers on map
showMarkers();
} | function createMarker(data) {
// Marker path
var markerPath = 'M403.8,178.4c0.1,0.2,0.1,0.5,0.2,0.7 M407.3,194.5c4.9,29.6,0.2,59.4-13,89.1 c-19.4,43.8-47.5,81.7-81.3,115.3c-15.5,15.4-32.3,29.5-48.6,44c-1.8,1.6-4.2,2.6-6.3,3.9c-1.5,0-3,0-4.5,0 c-6.1-4.6-12.5-8.9-18.3-13.8c-25.1-21.4-48.5-44.4-69-70.1 M144.6,332.9c-14.6-21.9-27.2-45-34.9-70.4 c-11.3-37.2-8.8-73.8,7.9-109.1c16.6-35.1,43-60.3,78.5-75.9c14.8-6.5,30.4-10.5,46.7-11.7c1-0.1,1.9-0.4,2.8-0.6 c6.7,0,13.4,0,20.1,0c7.8,1.2,15.8,1.9,23.5,3.8c47.3,11.4,82.5,38.7,104.1,82.4c1.9,3.9,3.6,7.7,5.2,11.6 M210.4,159.6 c-17.8,13.6-29.4,35.2-29.9,59.6c-0.9,41.1,33,75.5,75,76.2c40.9,0.6,75.1-32.9,75.9-74.5c0.8-41.6-32.9-76-75-76.6 c-9-0.1-17.6,1.4-25.6,4.2';
// Remove current markers from map
removeMarkers();
// Clear markers array
markers = [];
// Info Window
infowindow = new google.maps.InfoWindow();
data.forEach(function(data) {
// Create a marker per location, and put into markers array.
var marker = new google.maps.Marker({
// map: map,
position: {
lat: parseFloat(data.restaurant.location.latitude, 10),
lng: parseFloat(data.restaurant.location.longitude, 10)
},
title: data.restaurant.name,
animation: google.maps.Animation.DROP,
icon: {
path: markerPath,
strokeColor: '#' + data.restaurant.user_rating.rating_color,
strokeOpacity: 1,
strokeWeight: 2,
fillColor: '#18243b',
fillOpacity: 1,
scale: 0.1,
anchor: new google.maps.Point(250, 450)
},
// Marker/List display will be toggled based on this property
display: ko.observable(true),
info: {
url: data.restaurant.url,
avgCost: data.restaurant.average_cost_for_two,
cuisines: data.restaurant.cuisines,
image: data.restaurant.featured_image,
address: data.restaurant.location.address,
rating: data.restaurant.user_rating.aggregate_rating,
ratingText: data.restaurant.user_rating.rating_text,
ratingColor: data.restaurant.user_rating.rating_color
}
});
// Push the marker to the array of markers.
markers.push(marker);
// Create an onclick event to open an infowindow on each marker.
marker.addListener('click', function() {
// Toggle marker bounce animation
toggleBounce(marker);
populateInfoWindow(this);
});
});
// Push the marker to the knockout viewModel.dineList array
viewModel.dineList(markers);
// Show markers on map
showMarkers();
} |
JavaScript | function showMarkers() {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
if (markers[i].display()) {
markers[i].setMap(map);
// Extend bounds only if lat, lng is specified
if (markers[i].position.lat() !== 0 || markers[i].position.lng() !== 0) {
bounds.extend(markers[i].position);
}
} else {
markers[i].setMap(null);
}
}
// Extend the boundaries of the map for each marker
map.fitBounds(bounds);
// Extend the boundaries of the map for each marker when screen is resized
google.maps.event.addDomListener(window, 'resize', function() {
map.fitBounds(bounds);
});
// If no results found then alert user
if (markers.length === 0) {
alert("No results found in 2 kilometer radius");
}
} | function showMarkers() {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
if (markers[i].display()) {
markers[i].setMap(map);
// Extend bounds only if lat, lng is specified
if (markers[i].position.lat() !== 0 || markers[i].position.lng() !== 0) {
bounds.extend(markers[i].position);
}
} else {
markers[i].setMap(null);
}
}
// Extend the boundaries of the map for each marker
map.fitBounds(bounds);
// Extend the boundaries of the map for each marker when screen is resized
google.maps.event.addDomListener(window, 'resize', function() {
map.fitBounds(bounds);
});
// If no results found then alert user
if (markers.length === 0) {
alert("No results found in 2 kilometer radius");
}
} |
JavaScript | function CenterControl(controlDiv, map) {
// Set CSS for the control border.
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = '#252539';
// controlUI.style.border = '2px solid #fff';
controlUI.style.borderRadius = '10px';
controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
controlUI.style.cursor = 'pointer';
controlUI.style.marginBottom = '10px';
controlUI.style.marginLeft = '5px';
controlUI.style.textAlign = 'center';
controlUI.title = 'Toggle Map Mode';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior.
var controlText = document.createElement('div');
controlText.style.color = '#bec0c4';
controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
controlText.style.fontSize = '16px';
controlText.style.lineHeight = '38px';
controlText.style.paddingLeft = '10px';
controlText.style.paddingRight = '10px';
controlText.innerHTML = 'Dark Mode';
controlUI.appendChild(controlText);
// Clicking on the toggle mode button will change the map style
controlUI.addEventListener('click', function() {
if (map.styles === '') {
map.setOptions({ styles: mapDarkStyle });
controlText.innerHTML = 'Normal Mode';
controlUI.style.backgroundColor = '#d2d4d8';
controlText.style.color = '#434343';
} else {
map.setOptions({ styles: '' });
controlText.innerHTML = 'Dark Mode';
controlUI.style.backgroundColor = '#252539';
controlText.style.color = '#bec0c4';
}
});
} | function CenterControl(controlDiv, map) {
// Set CSS for the control border.
var controlUI = document.createElement('div');
controlUI.style.backgroundColor = '#252539';
// controlUI.style.border = '2px solid #fff';
controlUI.style.borderRadius = '10px';
controlUI.style.boxShadow = '0 2px 6px rgba(0,0,0,.3)';
controlUI.style.cursor = 'pointer';
controlUI.style.marginBottom = '10px';
controlUI.style.marginLeft = '5px';
controlUI.style.textAlign = 'center';
controlUI.title = 'Toggle Map Mode';
controlDiv.appendChild(controlUI);
// Set CSS for the control interior.
var controlText = document.createElement('div');
controlText.style.color = '#bec0c4';
controlText.style.fontFamily = 'Roboto,Arial,sans-serif';
controlText.style.fontSize = '16px';
controlText.style.lineHeight = '38px';
controlText.style.paddingLeft = '10px';
controlText.style.paddingRight = '10px';
controlText.innerHTML = 'Dark Mode';
controlUI.appendChild(controlText);
// Clicking on the toggle mode button will change the map style
controlUI.addEventListener('click', function() {
if (map.styles === '') {
map.setOptions({ styles: mapDarkStyle });
controlText.innerHTML = 'Normal Mode';
controlUI.style.backgroundColor = '#d2d4d8';
controlText.style.color = '#434343';
} else {
map.setOptions({ styles: '' });
controlText.innerHTML = 'Dark Mode';
controlUI.style.backgroundColor = '#252539';
controlText.style.color = '#bec0c4';
}
});
} |
JavaScript | function handleLocationError(browserHasGeolocation, pos) {
if (browserHasGeolocation) {
// Geolocation service failed
console.log('Error: Denied geolocation, try selecting location from the menu');
} else {
console.log('Error: This browser doesn\'t support geolocation.');
viewModel.errorText("Error: This browser doesn\'t support geolocation.");
}
} | function handleLocationError(browserHasGeolocation, pos) {
if (browserHasGeolocation) {
// Geolocation service failed
console.log('Error: Denied geolocation, try selecting location from the menu');
} else {
console.log('Error: This browser doesn\'t support geolocation.');
viewModel.errorText("Error: This browser doesn\'t support geolocation.");
}
} |
JavaScript | function mapStateToProps(state) {
return {
book: state.activeBook
}
} | function mapStateToProps(state) {
return {
book: state.activeBook
}
} |
JavaScript | format( err ) {
this.fileObject.errors++;
this.fileObject.messages.push(
{
line: err.lineNumber,
column: err.column,
message: err.description,
severity: 5,
type: 'ERROR',
fixable: false
}
);
} | format( err ) {
this.fileObject.errors++;
this.fileObject.messages.push(
{
line: err.lineNumber,
column: err.column,
message: err.description,
severity: 5,
type: 'ERROR',
fixable: false
}
);
} |
JavaScript | process() {
return new Promise( ( resolve, reject ) => {
fetch( this.path )
.then( response => response.text() )
.then( data => {
const errors = esprima.parse( data,
{
tolerant: true,
loc: true
}
).errors;
for ( let error of errors ) {
this.format( error );
}
})
.catch( error => this.format( error ) )
.finally( () => this.fileObject.errors && resolve( this.fileObject ) );
});
} | process() {
return new Promise( ( resolve, reject ) => {
fetch( this.path )
.then( response => response.text() )
.then( data => {
const errors = esprima.parse( data,
{
tolerant: true,
loc: true
}
).errors;
for ( let error of errors ) {
this.format( error );
}
})
.catch( error => this.format( error ) )
.finally( () => this.fileObject.errors && resolve( this.fileObject ) );
});
} |
JavaScript | function generateHTML(testResults) {
var stepsHtml = '',
header = '',
isPassed = false,
passedScenarios = 0,
passedSteps = 0,
stepsNumber = 0,
scenariosNumber = 0,
scenariosNumberInFeature = 0,
passedScenariosNumberInFeature = 0,
stepsNumberInFeature = 0,
passedStepsInFeature = 0,
scenariosHtml = '',
element,
step,
stepDuration = 0;
html = '';
for (var i = 0; i < testResults.length; i++) {
scenariosNumberInFeature = 0;
passedScenariosNumberInFeature = 0;
stepsNumberInFeature = 0;
passedStepsInFeature = 0;
scenariosHtml = '';
if (testResults[i].elements) {
for (var j = 0; j < testResults[i].elements.length; j++) {
element = testResults[i].elements[j];
if (element.type === 'scenario') {
scenariosNumber++;
scenariosNumberInFeature++;
stepsHtml = '';
isPassed = true;
for (var k = 0; k < testResults[i].elements[j].steps.length; k++) {
step = testResults[i].elements[j].steps[k];
if (isEmptyAfterStep(step) || isEmptyBeforeStep(step)) {
continue;
}
if (isAfterStepWithScreenshot(step)) {
stepsHtml += getAfterScreenshotStep(step);
} else {
stepsHtml += getStep(step);
stepDuration += (step.result.duration ? step.result.duration : 0);
stepsNumber++;
stepsNumberInFeature++;
if (step.result.status !== statuses.PASSED) {
isPassed = false;
} else if (step.result.status === statuses.PASSED) {
passedSteps++;
passedStepsInFeature++;
}
}
}
if (isPassed) {
passedScenarios++;
passedScenariosNumberInFeature++;
}
scenariosHtml += getScenarioContainer(getScenario(element, isPassed, stepsHtml));
}
}
}
html += getFeatureWithScenarios(getFeature(testResults[i], scenariosNumberInFeature, passedScenariosNumberInFeature, stepsNumberInFeature, passedStepsInFeature) + scenariosHtml);
}
header = getHeader(scenariosNumber, passedScenarios, stepsNumber, passedSteps, calculateDuration(stepDuration));
return header + html;
} | function generateHTML(testResults) {
var stepsHtml = '',
header = '',
isPassed = false,
passedScenarios = 0,
passedSteps = 0,
stepsNumber = 0,
scenariosNumber = 0,
scenariosNumberInFeature = 0,
passedScenariosNumberInFeature = 0,
stepsNumberInFeature = 0,
passedStepsInFeature = 0,
scenariosHtml = '',
element,
step,
stepDuration = 0;
html = '';
for (var i = 0; i < testResults.length; i++) {
scenariosNumberInFeature = 0;
passedScenariosNumberInFeature = 0;
stepsNumberInFeature = 0;
passedStepsInFeature = 0;
scenariosHtml = '';
if (testResults[i].elements) {
for (var j = 0; j < testResults[i].elements.length; j++) {
element = testResults[i].elements[j];
if (element.type === 'scenario') {
scenariosNumber++;
scenariosNumberInFeature++;
stepsHtml = '';
isPassed = true;
for (var k = 0; k < testResults[i].elements[j].steps.length; k++) {
step = testResults[i].elements[j].steps[k];
if (isEmptyAfterStep(step) || isEmptyBeforeStep(step)) {
continue;
}
if (isAfterStepWithScreenshot(step)) {
stepsHtml += getAfterScreenshotStep(step);
} else {
stepsHtml += getStep(step);
stepDuration += (step.result.duration ? step.result.duration : 0);
stepsNumber++;
stepsNumberInFeature++;
if (step.result.status !== statuses.PASSED) {
isPassed = false;
} else if (step.result.status === statuses.PASSED) {
passedSteps++;
passedStepsInFeature++;
}
}
}
if (isPassed) {
passedScenarios++;
passedScenariosNumberInFeature++;
}
scenariosHtml += getScenarioContainer(getScenario(element, isPassed, stepsHtml));
}
}
}
html += getFeatureWithScenarios(getFeature(testResults[i], scenariosNumberInFeature, passedScenariosNumberInFeature, stepsNumberInFeature, passedStepsInFeature) + scenariosHtml);
}
header = getHeader(scenariosNumber, passedScenarios, stepsNumber, passedSteps, calculateDuration(stepDuration));
return header + html;
} |
JavaScript | function generateReport(html) {
var template = grunt.file.read(templates.reportTemplate);
return grunt.template.process(template, {
data: {
scenarios: html
}
});
} | function generateReport(html) {
var template = grunt.file.read(templates.reportTemplate);
return grunt.template.process(template, {
data: {
scenarios: html
}
});
} |
JavaScript | function addDept() {
//inquirer prompts to gather user information
inquirer
//function to collect user input
.prompt([
//collecting the name of the new Department
{
name: "newDepartment",
type: "input",
message: "Please input the name of the new Department",
},
])
//promise to do after the inquirer prompts collect user information
.then((data) => {
//creating the query for setting the department in the department table
const query = "INSERT INTO department SET ?";
//making an object of the table row and corresponding infromation to put in that field
const newDept = {
name: data.newDepartment,
};
//calling the connection file and passing in the query and object of user input to the MySQL database
connection.query(query, newDept, (err, res) => {
//error handling
if (err) throw err;
//console success message
console.log("New Department successfully added to the department table of the company database!");
//returning the program to the file containing the inquirer prompts
inquireMod.prompts();
});
});
} | function addDept() {
//inquirer prompts to gather user information
inquirer
//function to collect user input
.prompt([
//collecting the name of the new Department
{
name: "newDepartment",
type: "input",
message: "Please input the name of the new Department",
},
])
//promise to do after the inquirer prompts collect user information
.then((data) => {
//creating the query for setting the department in the department table
const query = "INSERT INTO department SET ?";
//making an object of the table row and corresponding infromation to put in that field
const newDept = {
name: data.newDepartment,
};
//calling the connection file and passing in the query and object of user input to the MySQL database
connection.query(query, newDept, (err, res) => {
//error handling
if (err) throw err;
//console success message
console.log("New Department successfully added to the department table of the company database!");
//returning the program to the file containing the inquirer prompts
inquireMod.prompts();
});
});
} |
JavaScript | function deleteDept() {
//calling inquirer
inquirer
//function to determine user inputs
.prompt([
//asking the user to enter the name of the department to be deleted
{
name: "department",
type: "input",
message: "Enter the name of the Department you would like to delete.",
},
])
//promise to return after user input
.then((data) => {
//setting DELETE query on role table WHERE the department name is equal to the user input
const query = "DELETE FROM department WHERE ?";
//object containing the table row name and user input
const deleteDept = {
name: data.department,
};
//calling the connection file and passing in the query and object of user input to the MySQL database
connection.query(query, deleteDept, (err, res) => {
//error handling
if (err) throw err;
//console success message
console.log(
"This Department has been deleted from the department table of the company database."
);
//returning the program to the file contaiing the inquirer prompts
inquireMod.prompts();
});
});
} | function deleteDept() {
//calling inquirer
inquirer
//function to determine user inputs
.prompt([
//asking the user to enter the name of the department to be deleted
{
name: "department",
type: "input",
message: "Enter the name of the Department you would like to delete.",
},
])
//promise to return after user input
.then((data) => {
//setting DELETE query on role table WHERE the department name is equal to the user input
const query = "DELETE FROM department WHERE ?";
//object containing the table row name and user input
const deleteDept = {
name: data.department,
};
//calling the connection file and passing in the query and object of user input to the MySQL database
connection.query(query, deleteDept, (err, res) => {
//error handling
if (err) throw err;
//console success message
console.log(
"This Department has been deleted from the department table of the company database."
);
//returning the program to the file contaiing the inquirer prompts
inquireMod.prompts();
});
});
} |
JavaScript | function addEmployee() {
//calling inquirer
inquirer
//function to collect user input
.prompt([
//collecting the employee first name
{
name: "empFName",
type: "input",
message: "Please input new employee's first name.",
},
//collecting employee last name
{
name: "empLName",
type: "input",
message: "Please input the new employee's last name.",
},
//collecting a role id for employee
{
name: "empRole",
type: "input",
message: "Please input the Role ID for the new employee.",
},
//collecting the employee id of the manager
{
name: "empManager",
type: "input",
message:
"Please input Employee ID of the new employee (Please leave blank if the employee is a manager).",
},
])
//promise to do after inquirer prompts collect user information
.then((data) => {
//creating the query for setting the employee in the employee table
const query = "INSERT INTO employee SET ?";
//making an object of table rows and user input tha corresponds to that field
const newEmp = {
first_name: data.empFName,
last_name: data.empLName,
role_id: data.empRole,
manager_id: data.empManager,
};
//calling the connection file and passing in the query and object of user input to the MySQL database
connection.query(query, newEmp, (err, res) => {
//error handling
if (err) throw err;
//console success message
console.log("New Employee successfully added to the employee table of the company database.");
//returning the program to the file containing the inquirer prompts
inquireMod.prompts();
});
});
} | function addEmployee() {
//calling inquirer
inquirer
//function to collect user input
.prompt([
//collecting the employee first name
{
name: "empFName",
type: "input",
message: "Please input new employee's first name.",
},
//collecting employee last name
{
name: "empLName",
type: "input",
message: "Please input the new employee's last name.",
},
//collecting a role id for employee
{
name: "empRole",
type: "input",
message: "Please input the Role ID for the new employee.",
},
//collecting the employee id of the manager
{
name: "empManager",
type: "input",
message:
"Please input Employee ID of the new employee (Please leave blank if the employee is a manager).",
},
])
//promise to do after inquirer prompts collect user information
.then((data) => {
//creating the query for setting the employee in the employee table
const query = "INSERT INTO employee SET ?";
//making an object of table rows and user input tha corresponds to that field
const newEmp = {
first_name: data.empFName,
last_name: data.empLName,
role_id: data.empRole,
manager_id: data.empManager,
};
//calling the connection file and passing in the query and object of user input to the MySQL database
connection.query(query, newEmp, (err, res) => {
//error handling
if (err) throw err;
//console success message
console.log("New Employee successfully added to the employee table of the company database.");
//returning the program to the file containing the inquirer prompts
inquireMod.prompts();
});
});
} |
JavaScript | function updateEmpRole() {
//calling inquirer
inquirer
//function to collect user input
.prompt([
//asking for the ID of the employee whose role is to be updated
{
name: "employee",
type: "input",
message:
"Enter the ID of the Employee whose Role you would like to update.",
},
//collecting the new role id for that employee
{
name: "role",
type: "input",
message: "Enter the new Role ID for this Employee.",
},
])
//promise to perform after user input
.then((data) => {
//query to update the employee record WHERE the id is equal to the input and set it to the new role id infromation input by the user
const query = "UPDATE employee SET ? WHERE ?";
//object for what information to put into the question marks
const newRole = [
{
role_id: data.role,
},
{
id: data.employee,
},
];
//calling the connection file and passing in the query and object of user input to the MySQL database
connection.query(query, newRole, (err, res) => {
//error handling
if (err) throw err;
//console success message
console.log("This Role has been updated in the employee table.");
//returning the program to the file containing the inquirer prompts
inquireMod.prompts();
});
});
} | function updateEmpRole() {
//calling inquirer
inquirer
//function to collect user input
.prompt([
//asking for the ID of the employee whose role is to be updated
{
name: "employee",
type: "input",
message:
"Enter the ID of the Employee whose Role you would like to update.",
},
//collecting the new role id for that employee
{
name: "role",
type: "input",
message: "Enter the new Role ID for this Employee.",
},
])
//promise to perform after user input
.then((data) => {
//query to update the employee record WHERE the id is equal to the input and set it to the new role id infromation input by the user
const query = "UPDATE employee SET ? WHERE ?";
//object for what information to put into the question marks
const newRole = [
{
role_id: data.role,
},
{
id: data.employee,
},
];
//calling the connection file and passing in the query and object of user input to the MySQL database
connection.query(query, newRole, (err, res) => {
//error handling
if (err) throw err;
//console success message
console.log("This Role has been updated in the employee table.");
//returning the program to the file containing the inquirer prompts
inquireMod.prompts();
});
});
} |
JavaScript | function updateEmpManager() {
//calling inquirer
inquirer
//function to collect user input
.prompt([
//collecting the employee id
{
name: "employee",
type: "input",
message:
"Enter the ID of the Employee whose Manager you would like to update.",
},
//collecting the employee id of the manager for this employee
{
name: "manager",
type: "input",
message: "Enter the new Manager ID for this Employee.",
},
])
//promise to do after inquirer prompts collect user information
.then((data) => {
//creating the query string to update employee table at employee id with new manager id input from user
const query = "UPDATE employee SET ? WHERE ?";
//making an object of table rows and user input that corresponds to that field
const newRole = [
{
manager_id: data.manager,
},
{
id: data.employee,
},
];
//calling the connection file and passing in the query and object of user input to the MySQL database
connection.query(query, newRole, (err, res) => {
//error handling
if (err) throw err;
console.log("This Employee's record has been updated in the employee table of the company database.")
//returning the program to the file containing the inquirer prompts
inquireMod.prompts();
});
});
} | function updateEmpManager() {
//calling inquirer
inquirer
//function to collect user input
.prompt([
//collecting the employee id
{
name: "employee",
type: "input",
message:
"Enter the ID of the Employee whose Manager you would like to update.",
},
//collecting the employee id of the manager for this employee
{
name: "manager",
type: "input",
message: "Enter the new Manager ID for this Employee.",
},
])
//promise to do after inquirer prompts collect user information
.then((data) => {
//creating the query string to update employee table at employee id with new manager id input from user
const query = "UPDATE employee SET ? WHERE ?";
//making an object of table rows and user input that corresponds to that field
const newRole = [
{
manager_id: data.manager,
},
{
id: data.employee,
},
];
//calling the connection file and passing in the query and object of user input to the MySQL database
connection.query(query, newRole, (err, res) => {
//error handling
if (err) throw err;
console.log("This Employee's record has been updated in the employee table of the company database.")
//returning the program to the file containing the inquirer prompts
inquireMod.prompts();
});
});
} |
JavaScript | function viewEmployeesByManager() {
//query string to concatenate the manager name and display the employees that report to that manager joining role by role id to employee, department by department id onto role, and an inner join on employee
const query = `SELECT CONCAT(e2.first_name, " ", e2.last_name) AS Manager, e1.id AS EMPID, e1.first_name AS FName, e1.last_name AS LName, role.title AS Title, department.name AS Department, role.salary AS Salary FROM employee AS e1
LEFT JOIN role on e1.role_id = role.id
LEFT JOIN department ON role.department_id = department.id
INNER JOIN employee AS e2 on e2.id=e1.manager_id
ORDER BY manager ASC;`;
//calling the connection file and passing in the query and object of user input to the MySQL database
connection.query(query, (err, res) => {
//error handling
if (err) throw err;
//generating a table from returned information
const table = cTable.getTable(res);
//sending the table to the console
console.log(table);
//returning the program to the inquirer prompts file
inquireMod.prompts();
});
} | function viewEmployeesByManager() {
//query string to concatenate the manager name and display the employees that report to that manager joining role by role id to employee, department by department id onto role, and an inner join on employee
const query = `SELECT CONCAT(e2.first_name, " ", e2.last_name) AS Manager, e1.id AS EMPID, e1.first_name AS FName, e1.last_name AS LName, role.title AS Title, department.name AS Department, role.salary AS Salary FROM employee AS e1
LEFT JOIN role on e1.role_id = role.id
LEFT JOIN department ON role.department_id = department.id
INNER JOIN employee AS e2 on e2.id=e1.manager_id
ORDER BY manager ASC;`;
//calling the connection file and passing in the query and object of user input to the MySQL database
connection.query(query, (err, res) => {
//error handling
if (err) throw err;
//generating a table from returned information
const table = cTable.getTable(res);
//sending the table to the console
console.log(table);
//returning the program to the inquirer prompts file
inquireMod.prompts();
});
} |
JavaScript | function viewEmployeesByDepartment() {
//query string to select emplyees by id, display first and last name, and concatenate manager name from employee table, title and salary from role table, department from department table,
const query = `SELECT e1.id AS EMPID, e1.first_name AS FName, e1.last_name AS LName, role.title AS Title, department.name AS Department, role.salary AS Salary, CONCAT(e2.first_name, " ", e2.last_name) AS Manager FROM employee AS e1
LEFT JOIN role on e1.role_id = role.id
LEFT JOIN department ON role.department_id = department.id
LEFT JOIN employee AS e2 on e2.id=e1.manager_id
ORDER BY department ASC;`;
//query string to concatenate the manager name and display the employees that report to that manager joining role by role id to employee, department by department id onto role, and an inner join on employee
connection.query(query, (err, res) => {
//error handling
if (err) throw err;
//generating table from returned information
const table = cTable.getTable(res);
//sending table to the console
console.log(table);
//returning the program to the inquirer prompts file
inquireMod.prompts();
});
} | function viewEmployeesByDepartment() {
//query string to select emplyees by id, display first and last name, and concatenate manager name from employee table, title and salary from role table, department from department table,
const query = `SELECT e1.id AS EMPID, e1.first_name AS FName, e1.last_name AS LName, role.title AS Title, department.name AS Department, role.salary AS Salary, CONCAT(e2.first_name, " ", e2.last_name) AS Manager FROM employee AS e1
LEFT JOIN role on e1.role_id = role.id
LEFT JOIN department ON role.department_id = department.id
LEFT JOIN employee AS e2 on e2.id=e1.manager_id
ORDER BY department ASC;`;
//query string to concatenate the manager name and display the employees that report to that manager joining role by role id to employee, department by department id onto role, and an inner join on employee
connection.query(query, (err, res) => {
//error handling
if (err) throw err;
//generating table from returned information
const table = cTable.getTable(res);
//sending table to the console
console.log(table);
//returning the program to the inquirer prompts file
inquireMod.prompts();
});
} |
JavaScript | function deleteEmployee() {
//calling inquirer
inquirer
//function to determine user inputs
.prompt([
//collecting employee id from user
{
name: "empID",
type: "input",
message: "Enter the ID of the Employee you would like to delete.",
},
])
//promise to return after user input
.then((data) => {
//setting the DELETE queery on the employee table where id is equal to the user input
const query = "DELETE FROM employee WHERE ?";
//object containing the table row title and user input
const deleteEmp = {
id: data.empID,
};
//query string to concatenate the manager name and display the employees that report to that manager joining role by role id to employee, department by department id onto role, and an inner join on employee
connection.query(query, deleteEmp, (err, res) => {
//error handling
if (err) throw err;
//console success message
console.log("This Employee has been deleted from the company records.");
//returning the program to the file containing the inquirer prompts
inquireMod.prompts();
});
});
} | function deleteEmployee() {
//calling inquirer
inquirer
//function to determine user inputs
.prompt([
//collecting employee id from user
{
name: "empID",
type: "input",
message: "Enter the ID of the Employee you would like to delete.",
},
])
//promise to return after user input
.then((data) => {
//setting the DELETE queery on the employee table where id is equal to the user input
const query = "DELETE FROM employee WHERE ?";
//object containing the table row title and user input
const deleteEmp = {
id: data.empID,
};
//query string to concatenate the manager name and display the employees that report to that manager joining role by role id to employee, department by department id onto role, and an inner join on employee
connection.query(query, deleteEmp, (err, res) => {
//error handling
if (err) throw err;
//console success message
console.log("This Employee has been deleted from the company records.");
//returning the program to the file containing the inquirer prompts
inquireMod.prompts();
});
});
} |
JavaScript | function viewCompanyBudget() {
//query logic to get Department, SUM salary from employee with joins on role table at role id, and on department table at department id from role table
const query = `SELECT department.name AS Department, SUM(role.salary) AS Dept_Budget FROM employee
LEFT JOIN role ON employee.role_id = role.id
LEFT JOIN department ON role.department_id = department.id
GROUP BY department.name;`;
//query string to concatenate the manager name and display the employees that report to that manager joining role by role id to employee, department by department id onto role, and an inner join on employee
connection.query(query, (err, res) => {
//error handling
if (err) throw err;
//generating a table from the returned information
const table = cTable.getTable(res);
//sending the table to the console
console.log(table);
//returning the program to the inquirer prompts file
inquireMod.prompts();
});
} | function viewCompanyBudget() {
//query logic to get Department, SUM salary from employee with joins on role table at role id, and on department table at department id from role table
const query = `SELECT department.name AS Department, SUM(role.salary) AS Dept_Budget FROM employee
LEFT JOIN role ON employee.role_id = role.id
LEFT JOIN department ON role.department_id = department.id
GROUP BY department.name;`;
//query string to concatenate the manager name and display the employees that report to that manager joining role by role id to employee, department by department id onto role, and an inner join on employee
connection.query(query, (err, res) => {
//error handling
if (err) throw err;
//generating a table from the returned information
const table = cTable.getTable(res);
//sending the table to the console
console.log(table);
//returning the program to the inquirer prompts file
inquireMod.prompts();
});
} |
JavaScript | function viewTotalBudgetDept() {
//calling inquirer
inquirer
//function to collect user input
.prompt([
//collecting the department name that the user wants to see budget
{
name: "deptName",
type: "input",
message:
"Please enter the name of the Department to see its budget utilization.",
},
])
//promise to do aftr inquirer prompts collect user information
.then((data) => {
//query logic to get department and sum salary from employee with joins on role at role id, and on department at department id
const query = `SELECT department.name AS Department, SUM(role.salary) AS Dept_Budget FROM employee
LEFT JOIN role on employee.role_id = role.id
LEFT JOIN department ON role.department_id = department.id
WHERE ?;`;
//object containing the table row title and user input for the request
const queryDept = {
name: data.deptName,
};
//query string to concatenate the manager name and display the employees that report to that manager joining role by role id to employee, department by department id onto role, and an inner join on employee
connection.query(query, queryDept, (err, res) => {
//error handling
if (err) throw err;
//generating a table from the returned information
const table = cTable.getTable(res);
//sending the table to the console
console.log(table);
//returning the program to the inquirer prompts file
inquireMod.prompts();
});
});
} | function viewTotalBudgetDept() {
//calling inquirer
inquirer
//function to collect user input
.prompt([
//collecting the department name that the user wants to see budget
{
name: "deptName",
type: "input",
message:
"Please enter the name of the Department to see its budget utilization.",
},
])
//promise to do aftr inquirer prompts collect user information
.then((data) => {
//query logic to get department and sum salary from employee with joins on role at role id, and on department at department id
const query = `SELECT department.name AS Department, SUM(role.salary) AS Dept_Budget FROM employee
LEFT JOIN role on employee.role_id = role.id
LEFT JOIN department ON role.department_id = department.id
WHERE ?;`;
//object containing the table row title and user input for the request
const queryDept = {
name: data.deptName,
};
//query string to concatenate the manager name and display the employees that report to that manager joining role by role id to employee, department by department id onto role, and an inner join on employee
connection.query(query, queryDept, (err, res) => {
//error handling
if (err) throw err;
//generating a table from the returned information
const table = cTable.getTable(res);
//sending the table to the console
console.log(table);
//returning the program to the inquirer prompts file
inquireMod.prompts();
});
});
} |
JavaScript | function inquirerPrompts() {
inquirer
.prompt({
name: "choice",
type: "rawlist",
message: "What would you like to accomplish today?",
//prompts to display in the command line for app functionality
choices: [
"View all Departments",
"View all Roles",
"View all Employees",
"Add new Department",
"Add new Role",
"Add new Employee",
"Update Department",
"Update Role",
"Update Employee Role",
"Update Employee Manager",
"View Employees by Manager",
"View Employees by Department",
"Delete Department",
"Delete Role",
"Delete Employee",
"View total budget by Department",
"View total budget of Department",
"Exit",
],
})
//promise function contained in separate local file
.then(answer.answers);
} | function inquirerPrompts() {
inquirer
.prompt({
name: "choice",
type: "rawlist",
message: "What would you like to accomplish today?",
//prompts to display in the command line for app functionality
choices: [
"View all Departments",
"View all Roles",
"View all Employees",
"Add new Department",
"Add new Role",
"Add new Employee",
"Update Department",
"Update Role",
"Update Employee Role",
"Update Employee Manager",
"View Employees by Manager",
"View Employees by Department",
"Delete Department",
"Delete Role",
"Delete Employee",
"View total budget by Department",
"View total budget of Department",
"Exit",
],
})
//promise function contained in separate local file
.then(answer.answers);
} |
JavaScript | function _hideAll()
{
$(".status-on").hide();
$(".status-off").hide();
$(".no-devices").hide();
$(".connected").hide();
loader.close();
/*$(".status-on").show();
$(".status-off").show();
$(".no-devices").show();
$(".connected").show();*/
} | function _hideAll()
{
$(".status-on").hide();
$(".status-off").hide();
$(".no-devices").hide();
$(".connected").hide();
loader.close();
/*$(".status-on").show();
$(".status-off").show();
$(".no-devices").show();
$(".connected").show();*/
} |
JavaScript | function _checkReconnect(message) {
if (db.get("last_device_success")) {
_reconnect(db.get("last_device_success"));
loader.set(message);
}
} | function _checkReconnect(message) {
if (db.get("last_device_success")) {
_reconnect(db.get("last_device_success"));
loader.set(message);
}
} |
JavaScript | function _swipeArea() {
var actions = {};
var actionText = {};
actions["right"] = "prev";
actions["left"] = "next";
actions["up"] = "play";
actions["down"] = "stop";
actionText["right"] = "Previous";
actionText["left"] = "Next";
actionText["up"] = "Play/Pause";
actionText["down"] = "Stop";
$(".swipearea").swipe({
swipe:function(event, direction, distance, duration, fingerCount){
if (actions[direction]) {
var messageElement = $(this).children('.swipearea__message');
messageElement.text(actionText[direction]);
window.clearTimeout(window.messageTimeout);
window.messageTimeout = window.setTimeout(function(){
messageElement.text('Swipe Area');
}, 1000);
bth.action(actions[direction]);
}
},
threshold: $(".swipearea").hasClass('on') ? 80 : 0
});
} | function _swipeArea() {
var actions = {};
var actionText = {};
actions["right"] = "prev";
actions["left"] = "next";
actions["up"] = "play";
actions["down"] = "stop";
actionText["right"] = "Previous";
actionText["left"] = "Next";
actionText["up"] = "Play/Pause";
actionText["down"] = "Stop";
$(".swipearea").swipe({
swipe:function(event, direction, distance, duration, fingerCount){
if (actions[direction]) {
var messageElement = $(this).children('.swipearea__message');
messageElement.text(actionText[direction]);
window.clearTimeout(window.messageTimeout);
window.messageTimeout = window.setTimeout(function(){
messageElement.text('Swipe Area');
}, 1000);
bth.action(actions[direction]);
}
},
threshold: $(".swipearea").hasClass('on') ? 80 : 0
});
} |
JavaScript | function _activate(event) {
event.preventDefault();
_previousTime = _startTime;
_startTime = Date.now();
var getXY = pointerPositionXY(event);
//console.log(_pointers);
_startX = getXY.x;
_startY = getXY.y;
} | function _activate(event) {
event.preventDefault();
_previousTime = _startTime;
_startTime = Date.now();
var getXY = pointerPositionXY(event);
//console.log(_pointers);
_startX = getXY.x;
_startY = getXY.y;
} |
JavaScript | function _track(event) {
_dragging = true;
_lastDrag = Date.now();
event.preventDefault();
// Get the current position, and the distance we have since dragged
var getXY = pointerPositionXY(event);
_endX = getXY.x;
_endY = getXY.y;
_getDistance = _distance();
// The dragging logic, slow v.s. tapping v.s. dragging
_tapping = (_getDistance.x < 1.2 && _getDistance.x > -1.2 && _getDistance.y < 1.2 && _getDistance.y > -1.2);
_slow = (_getDistance.x < 3 && _getDistance.x > -3 && _getDistance.y < 3 && _getDistance.y > -3);
dragged = (!_tapping); // allow some more space before dragging
console.log("dragged:", dragged);
// console.log(
// "SLOW:", _slow,
// "x:", _getDistance.x,
// "y:", _getDistance.y,
// "DB:", db.get('mouseSensitivity')
// );
if (dragged && !_getDistance.x && !_getDistance.y) {
_lastDrag = Date.now();
}
if (!_getDistance.x && !_getDistance.y) {
//console.debug("EMPTY COORDS!");
_tapping = true;
_dragging = false;
}
// Send the command via the BTH
bth.action(
JSON.stringify({
action: "mouse-move",
x: (_slow) ? _getDistance.x : ( _getDistance.x * Number(db.get('mouseSensitivity')) ),
y: (_slow) ? _getDistance.y : ( _getDistance.y * Number(db.get('mouseSensitivity')) )
})
);
// Set the start to the current positions. This ensures that movements are relative
_startX = _endX;
_startY = _endY;
} | function _track(event) {
_dragging = true;
_lastDrag = Date.now();
event.preventDefault();
// Get the current position, and the distance we have since dragged
var getXY = pointerPositionXY(event);
_endX = getXY.x;
_endY = getXY.y;
_getDistance = _distance();
// The dragging logic, slow v.s. tapping v.s. dragging
_tapping = (_getDistance.x < 1.2 && _getDistance.x > -1.2 && _getDistance.y < 1.2 && _getDistance.y > -1.2);
_slow = (_getDistance.x < 3 && _getDistance.x > -3 && _getDistance.y < 3 && _getDistance.y > -3);
dragged = (!_tapping); // allow some more space before dragging
console.log("dragged:", dragged);
// console.log(
// "SLOW:", _slow,
// "x:", _getDistance.x,
// "y:", _getDistance.y,
// "DB:", db.get('mouseSensitivity')
// );
if (dragged && !_getDistance.x && !_getDistance.y) {
_lastDrag = Date.now();
}
if (!_getDistance.x && !_getDistance.y) {
//console.debug("EMPTY COORDS!");
_tapping = true;
_dragging = false;
}
// Send the command via the BTH
bth.action(
JSON.stringify({
action: "mouse-move",
x: (_slow) ? _getDistance.x : ( _getDistance.x * Number(db.get('mouseSensitivity')) ),
y: (_slow) ? _getDistance.y : ( _getDistance.y * Number(db.get('mouseSensitivity')) )
})
);
// Set the start to the current positions. This ensures that movements are relative
_startX = _endX;
_startY = _endY;
} |
JavaScript | function _complete(event){
event.preventDefault();
_handleClicks();
if (_dragging) {
_dragging = false;
}
} | function _complete(event){
event.preventDefault();
_handleClicks();
if (_dragging) {
_dragging = false;
}
} |
JavaScript | function _distance() {
var out = { x:0, y:0 };
if (_dragging) {
out.x = _endX - _startX;
out.y = _endY - _startY;
}
return out;
} | function _distance() {
var out = { x:0, y:0 };
if (_dragging) {
out.x = _endX - _startX;
out.y = _endY - _startY;
}
return out;
} |
JavaScript | function promiseOf(promise) {
return function control(execution) {
let succeed = value => execution.resume(value);
let fail = err => execution.throw(err);
let noop = x => x;
promise.then(value => succeed(value)).catch(error => fail(error));
// this execution has passed out of scope, so we don't care
// what happened to the promise, so make the callbacks noops.
// this effectively "unsubscribes" to the promise.
return () => succeed = fail = noop;
};
} | function promiseOf(promise) {
return function control(execution) {
let succeed = value => execution.resume(value);
let fail = err => execution.throw(err);
let noop = x => x;
promise.then(value => succeed(value)).catch(error => fail(error));
// this execution has passed out of scope, so we don't care
// what happened to the promise, so make the callbacks noops.
// this effectively "unsubscribes" to the promise.
return () => succeed = fail = noop;
};
} |
JavaScript | function recieveAllEvents() {
var addedEvents;
addedEvents = document.getElementsByClassName("calendar-event");
for (let i = 0; i < addedEvents.length; i++) {
addedEvents[i].addEventListener("click", showDetails);
}
} | function recieveAllEvents() {
var addedEvents;
addedEvents = document.getElementsByClassName("calendar-event");
for (let i = 0; i < addedEvents.length; i++) {
addedEvents[i].addEventListener("click", showDetails);
}
} |
JavaScript | function createMonth(month) {
for (let j = monthBeginning(currentMonth); j > 0; j--) {
days.innerHTML += `<div class='every_date previous_month_date'>${
lastDay - (j - 1)
}</div>`;
}
for (let i = 1; i <= 42; i++) {
if (
i === currentDay &&
currentMonth === new Date().getMonth() &&
currentYear === new Date().getFullYear()
) {
days.innerHTML += `<div class='every_date today_date' id='${i}_${currentMonth}_${currentYear}' data-date='every_date'>
<p class="day_number">${i}</p>
<button class="plus_button" data-button='plus-button'>+</button>
</div>`;
} else if (i <= lastDay) {
days.innerHTML += `<div class='every_date current_month_date' data-date='every_date' id ="${i}_${currentMonth}_${currentYear}">
<p class="day_number">${i}</p>
<button class="plus_button" data-button='plus-button'>+</button>
</div>`;
} else if (i <= lastDay + 1) {
for (let j = 1; j <= lastCell; j++)
days.innerHTML += `<div class='every_date next_month_date'>${j}</div>`;
}
}
} | function createMonth(month) {
for (let j = monthBeginning(currentMonth); j > 0; j--) {
days.innerHTML += `<div class='every_date previous_month_date'>${
lastDay - (j - 1)
}</div>`;
}
for (let i = 1; i <= 42; i++) {
if (
i === currentDay &&
currentMonth === new Date().getMonth() &&
currentYear === new Date().getFullYear()
) {
days.innerHTML += `<div class='every_date today_date' id='${i}_${currentMonth}_${currentYear}' data-date='every_date'>
<p class="day_number">${i}</p>
<button class="plus_button" data-button='plus-button'>+</button>
</div>`;
} else if (i <= lastDay) {
days.innerHTML += `<div class='every_date current_month_date' data-date='every_date' id ="${i}_${currentMonth}_${currentYear}">
<p class="day_number">${i}</p>
<button class="plus_button" data-button='plus-button'>+</button>
</div>`;
} else if (i <= lastDay + 1) {
for (let j = 1; j <= lastCell; j++)
days.innerHTML += `<div class='every_date next_month_date'>${j}</div>`;
}
}
} |
JavaScript | function followingMonth() {
if (currentMonth !== 11) {
currentMonth++;
} else {
currentMonth = 0;
currentYear++;
}
printNewMonth();
} | function followingMonth() {
if (currentMonth !== 11) {
currentMonth++;
} else {
currentMonth = 0;
currentYear++;
}
printNewMonth();
} |
JavaScript | function pinv(x) {
// convert js array to nd array
const ndX = nd.array(x);
// compute SVD NOTE: nd svd automatically remove the zero components in the singular matrix
const xSVD = nd.la.svd_decomp(ndX);
const { 0: lSVec, 1: singularVal, 2: rSVec } = xSVD;
// compute the inverse of singularVec
const singularDiag = nd.la.diag_mat(singularVal);
const modDiag = singularDiag.forElems((val, i, j) => {
if (i === j) singularDiag.set([i, j], 1 / val);
});
// now construct back the matrix in order to get our matrix psudo-inverse.
const xInv = nd.la.matmul(lSVec, singularDiag, rSVec);
return convert2dArray(xInv);
} | function pinv(x) {
// convert js array to nd array
const ndX = nd.array(x);
// compute SVD NOTE: nd svd automatically remove the zero components in the singular matrix
const xSVD = nd.la.svd_decomp(ndX);
const { 0: lSVec, 1: singularVal, 2: rSVec } = xSVD;
// compute the inverse of singularVec
const singularDiag = nd.la.diag_mat(singularVal);
const modDiag = singularDiag.forElems((val, i, j) => {
if (i === j) singularDiag.set([i, j], 1 / val);
});
// now construct back the matrix in order to get our matrix psudo-inverse.
const xInv = nd.la.matmul(lSVec, singularDiag, rSVec);
return convert2dArray(xInv);
} |
JavaScript | function tfMap(matrix, callbackFn) {
const array = matrix.arraySync();
const modArray = array.map(cRow => cVal => {
callbackFn(cVal);
});
// return the modified tf.tensor
return tf.tensor(modArray);
} | function tfMap(matrix, callbackFn) {
const array = matrix.arraySync();
const modArray = array.map(cRow => cVal => {
callbackFn(cVal);
});
// return the modified tf.tensor
return tf.tensor(modArray);
} |
JavaScript | function tfSort(vector) {
if (vector.shape[1] > 1)
throw new Error(" input must be of shape nx1 or 1xn.");
const array = tensor.flattten().arraySync();
const sortedArray = quickSort(array);
// return the sorted tf.tensor;
return tf.tensor(sortedArray);
} | function tfSort(vector) {
if (vector.shape[1] > 1)
throw new Error(" input must be of shape nx1 or 1xn.");
const array = tensor.flattten().arraySync();
const sortedArray = quickSort(array);
// return the sorted tf.tensor;
return tf.tensor(sortedArray);
} |
JavaScript | function costFunction(type) {
if (type === "mse") {
// mean-squared-error (yPred - y)**2
return function(y, yPred) {
return tf.sum(tf.pow(tf.sub(yPred, y), 2));
};
}
// add other cost function like R^2 etc.
} | function costFunction(type) {
if (type === "mse") {
// mean-squared-error (yPred - y)**2
return function(y, yPred) {
return tf.sum(tf.pow(tf.sub(yPred, y), 2));
};
}
// add other cost function like R^2 etc.
} |
JavaScript | function costFnDerivatives(type) {
if (type === "mse") {
return function(x, y, yPred) {
// d/dx of MSE w.r.t 'w' : (yPred - y)x
return tf.matMul(x.transpose(), tf.sub(yPred, y));
};
}
} | function costFnDerivatives(type) {
if (type === "mse") {
return function(x, y, yPred) {
// d/dx of MSE w.r.t 'w' : (yPred - y)x
return tf.matMul(x.transpose(), tf.sub(yPred, y));
};
}
} |
JavaScript | function normalizeData(data, unitVariance=0) {
let meanCenteredData = data.sub( data.mean(axis = 0) );
if(!unitVariance)
return meanCenteredData;
const stdev = normalizeData(meanCenteredData, 0).pow(2).mean().sqrt();
// z-score
const standardForm = meanCenteredData.div(stdev);
return standardForm;
} | function normalizeData(data, unitVariance=0) {
let meanCenteredData = data.sub( data.mean(axis = 0) );
if(!unitVariance)
return meanCenteredData;
const stdev = normalizeData(meanCenteredData, 0).pow(2).mean().sqrt();
// z-score
const standardForm = meanCenteredData.div(stdev);
return standardForm;
} |
JavaScript | function genSpan(A, fac) {
// first... convert it into an orthogonal matrix
const Aortho = tf.linalg.gramSchmidt(A.transpose()).transpose();
const p1 = Aortho.mul(fac);
const p2 = Aortho.mul(-fac);
// now connect p1 and p2 to form a hyperplane
const combined = p1.concat(p2, (axis = 1));
return {
x: combined.slice([0, 0], [1, -1]),
y:
combined.shape[0] >= 2
? combined.slice([1, 0], [1, -1])
: tf.zeros([1, combined.shape[0]]),
z:
combined.shape[0] === 3
? combined.slice([2, 0], [1, -1])
: tf.zeros([1, combined.shape[0]])
};
} | function genSpan(A, fac) {
// first... convert it into an orthogonal matrix
const Aortho = tf.linalg.gramSchmidt(A.transpose()).transpose();
const p1 = Aortho.mul(fac);
const p2 = Aortho.mul(-fac);
// now connect p1 and p2 to form a hyperplane
const combined = p1.concat(p2, (axis = 1));
return {
x: combined.slice([0, 0], [1, -1]),
y:
combined.shape[0] >= 2
? combined.slice([1, 0], [1, -1])
: tf.zeros([1, combined.shape[0]]),
z:
combined.shape[0] === 3
? combined.slice([2, 0], [1, -1])
: tf.zeros([1, combined.shape[0]])
};
} |
JavaScript | function tfDiag(X) {
if (!X.shape[1]) {
X = X.expandDims(1);
} else {
if (X.shape[0] === X.shape[1]){
return X.mul( tf.eye(X.shape[0],X.shape[0])).matMul(tf.ones([X.shape[0],1]))
}
if(X.shape[1] !== 1)
{
throw new Error(
`input must either be of shape [n,1] or of size [n,n] but given ${X.shape}`
);
}
}
return X.mul(tf.eye(X.shape[0]));
} | function tfDiag(X) {
if (!X.shape[1]) {
X = X.expandDims(1);
} else {
if (X.shape[0] === X.shape[1]){
return X.mul( tf.eye(X.shape[0],X.shape[0])).matMul(tf.ones([X.shape[0],1]))
}
if(X.shape[1] !== 1)
{
throw new Error(
`input must either be of shape [n,1] or of size [n,n] but given ${X.shape}`
);
}
}
return X.mul(tf.eye(X.shape[0]));
} |
JavaScript | function trainTestSplit(X, Y, percent=0.8, shuffle=true) {
/**
* TODO:-
* 1. split the data according to there corresponding classes
* 2. shuffle the data points
* 3. take _percent_ data as a training data and rest of them as test data.
* 4. if _percent.length_ === 2 then split the test data into _percepnt[1]_ as cross-validation set.
* 5. concat all the classwise X data for all the 3 sets (train,cross-validation and test)
* 6. return all the 3 sets.
*/
percent = percent.length ? percent : [percent]; // if the percent is just a number then convert it into array of length 1
let totalPercent = 0;
for(let i=0;i< percent;i++)
totalPercent += percent[i]
if (totalPercent >= 1.0)
throw new Error('the total percent must be equal to 1')
let classwiseX = X.concat(Y, axis=1);
// * 2. shuffle the data points of each class
if (shuffle){
const currClassXArray = classwiseX.arraySync();
tf.util.shuffle(currClassXArray);
classwiseX = tf.tensor(currClassXArray);
}
// * 3. take _percent_ data as a training data and rest of them as test data.
let classwiseXTrain = tf.tensor([]);
let classwiseXCV = tf.tensor([]);
let classwiseXTest = tf.tensor([]);
const percentLength = Math.floor(classwiseX.shape[0] * percent[0]);
const percentCVLength = Math.floor(classwiseX.shape[0] * percent[1]);
classwiseXTrain = classwiseXTrain.concat(
classwiseX.slice([0, 0], [percentLength, -1])
);
const otherData = classwiseX.slice([percentLength, 0], [-1, -1]);
// * 4. if _percent.length_ === 2 then split the test data into _percepnt[1]_ as cross-validation set.
if (percent.length === 2) {
classwiseXCV = classwiseXCV.concat(
otherData.slice([0, 0], [percentCVLength, -1])
);
}
classwiseXTest = classwiseXTest.concat(
classwiseX.slice([((percent.length===2)?percentCVLength : percentLength), 0], [-1, -1])
);
// * 6. return all the sets.
// add train set
const retVal = [{
x: classwiseXTrain.slice([0, 0], [-1, X.shape[1]]),
y: classwiseXTrain.slice([0,X.shape[1]], [-1, -1])
}];
if (percent.length === 2) {
// include corss-validation set as well
retVal.push({
x: classwiseXCV.slice([0, 0], [-1, X.shape[1]]),
y: classwiseXCV.slice([0,X.shape[1]], [-1, -1])
});
}
// add test set
// if the percent is 1.0 then don't include the test set.
if (percent[0] === 1.0)
return retVal
retVal.push({
x: classwiseXTest.slice([0, 0], [-1, X.shape[1]]),
y: classwiseXTest.slice([0,X.shape[1]], [-1, -1])
});
return retVal;
} | function trainTestSplit(X, Y, percent=0.8, shuffle=true) {
/**
* TODO:-
* 1. split the data according to there corresponding classes
* 2. shuffle the data points
* 3. take _percent_ data as a training data and rest of them as test data.
* 4. if _percent.length_ === 2 then split the test data into _percepnt[1]_ as cross-validation set.
* 5. concat all the classwise X data for all the 3 sets (train,cross-validation and test)
* 6. return all the 3 sets.
*/
percent = percent.length ? percent : [percent]; // if the percent is just a number then convert it into array of length 1
let totalPercent = 0;
for(let i=0;i< percent;i++)
totalPercent += percent[i]
if (totalPercent >= 1.0)
throw new Error('the total percent must be equal to 1')
let classwiseX = X.concat(Y, axis=1);
// * 2. shuffle the data points of each class
if (shuffle){
const currClassXArray = classwiseX.arraySync();
tf.util.shuffle(currClassXArray);
classwiseX = tf.tensor(currClassXArray);
}
// * 3. take _percent_ data as a training data and rest of them as test data.
let classwiseXTrain = tf.tensor([]);
let classwiseXCV = tf.tensor([]);
let classwiseXTest = tf.tensor([]);
const percentLength = Math.floor(classwiseX.shape[0] * percent[0]);
const percentCVLength = Math.floor(classwiseX.shape[0] * percent[1]);
classwiseXTrain = classwiseXTrain.concat(
classwiseX.slice([0, 0], [percentLength, -1])
);
const otherData = classwiseX.slice([percentLength, 0], [-1, -1]);
// * 4. if _percent.length_ === 2 then split the test data into _percepnt[1]_ as cross-validation set.
if (percent.length === 2) {
classwiseXCV = classwiseXCV.concat(
otherData.slice([0, 0], [percentCVLength, -1])
);
}
classwiseXTest = classwiseXTest.concat(
classwiseX.slice([((percent.length===2)?percentCVLength : percentLength), 0], [-1, -1])
);
// * 6. return all the sets.
// add train set
const retVal = [{
x: classwiseXTrain.slice([0, 0], [-1, X.shape[1]]),
y: classwiseXTrain.slice([0,X.shape[1]], [-1, -1])
}];
if (percent.length === 2) {
// include corss-validation set as well
retVal.push({
x: classwiseXCV.slice([0, 0], [-1, X.shape[1]]),
y: classwiseXCV.slice([0,X.shape[1]], [-1, -1])
});
}
// add test set
// if the percent is 1.0 then don't include the test set.
if (percent[0] === 1.0)
return retVal
retVal.push({
x: classwiseXTest.slice([0, 0], [-1, X.shape[1]]),
y: classwiseXTest.slice([0,X.shape[1]], [-1, -1])
});
return retVal;
} |
JavaScript | function class2OneHot(classTensor){
const nClasses = tf.max(classTensor);
let oneHotTensor = tf.tensor([]);
for(let i=0;i< nClasses;i++){
const thCenter = tf.sub( i,( classTensor ) ).pow(2);
const cClass = tf.sub(1, tf.clipByValue(tf.mul(thCenter, 10000000 ), 0, 1 ));
if( i === 0){
oneHot2Class = cClass;
continue;
}
oneHotTensor = oneHot2Class.concat(cClass, axis=1);
}
return oneHotTensor;
} | function class2OneHot(classTensor){
const nClasses = tf.max(classTensor);
let oneHotTensor = tf.tensor([]);
for(let i=0;i< nClasses;i++){
const thCenter = tf.sub( i,( classTensor ) ).pow(2);
const cClass = tf.sub(1, tf.clipByValue(tf.mul(thCenter, 10000000 ), 0, 1 ));
if( i === 0){
oneHot2Class = cClass;
continue;
}
oneHotTensor = oneHot2Class.concat(cClass, axis=1);
}
return oneHotTensor;
} |
JavaScript | function tensorMap(tensor, shape, func=(n,i, d)=>{/**console.log(n,i,d); */ return n}, index=0){
const len = tensor.length;
for(let i=0;i<len;i++){
// indexNum +=1;
if(!(tensor[i][0])){
tensor[i] = func(tensor[i], index2Coords(index, shape));
index++;
}
else{
const retVal = tensorMap(tensor[i], shape, func, index);
tensor[i] = retVal.tensor; //[0];
index = retVal.index
}
}
return {tensor: tensor,index: index}; // TODO: understand why we can't just return the tensor array. by using chrom dev tools
} | function tensorMap(tensor, shape, func=(n,i, d)=>{/**console.log(n,i,d); */ return n}, index=0){
const len = tensor.length;
for(let i=0;i<len;i++){
// indexNum +=1;
if(!(tensor[i][0])){
tensor[i] = func(tensor[i], index2Coords(index, shape));
index++;
}
else{
const retVal = tensorMap(tensor[i], shape, func, index);
tensor[i] = retVal.tensor; //[0];
index = retVal.index
}
}
return {tensor: tensor,index: index}; // TODO: understand why we can't just return the tensor array. by using chrom dev tools
} |
JavaScript | function coord2Index(coord,shape){
const size = shape.reduce((accumulator,currentValue)=> accumulator*currentValue, 1);
let index = 0;
let divSum = shape[0];
for(let i = 0;i<shape.length-1;i++){
index += (size/divSum)*coord[i];
divSum += shape[i];
}
return index+coord[coord.length -1];
} | function coord2Index(coord,shape){
const size = shape.reduce((accumulator,currentValue)=> accumulator*currentValue, 1);
let index = 0;
let divSum = shape[0];
for(let i = 0;i<shape.length-1;i++){
index += (size/divSum)*coord[i];
divSum += shape[i];
}
return index+coord[coord.length -1];
} |
JavaScript | function tfDet(tensor){
// based on this article: https://integratedmlai.com/find-the-determinant-of-a-matrix-with-pure-python-without-numpy-or-scipy/
if (tensor.shape.length > 2)throw new Error('tfDet only support 2d-tensors');
// if the matrix is singular then the determinant is 0
if(tensor.shape[0] !== tensor.shape[1])return 0;
const n = tensor.shape[0];
const Matrix = tensor.arraySync();
for(let i=0;i< n;i++){
for(let j=i+1;j<n;j++){
// id diagonal is zero then change it to a slight non-zero value so that we don't have to div by zero in future calculation
if(Matrix[i][i] === 0){
Matrix[i][i] = 1.0e-18;
}
const currRowFac = Matrix[j][i]/Matrix[i][i];
for(let k=0; k<n;k++){
Matrix[j][k] = Matrix[j][k] - currRowFac * Matrix[i][k];
}
}
}
let determinant = 1.0;
for(let i=0;i<n;i++){
determinant *= Matrix[i][i]
}
return tf.tensor(determinant);
} | function tfDet(tensor){
// based on this article: https://integratedmlai.com/find-the-determinant-of-a-matrix-with-pure-python-without-numpy-or-scipy/
if (tensor.shape.length > 2)throw new Error('tfDet only support 2d-tensors');
// if the matrix is singular then the determinant is 0
if(tensor.shape[0] !== tensor.shape[1])return 0;
const n = tensor.shape[0];
const Matrix = tensor.arraySync();
for(let i=0;i< n;i++){
for(let j=i+1;j<n;j++){
// id diagonal is zero then change it to a slight non-zero value so that we don't have to div by zero in future calculation
if(Matrix[i][i] === 0){
Matrix[i][i] = 1.0e-18;
}
const currRowFac = Matrix[j][i]/Matrix[i][i];
for(let k=0; k<n;k++){
Matrix[j][k] = Matrix[j][k] - currRowFac * Matrix[i][k];
}
}
}
let determinant = 1.0;
for(let i=0;i<n;i++){
determinant *= Matrix[i][i]
}
return tf.tensor(determinant);
} |
JavaScript | function tfEigen(tensor, epsilon=.0001, maxItrs=10000){
function shiftingRedirection(M, eigenValue, eigenVector){
/*
Apply shifting redirection to the matrix to compute next eigenpair: M = M-lambda v
*/
return (M.sub(eigenValue.mul(tf.matMul(eigenVector.transpose(), eigenVector))));
}
function powerMethod(M, epsilon=0.0001, maxItrs=10000){
// initialize
let eigenVecArray = (new Array(maxItrs)).fill(null);
eigenVecArray[0] = tf.randomNormal([M.shape[0], 1])
eigenVecArray[1] = tf.matMul(M, eigenVecArray[0]).div(tf.norm(tf.matMul(M, eigenVecArray[0])));
let count = 1;
while( ((tf.norm(eigenVecArray[count].sub(eigenVecArray[count-1])).flatten().arraySync()[0]) > epsilon) && (count < maxItrs)){
// Computing eigenvector
eigenVecArray[count+1] = tf.matMul(M, eigenVecArray[count]).div(tf.norm(tf.matMul(M, eigenVecArray[count])));
count++;
}
// Compute eigenValue
const eigenValue = tf.matMul(tf.matMul(eigenVecArray[count].transpose(), M), eigenVecArray[count]);
return {eigenVec: eigenVecArray[count], eigenVal: eigenValue}
}
function eigenPairs(M, epsilon= 0.00001, maxItrs = 100){
// initialize
let eigenVectors = (new Array(M.shape[0])).fill(null);
let eigenValues = tf.zeros(M.shape).arraySync();
for(let i=0;i< M.shape[0]; i++){
const { eigenVec : currEigenVec , eigenVal : currEigenVal } = powerMethod(M, epsilon, maxItrs);
eigenVectors[i] = currEigenVec.flatten().arraySync();
eigenValues[i][i] = currEigenVal.flatten().arraySync()[0];
// remove the currently calculated eigen vector direction from the original matrix so that it doesn't get recalculated again
M = shiftingRedirection(M, currEigenVec, currEigenVal);
}
return {eigenVectors: tf.tensor(eigenVectors), eigenValues: tf.tensor(eigenValues)};
}
if (tensor.shape.length > 2)
throw new Error('input must be a 2-dimensional tensor(a.k.a matrix) given a tensor of shape: '+tensor.shape);
if (( tensor.shape[0] != tensor.shape[1]))
throw new Error('input must be a square matrix, given a matrix of size: '+ tensor.shape)
return eigenPairs(tensor,epsilon, maxItrs)
} | function tfEigen(tensor, epsilon=.0001, maxItrs=10000){
function shiftingRedirection(M, eigenValue, eigenVector){
/*
Apply shifting redirection to the matrix to compute next eigenpair: M = M-lambda v
*/
return (M.sub(eigenValue.mul(tf.matMul(eigenVector.transpose(), eigenVector))));
}
function powerMethod(M, epsilon=0.0001, maxItrs=10000){
// initialize
let eigenVecArray = (new Array(maxItrs)).fill(null);
eigenVecArray[0] = tf.randomNormal([M.shape[0], 1])
eigenVecArray[1] = tf.matMul(M, eigenVecArray[0]).div(tf.norm(tf.matMul(M, eigenVecArray[0])));
let count = 1;
while( ((tf.norm(eigenVecArray[count].sub(eigenVecArray[count-1])).flatten().arraySync()[0]) > epsilon) && (count < maxItrs)){
// Computing eigenvector
eigenVecArray[count+1] = tf.matMul(M, eigenVecArray[count]).div(tf.norm(tf.matMul(M, eigenVecArray[count])));
count++;
}
// Compute eigenValue
const eigenValue = tf.matMul(tf.matMul(eigenVecArray[count].transpose(), M), eigenVecArray[count]);
return {eigenVec: eigenVecArray[count], eigenVal: eigenValue}
}
function eigenPairs(M, epsilon= 0.00001, maxItrs = 100){
// initialize
let eigenVectors = (new Array(M.shape[0])).fill(null);
let eigenValues = tf.zeros(M.shape).arraySync();
for(let i=0;i< M.shape[0]; i++){
const { eigenVec : currEigenVec , eigenVal : currEigenVal } = powerMethod(M, epsilon, maxItrs);
eigenVectors[i] = currEigenVec.flatten().arraySync();
eigenValues[i][i] = currEigenVal.flatten().arraySync()[0];
// remove the currently calculated eigen vector direction from the original matrix so that it doesn't get recalculated again
M = shiftingRedirection(M, currEigenVec, currEigenVal);
}
return {eigenVectors: tf.tensor(eigenVectors), eigenValues: tf.tensor(eigenValues)};
}
if (tensor.shape.length > 2)
throw new Error('input must be a 2-dimensional tensor(a.k.a matrix) given a tensor of shape: '+tensor.shape);
if (( tensor.shape[0] != tensor.shape[1]))
throw new Error('input must be a square matrix, given a matrix of size: '+ tensor.shape)
return eigenPairs(tensor,epsilon, maxItrs)
} |
JavaScript | function Factor(name, potentials){
// Inheriting the methods from Node Object
Node.call(this, name);
this.potential = potentials;
} | function Factor(name, potentials){
// Inheriting the methods from Node Object
Node.call(this, name);
this.potential = potentials;
} |
JavaScript | function generateFakeObject(maxItems = 10, gridHeight = 4000, gridWidth = 4000) {
const fakeElements = [];
// Generates a random value, it's a helper.
const random = (max=1, min=0) => Math.floor(Math.random()*(max - min) + min);
// generate X elements ( based on maxItems param ) filled with properties:
// - id, self explanatory ;), the ID(number) that identifies the object.
// - zIndex, the z (visual deepth) coord, random( range 0...10 ).
// - top/left, the x/y coord position in grid, random( range 0...max body width ).
// - width / height, the element dimension area, random( range( minSize...maxSize) ).
for(let acc=0; acc < maxItems; acc++){
fakeElements[acc] = {
id: acc,
zIndex: random(10,0),
top: random(3800),
left: random(3800),
width: 100,
height: 100,
};
}
return fakeElements;
} | function generateFakeObject(maxItems = 10, gridHeight = 4000, gridWidth = 4000) {
const fakeElements = [];
// Generates a random value, it's a helper.
const random = (max=1, min=0) => Math.floor(Math.random()*(max - min) + min);
// generate X elements ( based on maxItems param ) filled with properties:
// - id, self explanatory ;), the ID(number) that identifies the object.
// - zIndex, the z (visual deepth) coord, random( range 0...10 ).
// - top/left, the x/y coord position in grid, random( range 0...max body width ).
// - width / height, the element dimension area, random( range( minSize...maxSize) ).
for(let acc=0; acc < maxItems; acc++){
fakeElements[acc] = {
id: acc,
zIndex: random(10,0),
top: random(3800),
left: random(3800),
width: 100,
height: 100,
};
}
return fakeElements;
} |
JavaScript | function debounce(fn, delay, scope) {
let timeout;
return function () {
const context = scope || this
const args = arguments;
const later = function () {
timeout = null;
fn.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, delay);
};
} | function debounce(fn, delay, scope) {
let timeout;
return function () {
const context = scope || this
const args = arguments;
const later = function () {
timeout = null;
fn.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, delay);
};
} |
JavaScript | function throttle(fn, delay, scope) {
delay || (delay = 250);
let last, deferTimer;
return function () {
const context = scope || this;
const now = +new Date
const args = arguments;
if (last && now < last + delay) {
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, delay);
} else {
last = now;
fn.apply(context, args);
}
};
} | function throttle(fn, delay, scope) {
delay || (delay = 250);
let last, deferTimer;
return function () {
const context = scope || this;
const now = +new Date
const args = arguments;
if (last && now < last + delay) {
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, delay);
} else {
last = now;
fn.apply(context, args);
}
};
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.