language
stringclasses 6
values | original_string
stringlengths 25
887k
| text
stringlengths 25
887k
|
---|---|---|
JavaScript | function showRepos(currentUser, cb){
var repoDiv = document.getElementById('repos');
//Load spinner in the repository div while we wait
var spinner = loadSpinner(repoDiv);
var getRepos = user.userRepos(currentUser,function(err, repos){
var select = document.getElementById('repo-list');
// Populate the select list with the users' repos.
if(repos.length<1){
select.options.add(new Option('No repositories found'))
}
else{
for(var i=0; i < repos.length; i++){
var repo = repos[i].name;
select.options.add(new Option(repo))
}
}
spinner.stop();
});
} | function showRepos(currentUser, cb){
var repoDiv = document.getElementById('repos');
//Load spinner in the repository div while we wait
var spinner = loadSpinner(repoDiv);
var getRepos = user.userRepos(currentUser,function(err, repos){
var select = document.getElementById('repo-list');
// Populate the select list with the users' repos.
if(repos.length<1){
select.options.add(new Option('No repositories found'))
}
else{
for(var i=0; i < repos.length; i++){
var repo = repos[i].name;
select.options.add(new Option(repo))
}
}
spinner.stop();
});
} |
JavaScript | accountSearch(start_symbol, limit = 50) {
let uid = `${start_symbol}_${limit}}`;
return (dispatch) => {
if (!accountSearch[uid]) {
accountSearch[uid] = true;
return AccountApi.lookupAccounts(start_symbol, limit)
.then(result => {
accountSearch[uid] = false;
dispatch({accounts: result, searchTerm: start_symbol});
});
}
};
} | accountSearch(start_symbol, limit = 50) {
let uid = `${start_symbol}_${limit}}`;
return (dispatch) => {
if (!accountSearch[uid]) {
accountSearch[uid] = true;
return AccountApi.lookupAccounts(start_symbol, limit)
.then(result => {
accountSearch[uid] = false;
dispatch({accounts: result, searchTerm: start_symbol});
});
}
};
} |
JavaScript | transfer(from_account, to_account, amount, asset, memo, propose_account = null, fee_asset_id = "1.3.0") {
// Set the fee asset to use
fee_asset_id = accountUtils.getFinalFeeAsset(propose_account || from_account, "transfer", fee_asset_id);
try {
return (dispatch) => {
return ApplicationApi.transfer({
from_account, to_account, amount, asset, memo, propose_account, fee_asset_id
}).then(result => {
// console.log( "transfer result: ", result )
dispatch(result);
});
};
} catch (error) {
console.log("[AccountActions.js:90] ----- transfer error ----->", error);
return new Promise((resolve, reject) => {
reject(error);
});
}
} | transfer(from_account, to_account, amount, asset, memo, propose_account = null, fee_asset_id = "1.3.0") {
// Set the fee asset to use
fee_asset_id = accountUtils.getFinalFeeAsset(propose_account || from_account, "transfer", fee_asset_id);
try {
return (dispatch) => {
return ApplicationApi.transfer({
from_account, to_account, amount, asset, memo, propose_account, fee_asset_id
}).then(result => {
// console.log( "transfer result: ", result )
dispatch(result);
});
};
} catch (error) {
console.log("[AccountActions.js:90] ----- transfer error ----->", error);
return new Promise((resolve, reject) => {
reject(error);
});
}
} |
JavaScript | createAccount(
account_name,
registrar,
referrer,
referrer_percent,
refcode
) {
return (dispatch) => {
return WalletActions.createAccount(
account_name,
registrar,
referrer,
referrer_percent,
refcode
).then( () => {
dispatch(account_name);
return account_name;
});
};
} | createAccount(
account_name,
registrar,
referrer,
referrer_percent,
refcode
) {
return (dispatch) => {
return WalletActions.createAccount(
account_name,
registrar,
referrer,
referrer_percent,
refcode
).then( () => {
dispatch(account_name);
return account_name;
});
};
} |
JavaScript | upgradeAccount(account_id, lifetime) {
// Set the fee asset to use
let fee_asset_id = accountUtils.getFinalFeeAsset(account_id, "account_upgrade");
var tr = WalletApi.new_transaction();
tr.add_type_operation("account_upgrade", {
"fee": {
amount: 0,
asset_id: fee_asset_id
},
"account_to_upgrade": account_id,
"upgrade_to_lifetime_member": lifetime
});
return WalletDb.process_transaction(tr, null, true);
} | upgradeAccount(account_id, lifetime) {
// Set the fee asset to use
let fee_asset_id = accountUtils.getFinalFeeAsset(account_id, "account_upgrade");
var tr = WalletApi.new_transaction();
tr.add_type_operation("account_upgrade", {
"fee": {
amount: 0,
asset_id: fee_asset_id
},
"account_to_upgrade": account_id,
"upgrade_to_lifetime_member": lifetime
});
return WalletDb.process_transaction(tr, null, true);
} |
JavaScript | function handleClickOutside(event) {
if (ref.current && !ref.current.contains(event.target)) {
funcToExecute();
// alert("You clicked outside of me!");
}
} | function handleClickOutside(event) {
if (ref.current && !ref.current.contains(event.target)) {
funcToExecute();
// alert("You clicked outside of me!");
}
} |
JavaScript | createDynamicURI(datasetURI, prefix){
let newResourceURI = datasetURI + '/' + prefix + Math.round(+new Date() / 1000);
//do not add two slashes
if(datasetURI.slice(-1) === '/'){
newResourceURI = datasetURI + prefix + Math.round(+new Date() / 1000);
}
return newResourceURI;
} | createDynamicURI(datasetURI, prefix){
let newResourceURI = datasetURI + '/' + prefix + Math.round(+new Date() / 1000);
//do not add two slashes
if(datasetURI.slice(-1) === '/'){
newResourceURI = datasetURI + prefix + Math.round(+new Date() / 1000);
}
return newResourceURI;
} |
JavaScript | function cleanShot(d) {
const x = +d['shot-x']
const y = +d['shot-y']
const distance = calculateDistance(x, y)
const distanceBin = calculateDistanceBin(distance)
const zoneName = getZoneFromShot({ x, y })
const made = d.event.toLowerCase().indexOf('missed') < 0
const gameDate = d.gamedate
return { x, y, made, distance, distanceBin, zoneName, gameDate }
} | function cleanShot(d) {
const x = +d['shot-x']
const y = +d['shot-y']
const distance = calculateDistance(x, y)
const distanceBin = calculateDistanceBin(distance)
const zoneName = getZoneFromShot({ x, y })
const made = d.event.toLowerCase().indexOf('missed') < 0
const gameDate = d.gamedate
return { x, y, made, distance, distanceBin, zoneName, gameDate }
} |
JavaScript | function clean(data) {
const season = data[0].season
return _.chain(data)
.filter(d => d.season === season)
.map(cleanShot)
.value()
} | function clean(data) {
const season = data[0].season
return _.chain(data)
.filter(d => d.season === season)
.map(cleanShot)
.value()
} |
JavaScript | function findSuitableDispenseVol (ctr) {
var adjFactor = adjStockConc / stockConc; //factor that multiplies the dispense volume to a value that can be divisible by 2.5
var adjTargetVolume = targetVolume / adjFactor;
var tempDispenseVol = +((adjTargetVolume / Math.pow(2,ctr)).toFixed(2));
if (tempDispenseVol % 2.5 === 0) {
arrDispenseVols[ctr] = tempDispenseVol;
arrAdjStockConcs[ctr] = adjStockConc;
} else {
adjStockConc = adjStockConc / 10;
findSuitableDispenseVol(ctr);
}
} | function findSuitableDispenseVol (ctr) {
var adjFactor = adjStockConc / stockConc; //factor that multiplies the dispense volume to a value that can be divisible by 2.5
var adjTargetVolume = targetVolume / adjFactor;
var tempDispenseVol = +((adjTargetVolume / Math.pow(2,ctr)).toFixed(2));
if (tempDispenseVol % 2.5 === 0) {
arrDispenseVols[ctr] = tempDispenseVol;
arrAdjStockConcs[ctr] = adjStockConc;
} else {
adjStockConc = adjStockConc / 10;
findSuitableDispenseVol(ctr);
}
} |
JavaScript | function findClosestNumber(n,m) {
var q, n1, n2;
q = n / m;
n1 = m * Math.floor(q);
n2 = m * Math.ceil(q);
if (Math.abs(n-n1) < Math.abs(n-n2)) {
return n1;
} else {
return n2;
}
} | function findClosestNumber(n,m) {
var q, n1, n2;
q = n / m;
n1 = m * Math.floor(q);
n2 = m * Math.ceil(q);
if (Math.abs(n-n1) < Math.abs(n-n2)) {
return n1;
} else {
return n2;
}
} |
JavaScript | function findBestDispenseVol(tempDispVol,recurCtr) {
// return array of values
var returnVol; // declare return volume
// If the given dispense volume is divisible by 2.5, return it as the volume to be used.
if (tempDispVol % 2.5 === 0) {
returnVol = tempDispVol;
return [returnVol,recurCtr];
// If the given dispense volume is not dividisble by 2.5, multiply it by 10 and try again.
// recurCtr is incremented to keep track of how many times the recursion has taken place.
} else {
tempDispVol *= 10;
recurCtr++;
return findBestDispenseVol(tempDispVol,recurCtr);
}
} | function findBestDispenseVol(tempDispVol,recurCtr) {
// return array of values
var returnVol; // declare return volume
// If the given dispense volume is divisible by 2.5, return it as the volume to be used.
if (tempDispVol % 2.5 === 0) {
returnVol = tempDispVol;
return [returnVol,recurCtr];
// If the given dispense volume is not dividisble by 2.5, multiply it by 10 and try again.
// recurCtr is incremented to keep track of how many times the recursion has taken place.
} else {
tempDispVol *= 10;
recurCtr++;
return findBestDispenseVol(tempDispVol,recurCtr);
}
} |
JavaScript | function convertArrayOfObjectsToCSV(args) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data;
data = args.data || null;
if (data == null || !data.length) {
return null;
}
columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n';
keys = Object.keys(data[0]);
// creates an array of strings that correspond to the keys in the first object of the data array
// this will be used as the header row
result = '';
result += keys.join(columnDelimiter);
// joins all the elements of the keys array into a string inserting the columnDelimiter in between them
result += lineDelimiter;
// concatenates the lineDelimiter at the end of the string
data.forEach(function(item) {
ctr = 0;
keys.forEach(function(key) {
if (ctr > 0) result += columnDelimiter;
result += item[key];
ctr++;
});
result += lineDelimiter;
});
return result;
} | function convertArrayOfObjectsToCSV(args) {
var result, ctr, keys, columnDelimiter, lineDelimiter, data;
data = args.data || null;
if (data == null || !data.length) {
return null;
}
columnDelimiter = args.columnDelimiter || ',';
lineDelimiter = args.lineDelimiter || '\n';
keys = Object.keys(data[0]);
// creates an array of strings that correspond to the keys in the first object of the data array
// this will be used as the header row
result = '';
result += keys.join(columnDelimiter);
// joins all the elements of the keys array into a string inserting the columnDelimiter in between them
result += lineDelimiter;
// concatenates the lineDelimiter at the end of the string
data.forEach(function(item) {
ctr = 0;
keys.forEach(function(key) {
if (ctr > 0) result += columnDelimiter;
result += item[key];
ctr++;
});
result += lineDelimiter;
});
return result;
} |
JavaScript | function downloadCSV(arrData,args,i) {
var data, filename, link;
// Extracts the string of data to be downloaded as a CSV
var csv = convertArrayOfObjectsToCSV({
data: arrData[i] // input is an object with one value "data" which is the array (arrData) of arrays of objects
});
if (csv == null) return;
filename = args[i] || 'export.csv';
// Checks to see if the string is prepended with info that tells the browser
// that this is a CSV file and should be downloaded. If the string does not
// have this information, it is prepended to the string.
if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
// Encodes CSV string into the final form to be downloaded using prepended info
data = encodeURI(csv);
// Create element
link = document.createElement('a');
// Set href attribute to the encoded string
link.setAttribute('href', data);
// Set download attribute to file name
link.setAttribute('download', filename);
// Simulate click to download file
link.click();
} | function downloadCSV(arrData,args,i) {
var data, filename, link;
// Extracts the string of data to be downloaded as a CSV
var csv = convertArrayOfObjectsToCSV({
data: arrData[i] // input is an object with one value "data" which is the array (arrData) of arrays of objects
});
if (csv == null) return;
filename = args[i] || 'export.csv';
// Checks to see if the string is prepended with info that tells the browser
// that this is a CSV file and should be downloaded. If the string does not
// have this information, it is prepended to the string.
if (!csv.match(/^data:text\/csv/i)) {
csv = 'data:text/csv;charset=utf-8,' + csv;
}
// Encodes CSV string into the final form to be downloaded using prepended info
data = encodeURI(csv);
// Create element
link = document.createElement('a');
// Set href attribute to the encoded string
link.setAttribute('href', data);
// Set download attribute to file name
link.setAttribute('download', filename);
// Simulate click to download file
link.click();
} |
JavaScript | createDom() {
// find node
const baseSelector = `.${this.opts.selector}`
const node = document.querySelector(baseSelector)
if (!node) {
Error()
}
// Create Elements
const parentDiv = this.createElement('div', 'marker-widget') // parent div
const markerDiv = this.createElement('div', 'markers-container') // markers container
const markerList = this.createElement('ul', 'marker-list') // marker list as ul
const bigImg = this.createElement('img', 'big-img')
const listFragment = document.createDocumentFragment()
bigImg.src = this.opts.img
// create markers list using constructor data
this.opts.markers.map((data) => {
const marker = this.createElement('li', 'marker')
const markerContent = this.createElement('div', 'marker-content')
const markerTooltip = this.createElement('div', 'marker-tooltip')
const markerIcon = this.createElement('div', 'marker-icon')
const markerTitle = this.createElement('h2', 'm-title')
const markerSub = this.createElement('h3', 'm-sub')
const markerText = this.createElement('p', 'm-text')
const markerImg = this.createElement('div', 'm-img')
const markerClose = this.createElement('button', 'm-close')
// add coordinates coming from json
marker.style.left = `${data.x}${data.type}`
marker.style.top = `${data.y}${data.type}`
// add data coming from json inside each tag
markerTitle.innerText = data.h2
markerSub.innerText = data.h3
markerText.innerText = data.p
markerImg.style.backgroundImage = `url(${data.img})`
markerTooltip.innerText = data.tooltip
markerClose.innerText = 'close'
// create the structure of each marker dynamically
const markerFragment = document.createDocumentFragment()
markerFragment.append(markerTitle, markerSub, markerImg, markerText, markerClose)
markerContent.append(markerFragment)
marker.appendChild(markerIcon)
marker.appendChild(markerContent)
marker.appendChild(markerTooltip)
listFragment.appendChild(marker)
})
// insert all the elements into dom
markerList.appendChild(listFragment)
markerDiv.appendChild(markerList)
parentDiv.appendChild(markerDiv)
parentDiv.appendChild(bigImg)
node.append(parentDiv)
} | createDom() {
// find node
const baseSelector = `.${this.opts.selector}`
const node = document.querySelector(baseSelector)
if (!node) {
Error()
}
// Create Elements
const parentDiv = this.createElement('div', 'marker-widget') // parent div
const markerDiv = this.createElement('div', 'markers-container') // markers container
const markerList = this.createElement('ul', 'marker-list') // marker list as ul
const bigImg = this.createElement('img', 'big-img')
const listFragment = document.createDocumentFragment()
bigImg.src = this.opts.img
// create markers list using constructor data
this.opts.markers.map((data) => {
const marker = this.createElement('li', 'marker')
const markerContent = this.createElement('div', 'marker-content')
const markerTooltip = this.createElement('div', 'marker-tooltip')
const markerIcon = this.createElement('div', 'marker-icon')
const markerTitle = this.createElement('h2', 'm-title')
const markerSub = this.createElement('h3', 'm-sub')
const markerText = this.createElement('p', 'm-text')
const markerImg = this.createElement('div', 'm-img')
const markerClose = this.createElement('button', 'm-close')
// add coordinates coming from json
marker.style.left = `${data.x}${data.type}`
marker.style.top = `${data.y}${data.type}`
// add data coming from json inside each tag
markerTitle.innerText = data.h2
markerSub.innerText = data.h3
markerText.innerText = data.p
markerImg.style.backgroundImage = `url(${data.img})`
markerTooltip.innerText = data.tooltip
markerClose.innerText = 'close'
// create the structure of each marker dynamically
const markerFragment = document.createDocumentFragment()
markerFragment.append(markerTitle, markerSub, markerImg, markerText, markerClose)
markerContent.append(markerFragment)
marker.appendChild(markerIcon)
marker.appendChild(markerContent)
marker.appendChild(markerTooltip)
listFragment.appendChild(marker)
})
// insert all the elements into dom
markerList.appendChild(listFragment)
markerDiv.appendChild(markerList)
parentDiv.appendChild(markerDiv)
parentDiv.appendChild(bigImg)
node.append(parentDiv)
} |
JavaScript | createElement(selector, className = null) {
const elem = document.createElement(selector)
if(className != null) {
elem.className = className
}
return elem
} | createElement(selector, className = null) {
const elem = document.createElement(selector)
if(className != null) {
elem.className = className
}
return elem
} |
JavaScript | multipleEventsListeners(elem, events, func) {
var event = events.split(' ');
for (var i = 0; i < event.length; i++) {
elem.addEventListener(event[i], func, false);
}
} | multipleEventsListeners(elem, events, func) {
var event = events.split(' ');
for (var i = 0; i < event.length; i++) {
elem.addEventListener(event[i], func, false);
}
} |
JavaScript | dispose() {
for (let callId in this.calls) {
if (!this.calls.hasOwnProperty(callId)) {
continue;
}
this.calls[callId].dispose();
}
this.service.clientRelease(this.clientId);
this.calls = {};
} | dispose() {
for (let callId in this.calls) {
if (!this.calls.hasOwnProperty(callId)) {
continue;
}
this.calls[callId].dispose();
}
this.service.clientRelease(this.clientId);
this.calls = {};
} |
JavaScript | reset() {
for (let serviceId in this.services) {
/* istanbul ignore next */
if (!this.services.hasOwnProperty(serviceId)) {
continue;
}
let service = this.services[serviceId];
service.end();
}
this.services = {};
} | reset() {
for (let serviceId in this.services) {
/* istanbul ignore next */
if (!this.services.hasOwnProperty(serviceId)) {
continue;
}
let service = this.services[serviceId];
service.end();
}
this.services = {};
} |
JavaScript | buildService(serviceMeta, method, endpoint) {
return new Promise((resolve, reject) => {
let sid = this.serviceIdCounter++;
let info = {
serviceId: method,
endpoint: endpoint,
};
let service = new service_1.Service(serviceMeta, sid, info, {
resolve: resolve,
reject: reject,
}, this.send);
service.initStub();
this.services[sid] = service;
service.disposed.subscribe(() => {
delete this.services[sid];
});
this.send({
serviceCreate: {
serviceId: sid,
serviceInfo: info,
},
});
});
} | buildService(serviceMeta, method, endpoint) {
return new Promise((resolve, reject) => {
let sid = this.serviceIdCounter++;
let info = {
serviceId: method,
endpoint: endpoint,
};
let service = new service_1.Service(serviceMeta, sid, info, {
resolve: resolve,
reject: reject,
}, this.send);
service.initStub();
this.services[sid] = service;
service.disposed.subscribe(() => {
delete this.services[sid];
});
this.send({
serviceCreate: {
serviceId: sid,
serviceInfo: info,
},
});
});
} |
JavaScript | updateUser (user) {
return new Promise((resolve, reject) => {
fetch(`api/user/${user.id}`, {
method: 'POST',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify(user)
}).then((response) => {
return response.json();
}).then((response) => {
if (!response.success) {
return reject(response);
}
return resolve(response);
}).catch((error) => {
reject(error);
});
});
} | updateUser (user) {
return new Promise((resolve, reject) => {
fetch(`api/user/${user.id}`, {
method: 'POST',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify(user)
}).then((response) => {
return response.json();
}).then((response) => {
if (!response.success) {
return reject(response);
}
return resolve(response);
}).catch((error) => {
reject(error);
});
});
} |
JavaScript | hasRole (user, role) {
if (!user) { return false; }
const roles = role.split(',');
for (let r of roles) {
let reverse = false;
if (r.startsWith('!')) {
reverse = true;
r = r.substr(1);
}
if ((!reverse && !user.roles.includes(r)) ||
(reverse && user.roles.includes(r))) {
return false;
}
}
return true;
} | hasRole (user, role) {
if (!user) { return false; }
const roles = role.split(',');
for (let r of roles) {
let reverse = false;
if (r.startsWith('!')) {
reverse = true;
r = r.substr(1);
}
if ((!reverse && !user.roles.includes(r)) ||
(reverse && user.roles.includes(r))) {
return false;
}
}
return true;
} |
JavaScript | changePassword (data, userId) {
return new Promise((resolve, reject) => {
let url = 'api/user/password';
if (userId) { url += `?userId=${userId}`; }
fetch(url, {
method: 'POST',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify(data)
}).then((response) => {
return response.json();
}).then((response) => {
if (response.success) {
return resolve(response);
} else {
return reject(response.text);
}
});
});
} | changePassword (data, userId) {
return new Promise((resolve, reject) => {
let url = 'api/user/password';
if (userId) { url += `?userId=${userId}`; }
fetch(url, {
method: 'POST',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify(data)
}).then((response) => {
return response.json();
}).then((response) => {
if (response.success) {
return resolve(response);
} else {
return reject(response.text);
}
});
});
} |
JavaScript | create (hunt) {
return new Promise((resolve, reject) => {
const options = {
url: 'api/hunt',
method: 'POST',
data: hunt
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} | create (hunt) {
return new Promise((resolve, reject) => {
const options = {
url: 'api/hunt',
method: 'POST',
data: hunt
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} |
JavaScript | delete (id) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}`,
method: 'DELETE'
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} | delete (id) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}`,
method: 'DELETE'
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} |
JavaScript | cancel (id) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}/cancel`,
method: 'PUT'
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} | cancel (id) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}/cancel`,
method: 'PUT'
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} |
JavaScript | pause (id) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}/pause`,
method: 'PUT'
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} | pause (id) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}/pause`,
method: 'PUT'
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} |
JavaScript | play (id) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}/play`,
method: 'PUT'
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} | play (id) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}/play`,
method: 'PUT'
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} |
JavaScript | removeUser (id, userid) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}/user/${userid}`,
method: 'DELETE'
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} | removeUser (id, userid) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}/user/${userid}`,
method: 'DELETE'
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} |
JavaScript | addUsers (id, users) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}/users`,
method: 'POST',
data: { users: users }
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} | addUsers (id, users) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}/users`,
method: 'POST',
data: { users: users }
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} |
JavaScript | cleanup (id, users) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}/removefromsessions`,
method: 'PUT'
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} | cleanup (id, users) {
return new Promise((resolve, reject) => {
const options = {
url: `api/hunt/${id}/removefromsessions`,
method: 'PUT'
};
Vue.axios(options).then((response) => {
resolve(response);
}).catch((error) => {
reject(error);
});
});
} |
JavaScript | userHasHuntRole (user, hunt) {
if (hunt.roles.length) {
for (const role of hunt.roles) {
if (user.roles.indexOf(role) > -1) {
return true;
}
}
}
return false;
} | userHasHuntRole (user, hunt) {
if (hunt.roles.length) {
for (const role of hunt.roles) {
if (user.roles.indexOf(role) > -1) {
return true;
}
}
}
return false;
} |
JavaScript | canViewHunt (user, hunt) {
const huntUsers = hunt.users || [];
const userRoles = user.roles || [];
return user.userId === hunt.userId ||
userRoles.includes('arkimeAdmin') ||
huntUsers.includes(user.userId) ||
this.userHasHuntRole(user, hunt);
} | canViewHunt (user, hunt) {
const huntUsers = hunt.users || [];
const userRoles = user.roles || [];
return user.userId === hunt.userId ||
userRoles.includes('arkimeAdmin') ||
huntUsers.includes(user.userId) ||
this.userHasHuntRole(user, hunt);
} |
JavaScript | static async apiGet (req, res, next) {
const roles = await req.user.getRoles();
const views = await Db.getMatchingViews(req.user.userId, [...roles]);
// Set editable on any views that the user is allowed to edit
for (const view of views) {
view._editable = view.creator === req.user.userId || req.user.hasRole(view.editRoles);
view._viewable = view.creator === req.user.userId || req.user.hasRole(view.viewRoles);
}
res.send({ success: true, views: views });
} | static async apiGet (req, res, next) {
const roles = await req.user.getRoles();
const views = await Db.getMatchingViews(req.user.userId, [...roles]);
// Set editable on any views that the user is allowed to edit
for (const view of views) {
view._editable = view.creator === req.user.userId || req.user.hasRole(view.editRoles);
view._viewable = view.creator === req.user.userId || req.user.hasRole(view.viewRoles);
}
res.send({ success: true, views: views });
} |
JavaScript | static verifyView (view) {
// TODO: Check roles
if (typeof (view.name) !== 'string') {
return 'Missing name';
}
if (view.viewRoles !== undefined && !Array.isArray(view.viewRoles)) {
return 'viewRoles must be array';
}
if (view.editRoles !== undefined && !Array.isArray(view.editRoles)) {
return 'viewRoles must be array';
}
if (view.integrations !== undefined && !Array.isArray(view.integrations)) {
return 'integrations must be array';
}
return null;
} | static verifyView (view) {
// TODO: Check roles
if (typeof (view.name) !== 'string') {
return 'Missing name';
}
if (view.viewRoles !== undefined && !Array.isArray(view.viewRoles)) {
return 'viewRoles must be array';
}
if (view.editRoles !== undefined && !Array.isArray(view.editRoles)) {
return 'viewRoles must be array';
}
if (view.integrations !== undefined && !Array.isArray(view.integrations)) {
return 'integrations must be array';
}
return null;
} |
JavaScript | function simpleGatherNodes (req, res) {
simpleGather(req, res, null, (err, results) => {
const obj = results[0];
for (let i = 1; i < results.length; i++) {
shallowCopy(obj.nodes, results[i].nodes);
}
res.send(obj);
});
} | function simpleGatherNodes (req, res) {
simpleGather(req, res, null, (err, results) => {
const obj = results[0];
for (let i = 1; i < results.length; i++) {
shallowCopy(obj.nodes, results[i].nodes);
}
res.send(obj);
});
} |
JavaScript | function simpleGatherTasks (req, res) {
simpleGather(req, res, null, (err, results) => {
const obj = results[0];
for (let i = 1; i < results.length; i++) {
shallowCopy(obj.tasks, results[i].tasks);
}
res.send(obj);
});
} | function simpleGatherTasks (req, res) {
simpleGather(req, res, null, (err, results) => {
const obj = results[0];
for (let i = 1; i < results.length; i++) {
shallowCopy(obj.tasks, results[i].tasks);
}
res.send(obj);
});
} |
JavaScript | function simpleGatherAdd (req, res) {
simpleGather(req, res, null, (err, results) => {
const obj = results[0];
for (let i = 1; i < results.length; i++) {
shallowAdd(obj, results[i]);
}
obj.cluster_name = 'COMBINED';
res.send(obj);
});
} | function simpleGatherAdd (req, res) {
simpleGather(req, res, null, (err, results) => {
const obj = results[0];
for (let i = 1; i < results.length; i++) {
shallowAdd(obj, results[i]);
}
obj.cluster_name = 'COMBINED';
res.send(obj);
});
} |
JavaScript | function pingESNode (client, node) {
return new Promise((resolve, reject) => {
client.ping({}, {
requestTimeout: 3 * 1000 // ping usually has a 3000ms timeout
}, function (error, { body: response }) {
resolve({ isActive: !error, node: node });
});
});
} | function pingESNode (client, node) {
return new Promise((resolve, reject) => {
client.ping({}, {
requestTimeout: 3 * 1000 // ping usually has a 3000ms timeout
}, function (error, { body: response }) {
resolve({ isActive: !error, node: node });
});
});
} |
JavaScript | function shareView (req, res, user, endpoint, successMessage, errorMessage) {
const view = user.views[req.body.name];
view.shared = true;
delete user.views[req.body.name]; // remove the view from the
User.setUser(user.userId, user, (err, info) => {
if (err) {
console.log('ERROR - shareView -', endpoint, util.inspect(err, false, 50), info);
return res.serverError(500, errorMessage);
}
// save the view on the shared user
return saveSharedView(req, res, user, view, endpoint, successMessage, errorMessage);
});
} | function shareView (req, res, user, endpoint, successMessage, errorMessage) {
const view = user.views[req.body.name];
view.shared = true;
delete user.views[req.body.name]; // remove the view from the
User.setUser(user.userId, user, (err, info) => {
if (err) {
console.log('ERROR - shareView -', endpoint, util.inspect(err, false, 50), info);
return res.serverError(500, errorMessage);
}
// save the view on the shared user
return saveSharedView(req, res, user, view, endpoint, successMessage, errorMessage);
});
} |
JavaScript | function unshareView (req, res, user, sharedUser, endpoint, successMessage, errorMessage) {
User.setUser('_moloch_shared', sharedUser, (err, info) => {
if (err) {
console.log('ERROR - unshareView - setUser (_moloch_shared) -', endpoint, util.inspect(err, false, 50), info);
return res.serverError(500, errorMessage);
}
if (user.views[req.body.name]) { // the user already has a view with this name
return res.serverError(403, 'A view already exists with this name.');
}
user.views[req.body.name] = {
expression: req.body.expression,
user: req.body.user, // keep the user so we know who created it
shared: false,
sessionsColConfig: req.body.sessionsColConfig
};
User.setUser(user.userId, user, (err, subInfo) => {
if (err) {
console.log(`ERROR - saveSharedView - setUser (${user.userId}) -`, endpoint, util.inspect(err, false, 50), subInfo);
return res.serverError(500, errorMessage);
}
return res.send(JSON.stringify({
success: true,
text: successMessage
}));
});
});
} | function unshareView (req, res, user, sharedUser, endpoint, successMessage, errorMessage) {
User.setUser('_moloch_shared', sharedUser, (err, info) => {
if (err) {
console.log('ERROR - unshareView - setUser (_moloch_shared) -', endpoint, util.inspect(err, false, 50), info);
return res.serverError(500, errorMessage);
}
if (user.views[req.body.name]) { // the user already has a view with this name
return res.serverError(403, 'A view already exists with this name.');
}
user.views[req.body.name] = {
expression: req.body.expression,
user: req.body.user, // keep the user so we know who created it
shared: false,
sessionsColConfig: req.body.sessionsColConfig
};
User.setUser(user.userId, user, (err, subInfo) => {
if (err) {
console.log(`ERROR - saveSharedView - setUser (${user.userId}) -`, endpoint, util.inspect(err, false, 50), subInfo);
return res.serverError(500, errorMessage);
}
return res.send(JSON.stringify({
success: true,
text: successMessage
}));
});
});
} |
JavaScript | function str2format (str) {
if (str.match(/^(s|sec|secs|second|seconds)$/)) {
return 'seconds';
} else if (str.match(/^(m|min|mins|minute|minutes)$/)) {
return 'minutes';
} else if (str.match(/^(h|hr|hrs|hour|hours)$/)) {
return 'hours';
} else if (str.match(/^(d|day|days)$/)) {
return 'days';
} else if (str.match(/^(w|week|weeks)\d*$/)) {
return 'weeks';
} else if (str.match(/^(M|mon|mons|month|months)$/)) {
return 'months';
} else if (str.match(/^(q|qtr|qtrs|quarter|quarters)$/)) {
return 'quarters';
} else if (str.match(/^(y|yr|yrs|year|years)$/)) {
return 'years';
}
return undefined;
} | function str2format (str) {
if (str.match(/^(s|sec|secs|second|seconds)$/)) {
return 'seconds';
} else if (str.match(/^(m|min|mins|minute|minutes)$/)) {
return 'minutes';
} else if (str.match(/^(h|hr|hrs|hour|hours)$/)) {
return 'hours';
} else if (str.match(/^(d|day|days)$/)) {
return 'days';
} else if (str.match(/^(w|week|weeks)\d*$/)) {
return 'weeks';
} else if (str.match(/^(M|mon|mons|month|months)$/)) {
return 'months';
} else if (str.match(/^(q|qtr|qtrs|quarter|quarters)$/)) {
return 'quarters';
} else if (str.match(/^(y|yr|yrs|year|years)$/)) {
return 'years';
}
return undefined;
} |
JavaScript | deleteIntegrationsView (id) {
return new Promise((resolve, reject) => {
fetch(`api/view/${id}`, {
method: 'DELETE',
headers: setReqHeaders()
}).then((response) => {
return response.json();
}).then((response) => {
if (response.success) {
this.getIntegrationViews();
return resolve(response);
} else {
return reject(response.text);
}
});
});
} | deleteIntegrationsView (id) {
return new Promise((resolve, reject) => {
fetch(`api/view/${id}`, {
method: 'DELETE',
headers: setReqHeaders()
}).then((response) => {
return response.json();
}).then((response) => {
if (response.success) {
this.getIntegrationViews();
return resolve(response);
} else {
return reject(response.text);
}
});
});
} |
JavaScript | changePassword (data) {
return new Promise((resolve, reject) => {
fetch('api/user/password', {
method: 'POST',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify(data)
}).then((response) => {
return response.json();
}).then((response) => {
if (response.success) {
return resolve(response);
} else {
return reject(response.text);
}
});
});
} | changePassword (data) {
return new Promise((resolve, reject) => {
fetch('api/user/password', {
method: 'POST',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify(data)
}).then((response) => {
return response.json();
}).then((response) => {
if (response.success) {
return resolve(response);
} else {
return reject(response.text);
}
});
});
} |
JavaScript | static async apiList (req, res, next) {
const results = {};
const integrations = Integration.integrations.all;
const keys = req.user.getCont3xtKeys();
for (const integration of integrations) {
if (Object.keys(integration.itypes).length === 0) { continue; }
let doable = true;
// First check if user has disabled integration
const disabled = keys?.[integration.name]?.disabled;
if (disabled === true || disabled === 'true') {
doable = false;
}
// If still doable check to see if all settings set
if (doable && integration.settings) {
for (const setting in integration.settings) {
if (integration.settings[setting].required && !integration.getUserConfig(req.user, integration.name, setting)) {
doable = false;
break;
}
}
}
// User can override card display
let card = integration.card;
const cardstr = integration.getUserConfig(req.user, integration.name, 'card');
if (cardstr) {
card = JSON.parse(cardstr);
// Should normalize here
}
// User can override order
const order = integration.getUserConfig(req.user, integration.name, 'order', integration.order);
results[integration.name] = {
doable: doable,
cacheTimeout: integration.cacheable ? integration.cacheTimeout : -1,
cachePolicy: integration.cachePolicy,
icon: integration.icon,
card: card,
order: order
};
}
return res.send({ success: true, integrations: results });
} | static async apiList (req, res, next) {
const results = {};
const integrations = Integration.integrations.all;
const keys = req.user.getCont3xtKeys();
for (const integration of integrations) {
if (Object.keys(integration.itypes).length === 0) { continue; }
let doable = true;
// First check if user has disabled integration
const disabled = keys?.[integration.name]?.disabled;
if (disabled === true || disabled === 'true') {
doable = false;
}
// If still doable check to see if all settings set
if (doable && integration.settings) {
for (const setting in integration.settings) {
if (integration.settings[setting].required && !integration.getUserConfig(req.user, integration.name, setting)) {
doable = false;
break;
}
}
}
// User can override card display
let card = integration.card;
const cardstr = integration.getUserConfig(req.user, integration.name, 'card');
if (cardstr) {
card = JSON.parse(cardstr);
// Should normalize here
}
// User can override order
const order = integration.getUserConfig(req.user, integration.name, 'order', integration.order);
results[integration.name] = {
doable: doable,
cacheTimeout: integration.cacheable ? integration.cacheTimeout : -1,
cachePolicy: integration.cachePolicy,
icon: integration.icon,
card: card,
order: order
};
}
return res.send({ success: true, integrations: results });
} |
JavaScript | function updateTime (stats, istats, diff, prefix) {
const lookup = Math.min(stats[prefix + 'Lookup'], 100);
stats[prefix + 'RecentAvgMS'] = (stats[prefix + 'RecentAvgMS'] * (lookup - 1) + diff) / lookup;
const ilookup = Math.min(stats[prefix + 'Lookup'], 100);
istats[prefix + 'RecentAvgMS'] = (istats[prefix + 'RecentAvgMS'] * (ilookup - 1) + diff) / ilookup;
} | function updateTime (stats, istats, diff, prefix) {
const lookup = Math.min(stats[prefix + 'Lookup'], 100);
stats[prefix + 'RecentAvgMS'] = (stats[prefix + 'RecentAvgMS'] * (lookup - 1) + diff) / lookup;
const ilookup = Math.min(stats[prefix + 'Lookup'], 100);
istats[prefix + 'RecentAvgMS'] = (istats[prefix + 'RecentAvgMS'] * (ilookup - 1) + diff) / ilookup;
} |
JavaScript | hasPermission (priv) {
const user = store.state.user;
if (!user) { return false; }
const privs = priv.split(',');
for (let p of privs) {
let reverse = false;
if (p.startsWith('!')) {
reverse = true;
p = p.substr(1);
}
if ((!reverse && !user[p]) ||
(reverse && user[p])) {
return false;
}
}
return true;
} | hasPermission (priv) {
const user = store.state.user;
if (!user) { return false; }
const privs = priv.split(',');
for (let p of privs) {
let reverse = false;
if (p.startsWith('!')) {
reverse = true;
p = p.substr(1);
}
if ((!reverse && !user[p]) ||
(reverse && user[p])) {
return false;
}
}
return true;
} |
JavaScript | hasRole (role) {
const user = store.state.user;
if (!user) { return false; }
const roles = role.split(',');
for (let r of roles) {
let reverse = false;
if (r.startsWith('!')) {
reverse = true;
r = r.substr(1);
}
if ((!reverse && !user.roles.includes(r)) ||
(reverse && user.roles.includes(r))) {
return false;
}
}
return true;
} | hasRole (role) {
const user = store.state.user;
if (!user) { return false; }
const roles = role.split(',');
for (let r of roles) {
let reverse = false;
if (r.startsWith('!')) {
reverse = true;
r = r.substr(1);
}
if ((!reverse && !user.roles.includes(r)) ||
(reverse && user.roles.includes(r))) {
return false;
}
}
return true;
} |
JavaScript | saveSettings (settings, userId) {
return new Promise((resolve, reject) => {
const options = {
url: 'api/user/settings',
method: 'POST',
data: settings,
params: { userId: userId }
};
// update user settings
if (!userId || store.state.user.userId === userId) {
store.commit('setUserSettings', settings);
}
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error);
});
});
} | saveSettings (settings, userId) {
return new Promise((resolve, reject) => {
const options = {
url: 'api/user/settings',
method: 'POST',
data: settings,
params: { userId: userId }
};
// update user settings
if (!userId || store.state.user.userId === userId) {
store.commit('setUserSettings', settings);
}
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error);
});
});
} |
JavaScript | resetSettings (userId, theme) {
const settings = JSON.parse(JSON.stringify(defaultSettings));
if (theme) {
settings.theme = theme;
}
return this.saveSettings(settings, userId);
} | resetSettings (userId, theme) {
const settings = JSON.parse(JSON.stringify(defaultSettings));
if (theme) {
settings.theme = theme;
}
return this.saveSettings(settings, userId);
} |
JavaScript | createView (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: 'api/user/view',
method: 'POST',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error);
});
});
} | createView (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: 'api/user/view',
method: 'POST',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error);
});
});
} |
JavaScript | deleteView (view, viewName, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/view/${viewName}`,
method: 'DELETE',
data: view,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error);
});
});
} | deleteView (view, viewName, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/view/${viewName}`,
method: 'DELETE',
data: view,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error);
});
});
} |
JavaScript | updateView (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/view/${data.key}`,
method: 'PUT',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
response.data.views = this.parseViews(response.data.views);
resolve(response.data);
}, (error) => {
reject(error);
});
});
} | updateView (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/view/${data.key}`,
method: 'PUT',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
response.data.views = this.parseViews(response.data.views);
resolve(response.data);
}, (error) => {
reject(error);
});
});
} |
JavaScript | toggleShareView (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/view/${data.name}/toggleshare`,
method: 'POST',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error);
});
});
} | toggleShareView (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/view/${data.name}/toggleshare`,
method: 'POST',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error);
});
});
} |
JavaScript | createCronQuery (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: 'api/user/cron',
method: 'POST',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} | createCronQuery (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: 'api/user/cron',
method: 'POST',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} |
JavaScript | deleteCronQuery (key, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/cron/${key}`,
method: 'DELETE',
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} | deleteCronQuery (key, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/cron/${key}`,
method: 'DELETE',
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} |
JavaScript | updateCronQuery (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/cron/${data.key}`,
method: 'POST',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} | updateCronQuery (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/cron/${data.key}`,
method: 'POST',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} |
JavaScript | deleteColumnConfig (colName, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/column/${colName}`,
method: 'DELETE',
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} | deleteColumnConfig (colName, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/column/${colName}`,
method: 'DELETE',
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} |
JavaScript | updateColumnConfig (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/column/${data.name}`,
method: 'PUT',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} | updateColumnConfig (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/column/${data.name}`,
method: 'PUT',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} |
JavaScript | deleteSpiviewFieldConfig (spiName, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/spiview/${spiName}`,
method: 'POST',
data: { name: spiName },
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} | deleteSpiviewFieldConfig (spiName, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/spiview/${spiName}`,
method: 'POST',
data: { name: spiName },
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} |
JavaScript | updateSpiviewFieldConfig (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/spiview/${data.name}`,
method: 'PUT',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} | updateSpiviewFieldConfig (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/spiview/${data.name}`,
method: 'PUT',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error.data);
});
});
} |
JavaScript | changePassword (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: 'api/user/password',
method: 'POST',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error);
});
});
} | changePassword (data, userId) {
return new Promise((resolve, reject) => {
const options = {
url: 'api/user/password',
method: 'POST',
data: data,
params: { userId: userId }
};
Vue.axios(options)
.then((response) => {
resolve(response.data);
}, (error) => {
reject(error);
});
});
} |
JavaScript | saveState (state, stateName) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/state/${stateName}`,
method: 'POST',
data: state
};
Vue.axios(options)
.then((response) => {
resolve(response);
}, (error) => {
reject(error);
});
});
} | saveState (state, stateName) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/state/${stateName}`,
method: 'POST',
data: state
};
Vue.axios(options)
.then((response) => {
resolve(response);
}, (error) => {
reject(error);
});
});
} |
JavaScript | acknowledgeMsg (msgNum, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/${userId}/acknowledge`,
method: 'PUT',
data: { msgNum: msgNum }
};
Vue.axios(options)
.then((response) => {
resolve(response);
}, (error) => {
reject(error);
});
});
} | acknowledgeMsg (msgNum, userId) {
return new Promise((resolve, reject) => {
const options = {
url: `api/user/${userId}/acknowledge`,
method: 'PUT',
data: { msgNum: msgNum }
};
Vue.axios(options)
.then((response) => {
resolve(response);
}, (error) => {
reject(error);
});
});
} |
JavaScript | parseViews (views) {
for (const viewName in views) {
views[viewName].name = viewName;
}
return views;
} | parseViews (views) {
for (const viewName in views) {
views[viewName].name = viewName;
}
return views;
} |
JavaScript | static async apiGet (req, res, next) {
const roles = await req.user.getRoles();
let linkGroups = await Db.getMatchingLinkGroups(req.user.userId, [...roles]);
// Set editable on any linkGroups that the user is allowed to edit
for (const lg of linkGroups) {
lg._editable = lg.creator === req.user.userId || req.user.hasRole(lg.editRoles);
lg._viewable = lg.creator === req.user.userId || req.user.hasRole(lg.viewRoles);
}
const reordered = [];
const unordered = [];
const settings = req.user.cont3xt ?? {};
if (settings.linkGroup && settings.linkGroup.order) {
for (const group of linkGroups) {
if (settings.linkGroup.order.indexOf(group._id) === -1) {
unordered.push(group);
}
}
for (const id of settings.linkGroup.order) {
for (const group of linkGroups) {
if (group._id === id) {
reordered.push(group);
}
}
}
}
if (reordered.length) {
linkGroups = reordered.concat(unordered);
}
res.send({ success: true, linkGroups: linkGroups });
} | static async apiGet (req, res, next) {
const roles = await req.user.getRoles();
let linkGroups = await Db.getMatchingLinkGroups(req.user.userId, [...roles]);
// Set editable on any linkGroups that the user is allowed to edit
for (const lg of linkGroups) {
lg._editable = lg.creator === req.user.userId || req.user.hasRole(lg.editRoles);
lg._viewable = lg.creator === req.user.userId || req.user.hasRole(lg.viewRoles);
}
const reordered = [];
const unordered = [];
const settings = req.user.cont3xt ?? {};
if (settings.linkGroup && settings.linkGroup.order) {
for (const group of linkGroups) {
if (settings.linkGroup.order.indexOf(group._id) === -1) {
unordered.push(group);
}
}
for (const id of settings.linkGroup.order) {
for (const group of linkGroups) {
if (group._id === id) {
reordered.push(group);
}
}
}
}
if (reordered.length) {
linkGroups = reordered.concat(unordered);
}
res.send({ success: true, linkGroups: linkGroups });
} |
JavaScript | static verifyLinkGroup (lg) {
// TODO: Check roles
if (typeof (lg.name) !== 'string') {
return 'Missing name';
}
if (!Array.isArray(lg.links)) {
return 'Missing list of links';
}
if (lg.viewRoles !== undefined && !Array.isArray(lg.viewRoles)) {
return 'viewRoles must be array';
}
if (lg.editRoles !== undefined && !Array.isArray(lg.editRoles)) {
return 'editRoles must be array';
}
for (const link of lg.links) {
if (typeof (link.name) !== 'string') {
return 'Link missing name';
}
if (typeof (link.url) !== 'string') {
return 'Link missing url';
}
if (!Array.isArray(link.itypes)) {
return 'Link missing itypes';
}
}
return null;
} | static verifyLinkGroup (lg) {
// TODO: Check roles
if (typeof (lg.name) !== 'string') {
return 'Missing name';
}
if (!Array.isArray(lg.links)) {
return 'Missing list of links';
}
if (lg.viewRoles !== undefined && !Array.isArray(lg.viewRoles)) {
return 'viewRoles must be array';
}
if (lg.editRoles !== undefined && !Array.isArray(lg.editRoles)) {
return 'editRoles must be array';
}
for (const link of lg.links) {
if (typeof (link.name) !== 'string') {
return 'Link missing name';
}
if (typeof (link.url) !== 'string') {
return 'Link missing url';
}
if (!Array.isArray(link.itypes)) {
return 'Link missing itypes';
}
}
return null;
} |
JavaScript | static async apiCreate (req, res, next) {
const linkGroup = req.body;
linkGroup.creator = req.user.userId;
const msg = LinkGroup.verifyLinkGroup(linkGroup);
if (msg) {
return res.send({ success: false, text: msg });
}
const results = await Db.putLinkGroup(null, linkGroup);
if (!results) {
return res.send({ success: false, text: 'ES Error' });
}
return res.send({ success: true, text: 'Success' });
} | static async apiCreate (req, res, next) {
const linkGroup = req.body;
linkGroup.creator = req.user.userId;
const msg = LinkGroup.verifyLinkGroup(linkGroup);
if (msg) {
return res.send({ success: false, text: msg });
}
const results = await Db.putLinkGroup(null, linkGroup);
if (!results) {
return res.send({ success: false, text: 'ES Error' });
}
return res.send({ success: true, text: 'Success' });
} |
JavaScript | createLinkGroup (linkGroup) {
for (const link of linkGroup.links) {
delete link.expanded; // clear link expanded prop, it's just for the UI
}
return new Promise((resolve, reject) => {
fetch('api/linkGroup', {
method: 'PUT',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify(linkGroup)
}).then((response) => {
return response.json();
}).then((response) => {
if (response.success) {
this.getLinkGroups();
return resolve(response);
} else {
return reject(response.text);
}
});
});
} | createLinkGroup (linkGroup) {
for (const link of linkGroup.links) {
delete link.expanded; // clear link expanded prop, it's just for the UI
}
return new Promise((resolve, reject) => {
fetch('api/linkGroup', {
method: 'PUT',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify(linkGroup)
}).then((response) => {
return response.json();
}).then((response) => {
if (response.success) {
this.getLinkGroups();
return resolve(response);
} else {
return reject(response.text);
}
});
});
} |
JavaScript | deleteLinkGroup (id, index) {
store.commit('SET_LINK_GROUPS_ERROR', '');
return new Promise((resolve, reject) => {
fetch(`api/linkGroup/${id}`, {
method: 'DELETE',
headers: setReqHeaders()
}).then((response) => {
return response.json();
}).then((response) => {
if (response.success) {
store.commit('REMOVE_LINK_GROUP', index);
return resolve(response);
} else {
store.commit('SET_LINK_GROUPS_ERROR', response.text);
return reject(response.text);
}
});
});
} | deleteLinkGroup (id, index) {
store.commit('SET_LINK_GROUPS_ERROR', '');
return new Promise((resolve, reject) => {
fetch(`api/linkGroup/${id}`, {
method: 'DELETE',
headers: setReqHeaders()
}).then((response) => {
return response.json();
}).then((response) => {
if (response.success) {
store.commit('REMOVE_LINK_GROUP', index);
return resolve(response);
} else {
store.commit('SET_LINK_GROUPS_ERROR', response.text);
return reject(response.text);
}
});
});
} |
JavaScript | updateLinkGroup (linkGroup) {
store.commit('SET_LINK_GROUPS_ERROR', '');
for (const link of linkGroup.links) {
delete link.expanded; // clear link expanded prop, it's just for the UI
}
return new Promise((resolve, reject) => {
fetch(`api/linkGroup/${linkGroup._id}`, {
method: 'PUT',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify(linkGroup)
}).then((response) => {
return response.json();
}).then((response) => {
if (response.success) {
store.commit('UPDATE_LINK_GROUP', linkGroup);
return resolve(response);
} else {
store.commit('SET_LINK_GROUPS_ERROR', response.text);
return reject(response.text);
}
});
});
} | updateLinkGroup (linkGroup) {
store.commit('SET_LINK_GROUPS_ERROR', '');
for (const link of linkGroup.links) {
delete link.expanded; // clear link expanded prop, it's just for the UI
}
return new Promise((resolve, reject) => {
fetch(`api/linkGroup/${linkGroup._id}`, {
method: 'PUT',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify(linkGroup)
}).then((response) => {
return response.json();
}).then((response) => {
if (response.success) {
store.commit('UPDATE_LINK_GROUP', linkGroup);
return resolve(response);
} else {
store.commit('SET_LINK_GROUPS_ERROR', response.text);
return reject(response.text);
}
});
});
} |
JavaScript | parseFieldDef (line) {
if (line[0] === '#') {
line = line.substring(1);
}
if (line.lastIndexOf('field:', 0) === 0) {
const pos = this.api.addField(line);
const match = line.match(/shortcut:([^;]+)/);
if (match) {
this.shortcuts[match[1]] = { pos: pos, mod: 0 };
const kind = line.match(/kind:([^;]+)/);
if (kind) {
if (kind[1] === 'lotermfield') {
this.shortcuts[match[1]].mod = 1;
} else if (kind[1] === 'uptermfield') {
this.shortcuts[match[1]].mod = 2;
}
}
}
} else if (line.lastIndexOf('view:', 0) === 0) {
this.view += line.substring(5) + '\n';
}
} | parseFieldDef (line) {
if (line[0] === '#') {
line = line.substring(1);
}
if (line.lastIndexOf('field:', 0) === 0) {
const pos = this.api.addField(line);
const match = line.match(/shortcut:([^;]+)/);
if (match) {
this.shortcuts[match[1]] = { pos: pos, mod: 0 };
const kind = line.match(/kind:([^;]+)/);
if (kind) {
if (kind[1] === 'lotermfield') {
this.shortcuts[match[1]].mod = 1;
} else if (kind[1] === 'uptermfield') {
this.shortcuts[match[1]].mod = 2;
}
}
}
} else if (line.lastIndexOf('view:', 0) === 0) {
this.view += line.substring(5) + '\n';
}
} |
JavaScript | parseCSV (body, setCb, endCb) {
csv.parse(body, { skip_empty_lines: true, comment: '#', relax_column_count: true }, (err, data) => {
if (err) {
return endCb(err);
}
for (let i = 0; i < data.length; i++) {
const args = [];
for (const k in this.shortcuts) {
if (data[i][k] !== undefined && data[i][k] !== '') {
args.push(this.shortcuts[k].pos);
if (this.shortcuts[k].mod === 1) {
args.push(data[i][k].toLowerCase());
} else if (this.shortcuts[k].mod === 2) {
args.push(data[i][k].toUpperCase());
} else {
args.push(data[i][k]);
}
}
}
if (args.length === 0) {
setCb(data[i][this.column], WISESource.emptyResult);
} else {
setCb(data[i][this.column], WISESource.encodeResult.apply(null, args));
}
}
endCb(err);
});
} | parseCSV (body, setCb, endCb) {
csv.parse(body, { skip_empty_lines: true, comment: '#', relax_column_count: true }, (err, data) => {
if (err) {
return endCb(err);
}
for (let i = 0; i < data.length; i++) {
const args = [];
for (const k in this.shortcuts) {
if (data[i][k] !== undefined && data[i][k] !== '') {
args.push(this.shortcuts[k].pos);
if (this.shortcuts[k].mod === 1) {
args.push(data[i][k].toLowerCase());
} else if (this.shortcuts[k].mod === 2) {
args.push(data[i][k].toUpperCase());
} else {
args.push(data[i][k]);
}
}
}
if (args.length === 0) {
setCb(data[i][this.column], WISESource.emptyResult);
} else {
setCb(data[i][this.column], WISESource.encodeResult.apply(null, args));
}
}
endCb(err);
});
} |
JavaScript | parseTagger (body, setCb, endCb) {
const lines = body.toString().split(/\r?\n/);
this.view = '';
for (let l = 0, llen = lines.length; l < llen; l++) {
if (lines[l][0] === '#') {
this.parseFieldDef(lines[l]);
continue;
}
if (lines[l].match(/^\s*$/)) {
continue;
}
const args = [];
const parts = lines[l].split(';');
for (let p = 1; p < parts.length; p++) {
const kv = splitRemain(parts[p], '=', 1);
if (kv.length !== 2) {
console.log('WARNING -', this.section, "- ignored extra piece '" + parts[p] + "' from line '" + lines[l] + "'");
continue;
}
if (this.shortcuts[kv[0]] !== undefined) {
args.push(this.shortcuts[kv[0]].pos);
} else if (WISESource.field2Pos[kv[0]]) {
args.push(WISESource.field2Pos[kv[0]]);
} else {
args.push(this.api.addField('field:' + kv[0]));
}
args.push(kv[1]);
}
setCb(parts[0], WISESource.encodeResult.apply(null, args));
}
if (this.view !== '') {
this.api.addView(this.section, this.view);
}
endCb(null);
} | parseTagger (body, setCb, endCb) {
const lines = body.toString().split(/\r?\n/);
this.view = '';
for (let l = 0, llen = lines.length; l < llen; l++) {
if (lines[l][0] === '#') {
this.parseFieldDef(lines[l]);
continue;
}
if (lines[l].match(/^\s*$/)) {
continue;
}
const args = [];
const parts = lines[l].split(';');
for (let p = 1; p < parts.length; p++) {
const kv = splitRemain(parts[p], '=', 1);
if (kv.length !== 2) {
console.log('WARNING -', this.section, "- ignored extra piece '" + parts[p] + "' from line '" + lines[l] + "'");
continue;
}
if (this.shortcuts[kv[0]] !== undefined) {
args.push(this.shortcuts[kv[0]].pos);
} else if (WISESource.field2Pos[kv[0]]) {
args.push(WISESource.field2Pos[kv[0]]);
} else {
args.push(this.api.addField('field:' + kv[0]));
}
args.push(kv[1]);
}
setCb(parts[0], WISESource.encodeResult.apply(null, args));
}
if (this.view !== '') {
this.api.addView(this.section, this.view);
}
endCb(null);
} |
JavaScript | parseJSON (body, setCb, endCb) {
try {
let json = JSON.parse(body);
if (this.keyPath === undefined) {
return endCb('No keyPath set');
}
if (this.arrayPath !== undefined) {
const arrayPath = this.arrayPath.split('.');
for (let i = 0; i < arrayPath.length; i++) {
json = json[arrayPath[i]];
if (!json) {
return endCb(`Couldn't find ${arrayPath[i]} in results`);
}
}
}
// The rest of the code assumes an array
if (!Array.isArray(json)) {
json = [json];
}
const keyPath = this.keyPath.split('.');
// Convert shortcuts into array of key path
const shortcuts = [];
const shortcutsValue = [];
for (const k in this.shortcuts) {
shortcuts.push(k.split('.'));
shortcutsValue.push(this.shortcuts[k]);
}
for (let i = 0; i < json.length; i++) {
// Walk the key path
let key = json[i];
for (let j = 0; key && j < keyPath.length; j++) {
key = key[keyPath[j]];
}
if (key === undefined || key === null) {
continue;
}
const args = [];
// Check each shortcut
for (let k = 0; k < shortcuts.length; k++) {
let objs = json[i];
// Walk the shortcut path
for (let j = 0; objs && j < shortcuts[k].length; j++) {
objs = objs[shortcuts[k][j]];
}
// Always pretend we have an array
if (!Array.isArray(objs)) {
objs = [objs];
}
for (let o = 0; o < objs.length; o++) {
const obj = objs[o];
if (obj !== undefined && obj !== null && obj !== '') {
args.push(shortcutsValue[k].pos);
if (shortcutsValue[k].mod === 1) {
args.push(obj.toLowerCase());
} else if (shortcutsValue[k].mod === 2) {
args.push(obj.toUpperCase());
} else {
args.push(obj);
}
}
}
}
if (Array.isArray(key)) {
key.forEach((part) => {
setCb(part, WISESource.encodeResult.apply(null, args));
});
} else {
setCb(key, WISESource.encodeResult.apply(null, args));
}
}
endCb(null);
} catch (e) {
endCb(e);
}
} | parseJSON (body, setCb, endCb) {
try {
let json = JSON.parse(body);
if (this.keyPath === undefined) {
return endCb('No keyPath set');
}
if (this.arrayPath !== undefined) {
const arrayPath = this.arrayPath.split('.');
for (let i = 0; i < arrayPath.length; i++) {
json = json[arrayPath[i]];
if (!json) {
return endCb(`Couldn't find ${arrayPath[i]} in results`);
}
}
}
// The rest of the code assumes an array
if (!Array.isArray(json)) {
json = [json];
}
const keyPath = this.keyPath.split('.');
// Convert shortcuts into array of key path
const shortcuts = [];
const shortcutsValue = [];
for (const k in this.shortcuts) {
shortcuts.push(k.split('.'));
shortcutsValue.push(this.shortcuts[k]);
}
for (let i = 0; i < json.length; i++) {
// Walk the key path
let key = json[i];
for (let j = 0; key && j < keyPath.length; j++) {
key = key[keyPath[j]];
}
if (key === undefined || key === null) {
continue;
}
const args = [];
// Check each shortcut
for (let k = 0; k < shortcuts.length; k++) {
let objs = json[i];
// Walk the shortcut path
for (let j = 0; objs && j < shortcuts[k].length; j++) {
objs = objs[shortcuts[k][j]];
}
// Always pretend we have an array
if (!Array.isArray(objs)) {
objs = [objs];
}
for (let o = 0; o < objs.length; o++) {
const obj = objs[o];
if (obj !== undefined && obj !== null && obj !== '') {
args.push(shortcutsValue[k].pos);
if (shortcutsValue[k].mod === 1) {
args.push(obj.toLowerCase());
} else if (shortcutsValue[k].mod === 2) {
args.push(obj.toUpperCase());
} else {
args.push(obj);
}
}
}
}
if (Array.isArray(key)) {
key.forEach((part) => {
setCb(part, WISESource.encodeResult.apply(null, args));
});
} else {
setCb(key, WISESource.encodeResult.apply(null, args));
}
}
endCb(null);
} catch (e) {
endCb(e);
}
} |
JavaScript | static encodeResult () {
let l;
let len = 0;
for (let a = 1; a < arguments.length; a += 2) {
if (typeof (arguments[a]) === 'number') {
arguments[a] = arguments[a].toString();
}
l = Buffer.byteLength(arguments[a]);
if (l > 250) {
arguments[a] = arguments[a].substring(0, 240);
}
len += 3 + Buffer.byteLength(arguments[a]);
}
const buf = Buffer.allocUnsafe(len + 1);
let offset = 1;
for (let a = 1; a < arguments.length; a += 2) {
buf.writeUInt8(arguments[a - 1], offset);
len = Buffer.byteLength(arguments[a]);
buf.writeUInt8(len + 1, offset + 1);
l = buf.write(arguments[a], offset + 2);
buf.writeUInt8(0, offset + l + 2);
offset += 3 + l;
}
buf[0] = arguments.length / 2;
return buf;
} | static encodeResult () {
let l;
let len = 0;
for (let a = 1; a < arguments.length; a += 2) {
if (typeof (arguments[a]) === 'number') {
arguments[a] = arguments[a].toString();
}
l = Buffer.byteLength(arguments[a]);
if (l > 250) {
arguments[a] = arguments[a].substring(0, 240);
}
len += 3 + Buffer.byteLength(arguments[a]);
}
const buf = Buffer.allocUnsafe(len + 1);
let offset = 1;
for (let a = 1; a < arguments.length; a += 2) {
buf.writeUInt8(arguments[a - 1], offset);
len = Buffer.byteLength(arguments[a]);
buf.writeUInt8(len + 1, offset + 1);
l = buf.write(arguments[a], offset + 2);
buf.writeUInt8(0, offset + l + 2);
offset += 3 + l;
}
buf[0] = arguments.length / 2;
return buf;
} |
JavaScript | static combineResults (results) {
// Don't really need to combine 1 result
if (results.length === 1) {
return results[0] ? results[0] : WISESource.emptyResult;
}
let num = 0;
let len = 0;
for (let a = 0; a < results.length; a++) {
if (!results[a]) {
continue;
}
num += results[a][0];
len += results[a].length - 1;
}
if (len === 0) { return WISESource.emptyResult; }
const buf = Buffer.allocUnsafe(len + 1);
let offset = 1;
for (let a = 0; a < results.length; a++) {
if (!results[a]) {
continue;
}
results[a].copy(buf, offset, 1);
offset += results[a].length - 1;
}
buf[0] = num;
return buf;
} | static combineResults (results) {
// Don't really need to combine 1 result
if (results.length === 1) {
return results[0] ? results[0] : WISESource.emptyResult;
}
let num = 0;
let len = 0;
for (let a = 0; a < results.length; a++) {
if (!results[a]) {
continue;
}
num += results[a][0];
len += results[a].length - 1;
}
if (len === 0) { return WISESource.emptyResult; }
const buf = Buffer.allocUnsafe(len + 1);
let offset = 1;
for (let a = 0; a < results.length; a++) {
if (!results[a]) {
continue;
}
results[a].copy(buf, offset, 1);
offset += results[a].length - 1;
}
buf[0] = num;
return buf;
} |
JavaScript | static result2JSON (results) {
const collection = [];
let offset = 1;
for (let i = 0; i < results[0]; i++) {
const pos = results[offset];
const len = results[offset + 1];
const value = results.toString('utf8', offset + 2, offset + 2 + len - 1);
offset += 2 + len;
collection.push({ field: WISESource.pos2Field[pos], len: len - 1, value: value });
}
return JSON.stringify(collection).replace(/},{/g, '},\n{');
} | static result2JSON (results) {
const collection = [];
let offset = 1;
for (let i = 0; i < results[0]; i++) {
const pos = results[offset];
const len = results[offset + 1];
const value = results.toString('utf8', offset + 2, offset + 2 + len - 1);
offset += 2 + len;
collection.push({ field: WISESource.pos2Field[pos], len: len - 1, value: value });
}
return JSON.stringify(collection).replace(/},{/g, '},\n{');
} |
JavaScript | static request (url, file, cb) {
const headers = {};
if (file) {
if (fs.existsSync(file)) {
const stat = fs.statSync(file);
// Don't download again if file is less then 1 minutes old
if (Date.now() - stat.mtime.getTime() < 60000) {
return setImmediate(cb, 304);
}
headers['If-Modified-Since'] = stat.mtime.toUTCString();
}
}
let statusCode;
console.log(url);
request({ url: url, headers: headers })
.on('response', function (response) {
statusCode = response.statusCode;
if (response.statusCode === 200) {
this.pipe(fs.createWriteStream(file));
}
})
.on('error', (error) => {
console.log(error);
})
.on('end', () => {
setTimeout(cb, 100, statusCode);
});
} | static request (url, file, cb) {
const headers = {};
if (file) {
if (fs.existsSync(file)) {
const stat = fs.statSync(file);
// Don't download again if file is less then 1 minutes old
if (Date.now() - stat.mtime.getTime() < 60000) {
return setImmediate(cb, 304);
}
headers['If-Modified-Since'] = stat.mtime.toUTCString();
}
}
let statusCode;
console.log(url);
request({ url: url, headers: headers })
.on('response', function (response) {
statusCode = response.statusCode;
if (response.statusCode === 200) {
this.pipe(fs.createWriteStream(file));
}
})
.on('error', (error) => {
console.log(error);
})
.on('end', () => {
setTimeout(cb, 100, statusCode);
});
} |
JavaScript | sendChunk (subscriber, chunk) {
// Skip the chunk that is just [
if (chunk.length < 2) { return; }
try { // try to parse and send the chunk
const json = JSON.parse(chunk);
subscriber.next(json);
} catch (err) {
subscriber.error(`ERROR: ${err}`);
console.log(`Error parsing this chunk:\n${chunk}`);
}
} | sendChunk (subscriber, chunk) {
// Skip the chunk that is just [
if (chunk.length < 2) { return; }
try { // try to parse and send the chunk
const json = JSON.parse(chunk);
subscriber.next(json);
} catch (err) {
subscriber.error(`ERROR: ${err}`);
console.log(`Error parsing this chunk:\n${chunk}`);
}
} |
JavaScript | search ({ searchTerm, skipCache }) {
return new Observable((subscriber) => {
searchTerm = dr.refang(searchTerm.trim());
if (!searchTerm) { // nothing to do
return subscriber.complete();
}
// NOTE: this assumes that the client has already fetched the integrations
const doIntegrations = [];
for (const integration of store.state.selectedIntegrations) {
if (store.state.integrations[integration] && store.state.integrations[integration].doable) {
doIntegrations.push(integration);
}
}
fetch('api/integration/search', {
method: 'POST',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ query: searchTerm, skipCache, doIntegrations })
}).then((response) => {
if (!response.ok) { // test for bad response code (only on first chunk)
throw new Error(response.statusText);
}
return response.body;
}).then((rStream) => {
const reader = rStream.getReader();
const sendChunk = this.sendChunk;
const decoder = this.decoder;
return new ReadableStream({
start () {
let remaining = '';
function read () { // handle each data chunk
reader.read().then(({ done, value }) => {
if (done) { // stream is done
if (remaining.length) {
sendChunk(subscriber, remaining);
}
return subscriber.complete();
}
remaining += decoder(value);
let pos = 0;
while ((pos = remaining.indexOf('\n')) > -1) {
// - 1 = remove the trailing , or ]
sendChunk(subscriber, remaining.slice(0, pos - 1));
// keep the rest because it may not be complete
remaining = remaining.slice(pos + 1, remaining.length);
}
read(); // keep reading until done
});
}
read();
}
});
}).catch((err) => { // this catches an issue within the ^ .then
subscriber.error(err);
return subscriber.complete();
});
});
} | search ({ searchTerm, skipCache }) {
return new Observable((subscriber) => {
searchTerm = dr.refang(searchTerm.trim());
if (!searchTerm) { // nothing to do
return subscriber.complete();
}
// NOTE: this assumes that the client has already fetched the integrations
const doIntegrations = [];
for (const integration of store.state.selectedIntegrations) {
if (store.state.integrations[integration] && store.state.integrations[integration].doable) {
doIntegrations.push(integration);
}
}
fetch('api/integration/search', {
method: 'POST',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ query: searchTerm, skipCache, doIntegrations })
}).then((response) => {
if (!response.ok) { // test for bad response code (only on first chunk)
throw new Error(response.statusText);
}
return response.body;
}).then((rStream) => {
const reader = rStream.getReader();
const sendChunk = this.sendChunk;
const decoder = this.decoder;
return new ReadableStream({
start () {
let remaining = '';
function read () { // handle each data chunk
reader.read().then(({ done, value }) => {
if (done) { // stream is done
if (remaining.length) {
sendChunk(subscriber, remaining);
}
return subscriber.complete();
}
remaining += decoder(value);
let pos = 0;
while ((pos = remaining.indexOf('\n')) > -1) {
// - 1 = remove the trailing , or ]
sendChunk(subscriber, remaining.slice(0, pos - 1));
// keep the rest because it may not be complete
remaining = remaining.slice(pos + 1, remaining.length);
}
read(); // keep reading until done
});
}
read();
}
});
}).catch((err) => { // this catches an issue within the ^ .then
subscriber.error(err);
return subscriber.complete();
});
});
} |
JavaScript | refresh ({ itype, source, value }) {
return new Promise((resolve, reject) => {
fetch(`api/integration/${itype}/${source}/search`, {
method: 'POST',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ query: value })
}).then((response) => {
if (!response.ok) { // test for bad response code
throw new Error(response.statusText);
}
return response.json();
}).then((response) => {
return resolve(response);
}).catch((err) => { // this catches an issue within the ^ .then
return reject(err);
});
});
} | refresh ({ itype, source, value }) {
return new Promise((resolve, reject) => {
fetch(`api/integration/${itype}/${source}/search`, {
method: 'POST',
headers: setReqHeaders({ 'Content-Type': 'application/json' }),
body: JSON.stringify({ query: value })
}).then((response) => {
if (!response.ok) { // test for bad response code
throw new Error(response.statusText);
}
return response.json();
}).then((response) => {
return resolve(response);
}).catch((err) => { // this catches an issue within the ^ .then
return reject(err);
});
});
} |
JavaScript | function apiGetSettings (req, res, next) {
const cont3xt = req.user.cont3xt ?? {};
res.send({
success: true,
settings: cont3xt.settings ?? {},
linkGroup: cont3xt.linkGroup ?? {}
});
} | function apiGetSettings (req, res, next) {
const cont3xt = req.user.cont3xt ?? {};
res.send({
success: true,
settings: cont3xt.settings ?? {},
linkGroup: cont3xt.linkGroup ?? {}
});
} |
JavaScript | function apiPutSettings (req, res, next) {
let save = false;
User.getUser(req.user.userId, (err, user) => {
if (err || !user) {
return res.send({ success: false, text: 'Fetching user issue' });
}
if (user.cont3xt === undefined) { user.cont3xt = {}; }
if (req.body?.settings) {
user.cont3xt.settings = req.body.settings;
save = true;
}
if (req.body?.linkGroup) {
user.cont3xt.linkGroup = req.body.linkGroup;
save = true;
}
if (!save) {
return res.send({ success: false, text: 'Nothing sent to change' });
}
user.save((err) => {
res.send({ success: true, text: 'Saved' });
});
});
} | function apiPutSettings (req, res, next) {
let save = false;
User.getUser(req.user.userId, (err, user) => {
if (err || !user) {
return res.send({ success: false, text: 'Fetching user issue' });
}
if (user.cont3xt === undefined) { user.cont3xt = {}; }
if (req.body?.settings) {
user.cont3xt.settings = req.body.settings;
save = true;
}
if (req.body?.linkGroup) {
user.cont3xt.linkGroup = req.body.linkGroup;
save = true;
}
if (!save) {
return res.send({ success: false, text: 'Nothing sent to change' });
}
user.save((err) => {
res.send({ success: true, text: 'Saved' });
});
});
} |
JavaScript | function parseIpPort (yy, field, ipPortStr) {
const dbField = getFieldInfo(yy, field).dbField;
// Have just a single Ip, create obj for it
function parseSingleIp (exp, singleDbField, singleIp, singlePort) {
let singleObj;
if (typeof (singlePort) === 'string' && singlePort.match(/[^0-9]/)) {
throw singlePort + ' not a valid singlePort';
}
if (singleIp !== undefined) {
const colon = singleIp.indexOf(':');
if ((colon === -1 && singleIp.match(/[^.0-9/]/)) || // IP4
(colon !== -1 && singleIp.match(/[^a-fA-F:0-9/]/)) || // IP6
singleIp.match(/\/.*[^0-9]/)) { // CIDR
throw singleIp + ' not a valid ip';
}
singleObj = { term: {} };
singleObj.term[singleDbField] = singleIp;
}
if (singlePort !== -1) {
const expInfo = getFieldInfo(yy, exp);
if (expInfo.portField) {
singleObj = { bool: { filter: [singleObj, { term: {} }] } };
singleObj.bool.filter[1].term[expInfo.portField] = singlePort;
} else {
throw exp + " doesn't support port";
}
if (singleIp === undefined) {
singleObj = singleObj.bool.filter[1];
}
}
return singleObj;
}
// Special case of ip=
function parseAllIp (allIp, allPort) {
const infos = getIpInfoList(yy, allPort !== -1);
const ors = [];
for (const info of infos) {
const allObj = parseSingleIp(info.exp, info.dbField, allIp, allPort);
if (allObj) {
ors.push(allObj);
}
}
return { bool: { should: ors } };
}
let obj;
ipPortStr = ipPortStr.trim();
// We really have a list of them
if (isArrayFull(ipPortStr)) {
const list = ListToArrayMap(ipPortStr, str => parseIpPort(yy, field, str));
// Optimize 1 item in array
if (list.length === 1) {
return list[0]
}
if (isArrayAND(ipPortStr)) {
obj = { bool: { filter: list } };
} else {
obj = { bool: { should: list } };
}
return obj;
}
// Support ':80' and '.80'
if ((ipPortStr[0] === ':' && ipPortStr[0] !== ':') ||
(ipPortStr[0] === '.')) {
if (dbField !== 'ipall') {
return parseSingleIp(field, dbField, undefined, +ipPortStr.slice(1));
} else {
return parseAllIp(undefined, +ipPortStr.slice(1));
}
}
// Support ip4: '10.10.10.10' '10.10.10/16:80' '10.10.10:80' '10.10.10/16'
// Support ip6: '1::2' '1::2/16.80' '1::2.80' '1::2/16'
let ip;
let port = -1;
const colons = ipPortStr.split(':');
// More then 1 colon is ip 6
if (colons.length > 2) {
// Everything after . is port
const dots = ipPortStr.split('.');
if (dots.length > 1 && dots[1] !== '') {
port = dots[1];
}
// Everything before . is ip and slash
ip = dots[0];
} else {
// everything after : is port
if (colons.length > 1 && colons[1] !== '') {
port = colons[1];
}
// Have to do extra because we allow shorthand for /8, /16, /24
const slash = colons[0].split('/');
const dots = slash[0].split('.');
// If the last one is empty just pretend . isn't there, for auto complete
if (dots[dots.length - 1] === '') {
dots.length--;
}
switch (dots.length) {
case 4:
ip = `${dots[0]}.${dots[1]}.${dots[2]}.${dots[3]}`;
break;
case 3:
ip = `${dots[0]}.${dots[1]}.${dots[2]}.0`;
if (slash[1] === undefined) { slash[1] = '24'; }
break;
case 2:
ip = `${dots[0]}.${dots[1]}.0.0`;
if (slash[1] === undefined) { slash[1] = '16'; }
break;
case 1:
if (dots[0].length > 0) {
ip = `${dots[0]}.0.0.0`;
if (slash[1] === undefined) { slash[1] = '8'; }
}
break;
}
// Add the slash back to the ip
if (slash[1] && slash[1] !== '32') {
ip = `${ip}/${slash[1]}`;
}
}
if (dbField !== 'ipall') {
return parseSingleIp(field, dbField, ip, port);
} else {
return parseAllIp(ip, port);
}
} | function parseIpPort (yy, field, ipPortStr) {
const dbField = getFieldInfo(yy, field).dbField;
// Have just a single Ip, create obj for it
function parseSingleIp (exp, singleDbField, singleIp, singlePort) {
let singleObj;
if (typeof (singlePort) === 'string' && singlePort.match(/[^0-9]/)) {
throw singlePort + ' not a valid singlePort';
}
if (singleIp !== undefined) {
const colon = singleIp.indexOf(':');
if ((colon === -1 && singleIp.match(/[^.0-9/]/)) || // IP4
(colon !== -1 && singleIp.match(/[^a-fA-F:0-9/]/)) || // IP6
singleIp.match(/\/.*[^0-9]/)) { // CIDR
throw singleIp + ' not a valid ip';
}
singleObj = { term: {} };
singleObj.term[singleDbField] = singleIp;
}
if (singlePort !== -1) {
const expInfo = getFieldInfo(yy, exp);
if (expInfo.portField) {
singleObj = { bool: { filter: [singleObj, { term: {} }] } };
singleObj.bool.filter[1].term[expInfo.portField] = singlePort;
} else {
throw exp + " doesn't support port";
}
if (singleIp === undefined) {
singleObj = singleObj.bool.filter[1];
}
}
return singleObj;
}
// Special case of ip=
function parseAllIp (allIp, allPort) {
const infos = getIpInfoList(yy, allPort !== -1);
const ors = [];
for (const info of infos) {
const allObj = parseSingleIp(info.exp, info.dbField, allIp, allPort);
if (allObj) {
ors.push(allObj);
}
}
return { bool: { should: ors } };
}
let obj;
ipPortStr = ipPortStr.trim();
// We really have a list of them
if (isArrayFull(ipPortStr)) {
const list = ListToArrayMap(ipPortStr, str => parseIpPort(yy, field, str));
// Optimize 1 item in array
if (list.length === 1) {
return list[0]
}
if (isArrayAND(ipPortStr)) {
obj = { bool: { filter: list } };
} else {
obj = { bool: { should: list } };
}
return obj;
}
// Support ':80' and '.80'
if ((ipPortStr[0] === ':' && ipPortStr[0] !== ':') ||
(ipPortStr[0] === '.')) {
if (dbField !== 'ipall') {
return parseSingleIp(field, dbField, undefined, +ipPortStr.slice(1));
} else {
return parseAllIp(undefined, +ipPortStr.slice(1));
}
}
// Support ip4: '10.10.10.10' '10.10.10/16:80' '10.10.10:80' '10.10.10/16'
// Support ip6: '1::2' '1::2/16.80' '1::2.80' '1::2/16'
let ip;
let port = -1;
const colons = ipPortStr.split(':');
// More then 1 colon is ip 6
if (colons.length > 2) {
// Everything after . is port
const dots = ipPortStr.split('.');
if (dots.length > 1 && dots[1] !== '') {
port = dots[1];
}
// Everything before . is ip and slash
ip = dots[0];
} else {
// everything after : is port
if (colons.length > 1 && colons[1] !== '') {
port = colons[1];
}
// Have to do extra because we allow shorthand for /8, /16, /24
const slash = colons[0].split('/');
const dots = slash[0].split('.');
// If the last one is empty just pretend . isn't there, for auto complete
if (dots[dots.length - 1] === '') {
dots.length--;
}
switch (dots.length) {
case 4:
ip = `${dots[0]}.${dots[1]}.${dots[2]}.${dots[3]}`;
break;
case 3:
ip = `${dots[0]}.${dots[1]}.${dots[2]}.0`;
if (slash[1] === undefined) { slash[1] = '24'; }
break;
case 2:
ip = `${dots[0]}.${dots[1]}.0.0`;
if (slash[1] === undefined) { slash[1] = '16'; }
break;
case 1:
if (dots[0].length > 0) {
ip = `${dots[0]}.0.0.0`;
if (slash[1] === undefined) { slash[1] = '8'; }
}
break;
}
// Add the slash back to the ip
if (slash[1] && slash[1] !== '32') {
ip = `${ip}/${slash[1]}`;
}
}
if (dbField !== 'ipall') {
return parseSingleIp(field, dbField, ip, port);
} else {
return parseAllIp(ip, port);
}
} |
JavaScript | function parseSingleIp (exp, singleDbField, singleIp, singlePort) {
let singleObj;
if (typeof (singlePort) === 'string' && singlePort.match(/[^0-9]/)) {
throw singlePort + ' not a valid singlePort';
}
if (singleIp !== undefined) {
const colon = singleIp.indexOf(':');
if ((colon === -1 && singleIp.match(/[^.0-9/]/)) || // IP4
(colon !== -1 && singleIp.match(/[^a-fA-F:0-9/]/)) || // IP6
singleIp.match(/\/.*[^0-9]/)) { // CIDR
throw singleIp + ' not a valid ip';
}
singleObj = { term: {} };
singleObj.term[singleDbField] = singleIp;
}
if (singlePort !== -1) {
const expInfo = getFieldInfo(yy, exp);
if (expInfo.portField) {
singleObj = { bool: { filter: [singleObj, { term: {} }] } };
singleObj.bool.filter[1].term[expInfo.portField] = singlePort;
} else {
throw exp + " doesn't support port";
}
if (singleIp === undefined) {
singleObj = singleObj.bool.filter[1];
}
}
return singleObj;
} | function parseSingleIp (exp, singleDbField, singleIp, singlePort) {
let singleObj;
if (typeof (singlePort) === 'string' && singlePort.match(/[^0-9]/)) {
throw singlePort + ' not a valid singlePort';
}
if (singleIp !== undefined) {
const colon = singleIp.indexOf(':');
if ((colon === -1 && singleIp.match(/[^.0-9/]/)) || // IP4
(colon !== -1 && singleIp.match(/[^a-fA-F:0-9/]/)) || // IP6
singleIp.match(/\/.*[^0-9]/)) { // CIDR
throw singleIp + ' not a valid ip';
}
singleObj = { term: {} };
singleObj.term[singleDbField] = singleIp;
}
if (singlePort !== -1) {
const expInfo = getFieldInfo(yy, exp);
if (expInfo.portField) {
singleObj = { bool: { filter: [singleObj, { term: {} }] } };
singleObj.bool.filter[1].term[expInfo.portField] = singlePort;
} else {
throw exp + " doesn't support port";
}
if (singleIp === undefined) {
singleObj = singleObj.bool.filter[1];
}
}
return singleObj;
} |
JavaScript | function termOrTermsDate (dbField, str) {
if (isArrayFull(str)) {
const items = []
ListToArray(str).forEach(function (astr) {
const d = moment.unix(parseSeconds(stripQuotes(astr))).format();
const r = { range: {} };
r.range[dbField] = { gte: d, lte: d };
items.push(r);
});
if (isArrayAND(str)) {
return { bool: { filter: items } };
} else {
return { bool: { should: items } };
}
}
const d = moment.unix(parseSeconds(stripQuotes(str))).format();
const obj = { range: {} };
obj.range[dbField] = { gte: d, lte: d };
return obj;
} | function termOrTermsDate (dbField, str) {
if (isArrayFull(str)) {
const items = []
ListToArray(str).forEach(function (astr) {
const d = moment.unix(parseSeconds(stripQuotes(astr))).format();
const r = { range: {} };
r.range[dbField] = { gte: d, lte: d };
items.push(r);
});
if (isArrayAND(str)) {
return { bool: { filter: items } };
} else {
return { bool: { should: items } };
}
}
const d = moment.unix(parseSeconds(stripQuotes(str))).format();
const obj = { range: {} };
obj.range[dbField] = { gte: d, lte: d };
return obj;
} |
JavaScript | function importTransformer(context) {
return (node) => {
/**
* @param {typescript.Node} node
*/
function visitor(node) {
if (shouldMutateModuleSpecifier(node)) {
if (typescript.isImportDeclaration(node)) {
const newModuleSpecifier = typescript.createLiteral(`${node.moduleSpecifier.text}.js`);
return typescript.updateImportDeclaration(
node,
node.decorators,
node.modifiers,
node.importClause,
newModuleSpecifier,
);
} else if (typescript.isExportDeclaration(node)) {
const newModuleSpecifier = typescript.createLiteral(`${node.moduleSpecifier.text}.js`);
return typescript.updateExportDeclaration(
node,
node.decorators,
node.modifiers,
node.exportClause,
newModuleSpecifier,
);
}
}
return typescript.visitEachChild(node, visitor, context);
}
return typescript.visitNode(node, visitor);
};
} | function importTransformer(context) {
return (node) => {
/**
* @param {typescript.Node} node
*/
function visitor(node) {
if (shouldMutateModuleSpecifier(node)) {
if (typescript.isImportDeclaration(node)) {
const newModuleSpecifier = typescript.createLiteral(`${node.moduleSpecifier.text}.js`);
return typescript.updateImportDeclaration(
node,
node.decorators,
node.modifiers,
node.importClause,
newModuleSpecifier,
);
} else if (typescript.isExportDeclaration(node)) {
const newModuleSpecifier = typescript.createLiteral(`${node.moduleSpecifier.text}.js`);
return typescript.updateExportDeclaration(
node,
node.decorators,
node.modifiers,
node.exportClause,
newModuleSpecifier,
);
}
}
return typescript.visitEachChild(node, visitor, context);
}
return typescript.visitNode(node, visitor);
};
} |
JavaScript | function buildWatch() {
gulp.watch('src/**/*.ts', { ignoreInitial: false }, buildTS);
gulp.watch('src/**/*.less', { ignoreInitial: false }, buildLess);
gulp.watch('src/**/*.scss', { ignoreInitial: false }, buildSASS);
gulp.watch('src/**/*.js', { ignoreInitial: false }, buildJS);
gulp.watch('src/**/*.mjs', { ignoreInitial: false }, buildMJS);
gulp.watch('src/**/*.css', { ignoreInitial: false }, buildCSS);
gulp.watch(['src/fonts', 'src/lang', 'src/templates', 'src/*.json'], { ignoreInitial: false }, copyFiles);
} | function buildWatch() {
gulp.watch('src/**/*.ts', { ignoreInitial: false }, buildTS);
gulp.watch('src/**/*.less', { ignoreInitial: false }, buildLess);
gulp.watch('src/**/*.scss', { ignoreInitial: false }, buildSASS);
gulp.watch('src/**/*.js', { ignoreInitial: false }, buildJS);
gulp.watch('src/**/*.mjs', { ignoreInitial: false }, buildMJS);
gulp.watch('src/**/*.css', { ignoreInitial: false }, buildCSS);
gulp.watch(['src/fonts', 'src/lang', 'src/templates', 'src/*.json'], { ignoreInitial: false }, copyFiles);
} |
JavaScript | async function clean() {
const name = path.basename(path.resolve('.'));
const files = [];
// If the project uses TypeScript
if (fs.existsSync(path.join('src', `${name}.ts`))) {
files.push(
'lang',
'templates',
'packs',
'assets',
'icons',
'module',
'modules',
`${name}.js`,
'module.json',
'system.json',
'template.json',
);
}
// If the project uses Less or SASS
if (fs.existsSync(path.join('src', `${name}.less`)) || fs.existsSync(path.join('src', `${name}.scss`))) {
files.push('fonts', `${name}.css`);
}
console.log(' ', chalk.yellow('Files to clean:'));
console.log(' ', chalk.blueBright(files.join('\n ')));
// Attempt to remove the files
try {
for (const filePath of files) {
await fs.remove(path.join('dist', filePath));
}
return Promise.resolve();
} catch (err) {
Promise.reject(err);
}
} | async function clean() {
const name = path.basename(path.resolve('.'));
const files = [];
// If the project uses TypeScript
if (fs.existsSync(path.join('src', `${name}.ts`))) {
files.push(
'lang',
'templates',
'packs',
'assets',
'icons',
'module',
'modules',
`${name}.js`,
'module.json',
'system.json',
'template.json',
);
}
// If the project uses Less or SASS
if (fs.existsSync(path.join('src', `${name}.less`)) || fs.existsSync(path.join('src', `${name}.scss`))) {
files.push('fonts', `${name}.css`);
}
console.log(' ', chalk.yellow('Files to clean:'));
console.log(' ', chalk.blueBright(files.join('\n ')));
// Attempt to remove the files
try {
for (const filePath of files) {
await fs.remove(path.join('dist', filePath));
}
return Promise.resolve();
} catch (err) {
Promise.reject(err);
}
} |
JavaScript | async function linkUserData() {
const name = path.basename(path.resolve('.'));
const config = fs.readJSONSync('foundryconfig.json');
let destDir;
try {
if (
fs.existsSync(path.resolve('.', 'dist', 'module.json')) ||
fs.existsSync(path.resolve('.', 'src', 'module.json'))
) {
destDir = 'modules';
} else if (
fs.existsSync(path.resolve('.', 'dist', 'system.json')) ||
fs.existsSync(path.resolve('.', 'src', 'system.json'))
) {
destDir = 'systems';
} else {
throw Error(`Could not find ${chalk.blueBright('module.json')} or ${chalk.blueBright('system.json')}`);
}
let linkDir;
if (config.dataPath) {
if (!fs.existsSync(path.join(config.dataPath, 'Data')))
throw Error('User Data path invalid, no Data directory found');
linkDir = path.join(config.dataPath, 'Data', destDir, name);
} else {
throw Error('No User Data path defined in foundryconfig.json');
}
if (argv.clean || argv.c) {
console.log(chalk.yellow(`Removing build in ${chalk.blueBright(linkDir)}`));
await fs.remove(linkDir);
} else if (!fs.existsSync(linkDir)) {
console.log(chalk.green(`Copying build to ${chalk.blueBright(linkDir)}`));
await fs.symlink(path.resolve('./dist'), linkDir);
}
return Promise.resolve();
} catch (err) {
Promise.reject(err);
}
} | async function linkUserData() {
const name = path.basename(path.resolve('.'));
const config = fs.readJSONSync('foundryconfig.json');
let destDir;
try {
if (
fs.existsSync(path.resolve('.', 'dist', 'module.json')) ||
fs.existsSync(path.resolve('.', 'src', 'module.json'))
) {
destDir = 'modules';
} else if (
fs.existsSync(path.resolve('.', 'dist', 'system.json')) ||
fs.existsSync(path.resolve('.', 'src', 'system.json'))
) {
destDir = 'systems';
} else {
throw Error(`Could not find ${chalk.blueBright('module.json')} or ${chalk.blueBright('system.json')}`);
}
let linkDir;
if (config.dataPath) {
if (!fs.existsSync(path.join(config.dataPath, 'Data')))
throw Error('User Data path invalid, no Data directory found');
linkDir = path.join(config.dataPath, 'Data', destDir, name);
} else {
throw Error('No User Data path defined in foundryconfig.json');
}
if (argv.clean || argv.c) {
console.log(chalk.yellow(`Removing build in ${chalk.blueBright(linkDir)}`));
await fs.remove(linkDir);
} else if (!fs.existsSync(linkDir)) {
console.log(chalk.green(`Copying build to ${chalk.blueBright(linkDir)}`));
await fs.symlink(path.resolve('./dist'), linkDir);
}
return Promise.resolve();
} catch (err) {
Promise.reject(err);
}
} |
JavaScript | function updateManifest(cb) {
const packageJson = fs.readJSONSync('package.json');
const config = getConfig(),
manifest = getManifest(),
rawURL = config.rawURL,
repoURL = config.repository,
manifestRoot = manifest.root;
if (!config) cb(Error(chalk.red('foundryconfig.json not found')));
if (!manifest) cb(Error(chalk.red('Manifest JSON not found')));
if (!rawURL || !repoURL) cb(Error(chalk.red('Repository URLs not configured in foundryconfig.json')));
try {
const version = argv.update || argv.u;
/* Update version */
const versionMatch = /^(\d{1,}).(\d{1,}).(\d{1,})$/;
const currentVersion = manifest.file.version;
let targetVersion = '';
if (!version) {
cb(Error('Missing version number'));
}
if (versionMatch.test(version)) {
targetVersion = version;
} else {
targetVersion = currentVersion.replace(versionMatch, (substring, major, minor, patch) => {
console.log(substring, Number(major) + 1, Number(minor) + 1, Number(patch) + 1);
if (version === 'major') {
return `${Number(major) + 1}.0.0`;
} else if (version === 'minor') {
return `${major}.${Number(minor) + 1}.0`;
} else if (version === 'patch') {
return `${major}.${minor}.${Number(patch) + 1}`;
} else {
return '';
}
});
}
if (targetVersion === '') {
return cb(Error(chalk.red('Error: Incorrect version arguments.')));
}
if (targetVersion === currentVersion) {
return cb(Error(chalk.red('Error: Target version is identical to current version.')));
}
console.log(`Updating version number to '${targetVersion}'`);
packageJson.version = targetVersion;
manifest.file.version = targetVersion;
/* Update URLs */
const result = `${rawURL}/v${manifest.file.version}/package/${manifest.file.name}-v${manifest.file.version}.zip`;
manifest.file.url = repoURL;
manifest.file.manifest = `${rawURL}/master/${manifestRoot}/${manifest.name}`;
manifest.file.download = result;
const prettyProjectJson = stringify(manifest.file, {
maxLength: 35,
indent: '\t',
});
fs.writeJSONSync('package.json', packageJson, { spaces: '\t' });
fs.writeFileSync(path.join(manifest.root, manifest.name), prettyProjectJson, 'utf8');
return cb();
} catch (err) {
cb(err);
}
} | function updateManifest(cb) {
const packageJson = fs.readJSONSync('package.json');
const config = getConfig(),
manifest = getManifest(),
rawURL = config.rawURL,
repoURL = config.repository,
manifestRoot = manifest.root;
if (!config) cb(Error(chalk.red('foundryconfig.json not found')));
if (!manifest) cb(Error(chalk.red('Manifest JSON not found')));
if (!rawURL || !repoURL) cb(Error(chalk.red('Repository URLs not configured in foundryconfig.json')));
try {
const version = argv.update || argv.u;
/* Update version */
const versionMatch = /^(\d{1,}).(\d{1,}).(\d{1,})$/;
const currentVersion = manifest.file.version;
let targetVersion = '';
if (!version) {
cb(Error('Missing version number'));
}
if (versionMatch.test(version)) {
targetVersion = version;
} else {
targetVersion = currentVersion.replace(versionMatch, (substring, major, minor, patch) => {
console.log(substring, Number(major) + 1, Number(minor) + 1, Number(patch) + 1);
if (version === 'major') {
return `${Number(major) + 1}.0.0`;
} else if (version === 'minor') {
return `${major}.${Number(minor) + 1}.0`;
} else if (version === 'patch') {
return `${major}.${minor}.${Number(patch) + 1}`;
} else {
return '';
}
});
}
if (targetVersion === '') {
return cb(Error(chalk.red('Error: Incorrect version arguments.')));
}
if (targetVersion === currentVersion) {
return cb(Error(chalk.red('Error: Target version is identical to current version.')));
}
console.log(`Updating version number to '${targetVersion}'`);
packageJson.version = targetVersion;
manifest.file.version = targetVersion;
/* Update URLs */
const result = `${rawURL}/v${manifest.file.version}/package/${manifest.file.name}-v${manifest.file.version}.zip`;
manifest.file.url = repoURL;
manifest.file.manifest = `${rawURL}/master/${manifestRoot}/${manifest.name}`;
manifest.file.download = result;
const prettyProjectJson = stringify(manifest.file, {
maxLength: 35,
indent: '\t',
});
fs.writeJSONSync('package.json', packageJson, { spaces: '\t' });
fs.writeFileSync(path.join(manifest.root, manifest.name), prettyProjectJson, 'utf8');
return cb();
} catch (err) {
cb(err);
}
} |
JavaScript | _printTimestamp(logLevel, separator = this.#separator) {
const timestamp = `${this.#openQuote}${new Date().toLocaleTimeString(this.#locales, this.#options)}${this.#closeQuote}${separator}`;
switch (logLevel) {
case this.#LOG_LEVEL.log:
case this.#LOG_LEVEL.info:
case this.#LOG_LEVEL.warn: {
process.stdout.write(timestamp);
break;
}
case this.#LOG_LEVEL.error: {
process.stderr.write(timestamp);
break;
}
default: {
throw new Error('An undefined `logLevel` was specified as an argument. `logLevel` must be one of the groups defined below. <https://console.spec.whatwg.org/#loglevel-severity>');
}
}
} | _printTimestamp(logLevel, separator = this.#separator) {
const timestamp = `${this.#openQuote}${new Date().toLocaleTimeString(this.#locales, this.#options)}${this.#closeQuote}${separator}`;
switch (logLevel) {
case this.#LOG_LEVEL.log:
case this.#LOG_LEVEL.info:
case this.#LOG_LEVEL.warn: {
process.stdout.write(timestamp);
break;
}
case this.#LOG_LEVEL.error: {
process.stderr.write(timestamp);
break;
}
default: {
throw new Error('An undefined `logLevel` was specified as an argument. `logLevel` must be one of the groups defined below. <https://console.spec.whatwg.org/#loglevel-severity>');
}
}
} |
JavaScript | function doAuthRedirect() {
//Creating the url to authenticate the client using config from above
var url = config.authUrl + 'login/oauth2/auth?state=' + config.state +
'&response_type=' + config.response_type + '&redirect_uri=' + config.redirectUri + '&client_id=' + config.client_id + '&scope=' + config.scope;
//Sends the user to the url when connectbutton is clicked
window.location.href = url;
} | function doAuthRedirect() {
//Creating the url to authenticate the client using config from above
var url = config.authUrl + 'login/oauth2/auth?state=' + config.state +
'&response_type=' + config.response_type + '&redirect_uri=' + config.redirectUri + '&client_id=' + config.client_id + '&scope=' + config.scope;
//Sends the user to the url when connectbutton is clicked
window.location.href = url;
} |
JavaScript | function updateUIWithAuthState(hasAuth) {
if (hasAuth) {
$(".notsignedin").css('display', 'none');
$(".signedin").css('display', 'block');
} else {
$(".notsignedin").css('display', 'block');
$(".signedin").css('display', 'none');
}
} | function updateUIWithAuthState(hasAuth) {
if (hasAuth) {
$(".notsignedin").css('display', 'none');
$(".signedin").css('display', 'block');
} else {
$(".notsignedin").css('display', 'block');
$(".signedin").css('display', 'none');
}
} |
JavaScript | function callUserStoryAPI(p){
//if (table.tableInfo.id == "UserStory"){
var pageStart = (p * 2000) + 1;
//Creating the request to retreive data from rally
console.log("projectid rallywdc: ", projectID);
var xhr = $.ajax({
//Sending the access token to rally to show we have been authenticated
beforeSend: function(request) {
request.setRequestHeader("zsessionid", accessToken);
},
//Url that for that request
url: "https://rally1.rallydev.com/slm/webservice/v2.0/hierarchicalrequirement?workspace=https://rally1.rallydev.com/slm/webservice/v2.0/workspace/23724738313&query=(PortfolioItem.Tags.Name%20contains%20Testing)&fetch=FormattedID,PortfolioItem&start="+ pageStart +"&pagesize=2000",
dataType: 'json',
success: function (data) {
//Where all the JSON data is stored
var feat=data;
console.log(feat);
//Reterving data for entery in feat object
for (var i = 0, len = feat.QueryResult.Results.length; i < len; i++) {
//pushing data to tableau tabel object
tableData.push({
"FormattedID": feat.QueryResult.Results[i].FormattedID,
"PortfolioIitemFormattedID": feat.QueryResult.Results[i].PortfolioItem.FormattedID,
});
}
var lastPage = false;
if (p == Math.ceil(feat.QueryResult.TotalResultCount/2000)){
lastPage = true;
}
if (!lastPage){
table.appendRows(tableData);
tableData = [];
callUserStoryAPI(p+1);
}else{
doneCallback();
}
//table.appendRows(tableData);
//doneCallback();
}
});
} | function callUserStoryAPI(p){
//if (table.tableInfo.id == "UserStory"){
var pageStart = (p * 2000) + 1;
//Creating the request to retreive data from rally
console.log("projectid rallywdc: ", projectID);
var xhr = $.ajax({
//Sending the access token to rally to show we have been authenticated
beforeSend: function(request) {
request.setRequestHeader("zsessionid", accessToken);
},
//Url that for that request
url: "https://rally1.rallydev.com/slm/webservice/v2.0/hierarchicalrequirement?workspace=https://rally1.rallydev.com/slm/webservice/v2.0/workspace/23724738313&query=(PortfolioItem.Tags.Name%20contains%20Testing)&fetch=FormattedID,PortfolioItem&start="+ pageStart +"&pagesize=2000",
dataType: 'json',
success: function (data) {
//Where all the JSON data is stored
var feat=data;
console.log(feat);
//Reterving data for entery in feat object
for (var i = 0, len = feat.QueryResult.Results.length; i < len; i++) {
//pushing data to tableau tabel object
tableData.push({
"FormattedID": feat.QueryResult.Results[i].FormattedID,
"PortfolioIitemFormattedID": feat.QueryResult.Results[i].PortfolioItem.FormattedID,
});
}
var lastPage = false;
if (p == Math.ceil(feat.QueryResult.TotalResultCount/2000)){
lastPage = true;
}
if (!lastPage){
table.appendRows(tableData);
tableData = [];
callUserStoryAPI(p+1);
}else{
doneCallback();
}
//table.appendRows(tableData);
//doneCallback();
}
});
} |
JavaScript | function SlideObject(image) {
this.image = image; // add and image key that is assigned to the image parameter
this.id = `slider__${slideIndex}`;
slideIndex++;
slideArray.push(this);
} | function SlideObject(image) {
this.image = image; // add and image key that is assigned to the image parameter
this.id = `slider__${slideIndex}`;
slideIndex++;
slideArray.push(this);
} |
JavaScript | AVAILABLE() {
chrome.browserAction.setIcon({
tabId: tab.id,
path: {
32: 'img/bot_32.png',
64: 'img/bot_64.png',
},
});
chrome.browserAction.setPopup({
tabId: tab.id,
popup: 'popup.html',
});
/**
* track the actived tabs that have been redirected to
* new host, activate the recordation under the new host
*/
if (activeTabList.find(i => i.id === tab.id)) {
signal.toContentScript(tab.id, {
action: 'START_RECORD',
/**
* tell content script that it has been redirected
*/
from: 'BG',
});
}
/** there is unfinished task */
const stepIndex = taskList.findIndex(({ tabId }) => tabId === tab.id);
if (stepIndex >= 0) {
signal.toContentScript(tab.id, {
action: 'RESTORE',
step: taskList[stepIndex].step + 1,
name: taskList[stepIndex].name
});
taskList.splice(stepIndex, 1);
}
} | AVAILABLE() {
chrome.browserAction.setIcon({
tabId: tab.id,
path: {
32: 'img/bot_32.png',
64: 'img/bot_64.png',
},
});
chrome.browserAction.setPopup({
tabId: tab.id,
popup: 'popup.html',
});
/**
* track the actived tabs that have been redirected to
* new host, activate the recordation under the new host
*/
if (activeTabList.find(i => i.id === tab.id)) {
signal.toContentScript(tab.id, {
action: 'START_RECORD',
/**
* tell content script that it has been redirected
*/
from: 'BG',
});
}
/** there is unfinished task */
const stepIndex = taskList.findIndex(({ tabId }) => tabId === tab.id);
if (stepIndex >= 0) {
signal.toContentScript(tab.id, {
action: 'RESTORE',
step: taskList[stepIndex].step + 1,
name: taskList[stepIndex].name
});
taskList.splice(stepIndex, 1);
}
} |
JavaScript | async RESTORE_STATU({ step, name }) {
taskList.push({
tabId: tab.id,
step,
name
});
} | async RESTORE_STATU({ step, name }) {
taskList.push({
tabId: tab.id,
step,
name
});
} |
JavaScript | broadcast(tabId, message) {
if (tabId) {
this.toContentScript(tabId, message);
}
this.send(EMsgType.TO_BG, message);
this.send(EMsgType.TO_POPUP);
} | broadcast(tabId, message) {
if (tabId) {
this.toContentScript(tabId, message);
}
this.send(EMsgType.TO_BG, message);
this.send(EMsgType.TO_POPUP);
} |
Subsets and Splits