Calculate the sum of a specific array data - node.js

After calling all the data from my database, I would like to try and calculate the individual values of my array. I have made 2 users state as "banned"
//get all banned status for all users
res.data.data.forEach((dataItem, index) => {
console.log(`Banned ${index}`, dataItem.banned);
I would like to try and get the sum of "banned" and "not banned" which in this case is "banned 2" and "NotBanned 2"
tried this but dint work
for (const dataItem of res.data.data) {
let NotBanned = 0;
if(dataItem.banned === false){
NotBanned++;
console.log("Not Banned", NotBanned);
}
}
for (const dataItem of res.data.data) {
var BannedUsers = 0;
if(dataItem.banned === true){
BannedUsers++;
console.log("Not Banned",BannedUsers);
}
}

let
bannedUsers = 0,
unBannedUsers = 0;
const response = res.data.data
for(let users = 0; users < response.length; users ++ ) {
if(!response.banned) {
unBannedUsers += users;
}
else {
bannedUsers += users;
}
}
console.log(`Banned Users : ${bannedUsers} , UnBanned Users : ${unBannedUsers}` )

Related

In firebase cloud function the child is self-deleting

When I add a transaction in the function below, the child of the "guncelLig" is automatically deleted. When I remove the second transaction there is no problem, it works very well.
this code work correct :
for (let i = 0; i < users.length; i++) {
const userID = users[i].id;
database.ref().child("users").child("profilData").child(userID).child("guncelLig").transaction(function (value) {
if (value > 1) {
database.ref().child("users").child("profilData").child(userID).update({
"lastUpdate": toSwiftDate(),
});
return value - 1;
}
return value;
});
}
but when I add the new part to the code below, "guncelLig" is completely deleted from the firebase realtime databse:
for (let i = 0; i < users.length; i++) {
const userID = users[i].id;
database.ref().child("users").child("profilData").child(userID).child("guncelLig").transaction(function (value) {
if (value > 1) {
database.ref().child("users").child("profilData").child(userID).update({
"lastUpdate": toSwiftDate(),
});
/// NEW CODE ERROR SOURCHE
database.ref().child("users").child("profilData").child(userID).child("EnYukselLig").transaction(function (EnYukselLig) {
if (EnYukselLig > value - 1) {
return value - 1;
}
return EnYukselLig;
});
return value - 1; // arttır
}
return value; /// ALWAYS RETURN NULL
});
}
Where am I doing wrong? please help me
You should write your code as async/await. With await you can wait for the nested transaction to finish.
for (let i = 0; i < users.length; i++) {
const userID = users[i].id;
database
.ref()
.child("users")
.child("profilData")
.child(userID)
.child("guncelLig")
.transaction(async (value) => {
if (value > 1) {
await database
.ref()
.child("users")
.child("profilData")
.child(userID)
.update({
lastUpdate: toSwiftDate(),
});
/// NEW CODE ERROR SOURCHE
await database
.ref()
.child("users")
.child("profilData")
.child(userID)
.child("EnYukselLig")
.transaction(function (EnYukselLig) {
if (EnYukselLig > value - 1) {
return value - 1;
}
return EnYukselLig;
});
return value - 1; // arttır
}
// No handler if the value is NULL
return value; /// ALWAYS RETURN NULL
});
}
You also don't handle the case if value is already null.
It is not recommmended to nest transactions like that. Transacions by nature can run multiple times and there is no guaranty that they finish as expected depending on the amount of updates that happen on the same location.

discord js how to sort json file money by descending

I try to sort a money in my json file but every time i get "money.slice is not a function"
can someone help with this? "money.sort((a,b)=>{b.money - a.money});" dont work to
My JSON file:
{"2858236346346":{"name":"user1","money":100}}, {"346342356347436":{"name":"user2","money":1000}}
The Code I have trouble with:
execute(client, message, args) {
let rawdata = fs.readFileSync('./money.json');
let money = JSON.parse(rawdata);
console.log(money);
const res = money.slice().sort((a, b) => b.money - a.money);
console.log(res);
let embed = new Discord.MessageEmbed()
.setTitle("Najbogatsi Gracze")
//if there are no results
if (res.length === 0) {
embed.setColor("RED");
embed.setThumbnail("https://i.imgur.com/pWHpi7G.png");
embed.addField("Nie znaleziono danych", "Wpisz na czacie $daily aby zdobyć pieniądze!")
} else if (res.length < 10) {
//less than 10 results
embed.setColor("BLURPLE");
embed.setThumbnail("https://i.imgur.com/pWHpi7G.png");
for (i = 0; i < res.length; i++) {
let member = message.guild.members.cache.get(res[i].id) || "Brak danych"
if (member === "Brak danych") {
embed.addField(`${i + 1}. ${member}`, `**Kasa:**: ${res[i].money}zł`);
} else {
embed.addField(`${i + 1}. ${member.user.username}`, `**Kasa:**: ${res[i].money}zł`);
}
...
Nevermind I just figured it out we must use loop and define new "const" in this case "res = [];" so then we can push a new json and then sort it
let money = JSON.parse(fs.readFileSync("./money.json", "utf8"));
const res = [];
for(let userID in money){
res.push({"id": userID, "money": money[userID].money })
res.sort((a, b) => Object.values(b)[1] - Object.values(a)[1])
console.log(money, res);
}

roles.forEach not a function

So basically what is happening, is this code is running when a command is run. If the user's string (UserID) fits into the array, it responds as true and sets the access level to 6. If that is false, it checks for roles and sets the access level if they have certain roles by the role names. However, the role names part is not working. For example, a user with the Moderator role (normally access level 3 / perms.three), is showing up as access level 0 and I cannot figure out why.
The way this is supposed to work is that it checks the ID of a user. If that ID is in a pre-defined array located in a .json file, it overrides all other access levels by giving an access level of 6. If the array doesn't exist it moves onto the roles function and searches to see if the role exists in the persons list of roles.
This is what I use to check the roles/userID.
if (command.accessLevel > perms.getAccess(message.member.roles) || command.accessLevel > perms.getAccess(message.member.id)){
return message.channel.send("``Error: Access Denied.``");
}
This is the permissions.js file:
const bot = require('./bot').skynet;
const config = require('./config.json');
const perms = require('./permissions.json').access;
function arrayHas(arr, val){
var result = false;
for (var item in arr){
if (arr[item] == val){
result = true;
break;
}
}
return result;
}
function getAccess(user){
var access = 0;
if (typeof(user) == 'string'){
if (arrayHas(perms.six, user)){
return 6;
}
}
var roles = user;
roles.forEach(function(role){
if (arrayHas(perms.five, role.name)){
access = 5;
return;
}
else if (arrayHas(perms.four, role.name)){
access = 4;
return;
}
else if (arrayHas(perms.three, role.name)){
access = 3;
return;
}
else if (arrayHas(perms.two, role.name)){
access = 2;
return;
}
else if (arrayHas(perms.one, role.name)){
access = 1;
return;
}
});
return access;
}
bot.on('message', message => {
console.log(getAccess(message.member.id));
console.log(getAccess(message.member.roles));
})
module.exports = {
arrayHas: arrayHas,
getAccess: getAccess,
};
In the first if statement, you should return a value after the inside if statement. Otherwise, you'll continue to the following code roles.forEach for a string which will fail (roles.forEach is not a function)
Or place the non-string logic inside an else statement:
function getAccess(user){
var access = 0;
if (typeof(user) == 'string'){
if (arrayHas(perms.six, user)){
return 6;
}
} else {
var roles = user;
roles.forEach(function(role){
if (arrayHas(perms.five, role.name)){
access = 5;
return;
}
else if (arrayHas(perms.four, role.name)){
access = 4;
return;
}
else if (arrayHas(perms.three, role.name)){
access = 3;
return;
}
else if (arrayHas(perms.two, role.name)){
access = 2;
return;
}
else if (arrayHas(perms.one, role.name)){
access = 1;
return;
}
});
}
return access;
}
In your function getAccess(), you're setting the access variable but never actually returning the value. Try this revised version.
const Discord = require('discord.js');
const { skynet: bot } = require('./bot');
const config = require('./config.json');
const { access: perms } = require('./permissions.json');
/**
* Return the access level of a member.
* #param {Discord.GuildMember} member
*/
function getAccess(member) {
if (!(member instanceof Discord.GuildMember)) return new TypeError('Expected a GuildMember.');
if (arrayHas(perms.six, member.user.id)) return 6;
const roles = member.roles;
for (const role of roles) {
if (arrayHas(perms.five, role.name)) return 5;
if (arrayHas(perms.four, role.name)) return 4;
if (arrayHas(perms.three, role.name)) return 3;
if (arrayHas(perms.two, role.name)) return 2;
if (arrayHas(perms.one, role.name)) return 1;
}
return 0;
}

values get undefined after then of promise nodejs

I'm facing a problem with my code... I make a query to my DB to check if a mac address of a array of macs is on the DB. If I have any result I return the count of macs in my DB and if is > 0 then I don't add nothing cause the mac already is listed, but if my result.count = 0 then I will add a new record.
My new record just have the mac address. For this I'm trying:
var countRepetidos = 0
var countPromises = []
if (obj.data.list != {} && obj.data.list.length > 0) {
var aux = obj.data["list"]
countRepetidos = 0
for (var i = 0; i < aux.length; i++) {
countPromises.push(Database.Probing.getMacAdress(aux[i]).then(function(data) {
console.log("probing countPromises aux[i] ", aux[i])
if (data.count > 0) {
countRepetidos += 1
} else {
Database.Probing.addMac(aux[i])
}
return Promise.resolve()
}))
}
Promise.all(countPromises).then(() => {
dataRepeated = [obj.data.stats.since, countRepetidos]
listaRepeated.push(dataRepeated)
console.log("probing listaRepeated --> ", listaRepeated)
if (listaRepeated != [] && (listaRepeated[0][0] != undefined && listaRepeated[0][1] != undefined)) {
Database.Probing.getLastTimestamp("probing_repeated", device.id).then(function(data) {
var lastTimestamp = data.date_part
console.log('probing lastTimestamp ', lastTimestamp * 1000)
if (lastTimestamp != listaRepeated[0][0] / 1000) {
Controllers.Agregate.agregateData("probing_repeated", 5 * 60, listaRepeated, dbHistConnectionString, device.id, device.network_id, device.organization_id, ["time", "clients"])
}
})
}
})
}
The problem is after the then of Database.Probing.getMacAddress my aux[i] gets undefined and I need this value to insert into my DB.
Anyone can help?
You need to preserve the value of i. You can do this way:
for (var i = 0; i < aux.length; i++) {
(function(i) {
countPromises.push(
Database.Probing.getMacAdress(aux[i]).then(function(data) {
console.log("probing countPromises aux[i] ", aux[i])
if (data.count > 0) {
countRepetidos += 1
} else {
Database.Probing.addMac(aux[i])
}
return Promise.resolve()
}))
})(i)
}
Edit 1: As suggested by #lain, use let over var
for (let i = 0; i < aux.length; i++) {}

Opening tabs in Chrome news reader extension

I'm trying to create a simple chrome extension using the following google RSS reader sample,
http://code.google.com/chrome/extensions/samples.html#597015d3bcce3da693b02314afd607bec4f55291
I can add links in the pop-up window that open tabs, but not from the feeds themselves.
Looping through the items in the feed, grabbing title tags and link tags, I want the title to link the the appropriate sites
var entries = doc.getElementsByTagName('item');
var count = Math.min(entries.length, maxFeedItems);
for (var i = 0; i < count; i++) {
item = entries.item(i);
// Grab the title for the feed item.
var itemTitle = item.getElementsByTagName('title')[0];
if (itemTitle) {
itemTitle = itemTitle.textContent;
} else {
itemTitle = "Unknown title";
}
// Grab the link for this feed item
var itemLink = item.getElementsByTagName('link')[0];
if (itemLink) {
itemLink = itemLink.textContent;
} else {
itemLink = "Unknown link";
}
var title = document.createElement("a");
title.className = "item_title";
title.innerText = itemTitle; //display title in iframe
title.addEventListener("click", titleLink); // should open link when clicking on title, but does not.
}
// -------------------------------------------------------------------
// Show |url| in a new tab.
function showUrl(url) {
// Only allow http and https URLs.
if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
return;
}
chrome.tabs.create({url: url});
}
function moreStories(event) {
showUrl(moreStoriesUrl);
}
function titleLink(event) {
showUrl(itemLink);
}
Any thoughts on why this is not working.
If I replace title.addEventListener("click", titleLink); with title.addEventListener("click", moreStories); each title will link to moreStories, I cannot get each title to link to itemLink.
Thanks
Its a bit hard to answer your question without the whole code, but Ill give it a shot ;)
First up, titleLink() isnt going to work because itemLink isnt known. When you create title (the link) you should of attached it to that...say title.href=itemLink then in tiltleLinks you could access that href with showUrl(event.currentTarget.href)
Also did you fix the error in that example?...if not then change frameLoaded to....
function frameLoaded() {
var links = document.getElementsByTagName("A");
for (i = 0; i < links.length; i++) {
var clssName = links[i].className;
if (clssName != "item_title" && clssName != "open_box") {
links[i].addEventListener("click", showStory);
}
}
window.addEventListener("message", messageHandler);
}
If you still have probs could you attach the whole code so I can see what your doing and Ill give you a hand.
Thank you very much for your help.
code title.href=itemLink and code showUrl(event.currentTarget.href) was exactly what I needed.
For completeness, here is the full code,
<script id="iframe_script">
function reportHeight() {
var msg = JSON.stringify({type:"size", size:document.body.offsetHeight});
parent.postMessage(msg, "*");
}
function frameLoaded() {
var links = document.getElementsByTagName("A");
for (i = 0; i < links.length; i++) {
var class = links[i].className;
if (class != "item_title" && class != "open_box") {
links[i].addEventListener("click", showStory);
}
}
window.addEventListener("message", messageHandler);
}
function showStory(event) {
var href = event.currentTarget.href;
parent.postMessage(JSON.stringify({type:"show", url:href}), "*");
event.preventDefault();
}
function messageHandler(event) {
reportHeight();
}
</script>
<script>
// Feed URL.
var feedUrl = 'http://localhost/newsfeed.xml';
// The XMLHttpRequest object that tries to load and parse the feed.
var req;
function main() {
req = new XMLHttpRequest();
req.onload = handleResponse;
req.onerror = handleError;
req.open("GET", feedUrl, true);
req.send(null);
}
// Handles feed parsing errors.
function handleFeedParsingFailed(error) {
var feed = document.getElementById("feed");
feed.className = "error";
feed.innerText = "Error: " + error;
}
// Handles errors during the XMLHttpRequest.
function handleError() {
handleFeedParsingFailed('Failed to fetch RSS feed.');
}
// Handles parsing the feed data we got back from XMLHttpRequest.
function handleResponse() {
var doc = req.responseXML;
if (!doc) {
handleFeedParsingFailed("Not a valid feed.");
return;
}
buildPreview(doc);
}
// The maximum number of feed items to show in the preview.
var maxFeedItems = 10;
// Where the more stories link should navigate to.
var moreStoriesUrl;
function buildPreview(doc) {
// Get the link to the feed source.
var link = doc.getElementsByTagName("link");
var parentTag = link[0].parentNode.tagName;
if (parentTag != "item" && parentTag != "entry") {
moreStoriesUrl = link[0].textContent;
}
// Setup the title image.
var images = doc.getElementsByTagName("image");
var titleImg;
if (images.length != 0) {
var urls = images[0].getElementsByTagName("url");
if (urls.length != 0) {
titleImg = urls[0].textContent;
}
}
var img = document.getElementById("title");
// Listen for mouse and key events
if (titleImg) {
img.src = titleImg;
if (moreStoriesUrl) {
document.getElementById("title_a").addEventListener("click",moreStories);
document.getElementById("title_a").addEventListener("keydown",
function(event) {
if (event.keyCode == 13) {
moreStories(event);
}});
}
} else {
img.style.display = "none";
}
// Construct the iframe's HTML.
var iframe_src = "<!doctype html><html><head><script>" +
document.getElementById("iframe_script").textContent + "<" +
"/script></head><body onload='frameLoaded();' " +
"style='padding:0px;margin:0px;'>";
var feed = document.getElementById("feed");
// Set ARIA role indicating the feed element has a tree structure
feed.setAttribute("role", "tree");
var entries = doc.getElementsByTagName('item');
var count = Math.min(entries.length, maxFeedItems);
for (var i = 0; i < count; i++) {
item = entries.item(i);
// Grab the title for the feed item.
var itemTitle = item.getElementsByTagName('title')[0];
if (itemTitle) {
itemTitle = itemTitle.textContent;
} else {
itemTitle = "Unknown title";
}
// Grab the link for the feed item.
var itemLink = item.getElementsByTagName('link')[0];
if (itemLink) {
itemLink = itemLink.textContent;
} else {
itemLink = "Unknown link";
}
var item = document.createElement("div");
var title = document.createElement("a");
title.innerText = itemTitle; //display title in iframe
title.href=itemLink;
title.addEventListener("click", titleLink);
item.appendChild(title);
feed.appendChild(item);
}
if (moreStoriesUrl) {
var more = document.createElement("a");
more.className = "more";
more.innerText = "***Site Main Page*** \u00BB";
more.tabIndex = 0;
more.addEventListener("click", moreStories);
more.addEventListener("keydown", function(event) {
if (event.keyCode == 13) {
moreStories(event);
}});
feed.appendChild(more);
}
}
// -------------------------------------------------------------------
// Show |url| in a new tab.
function showUrl(url) {
// Only allow http and https URLs.
if (url.indexOf("http:") != 0 && url.indexOf("https:") != 0) {
return;
}
chrome.tabs.create({url: url});
}
// -------------------------------------------------------------------
function moreStories(event) {
showUrl(moreStoriesUrl);
}
function titleLink(event) {
showUrl(event.currentTarget.href);
}
function keyHandlerShowDesc(event) {
// Display content under heading when spacebar or right-arrow pressed
// Hide content when spacebar pressed again or left-arrow pressed
// Move to next heading when down-arrow pressed
// Move to previous heading when up-arrow pressed
if (event.keyCode == 32) {
showDesc(event);
} else if ((this.parentNode.className == "item opened") &&
(event.keyCode == 37)) {
showDesc(event);
} else if ((this.parentNode.className == "item") && (event.keyCode == 39)) {
showDesc(event);
} else if (event.keyCode == 40) {
if (this.parentNode.nextSibling) {
this.parentNode.nextSibling.children[1].focus();
}
} else if (event.keyCode == 38) {
if (this.parentNode.previousSibling) {
this.parentNode.previousSibling.children[1].focus();
}
}
}
function showDesc(event) {
var item = event.currentTarget.parentNode;
var items = document.getElementsByClassName("item");
for (var i = 0; i < items.length; i++) {
var iframe = items[i].getElementsByClassName("item_desc")[0];
if (items[i] == item && items[i].className == "item") {
items[i].className = "item opened";
iframe.contentWindow.postMessage("reportHeight", "*");
// Set the ARIA state indicating the tree item is currently expanded.
items[i].getElementsByClassName("item_title")[0].
setAttribute("aria-expanded", "true");
iframe.tabIndex = 0;
} else {
items[i].className = "item";
iframe.style.height = "0px";
// Set the ARIA state indicating the tree item is currently collapsed.
items[i].getElementsByClassName("item_title")[0].
setAttribute("aria-expanded", "false");
iframe.tabIndex = -1;
}
}
}
function iframeMessageHandler(e) {
// Only listen to messages from one of our own iframes.
var iframes = document.getElementsByTagName("IFRAME");
for (var i = 0; i < iframes.length; i++) {
if (iframes[i].contentWindow == e.source) {
var msg = JSON.parse(e.data);
if (msg) {
if (msg.type == "size") {
iframes[i].style.height = msg.size + "px";
}
else if (msg.type == "show") {
var url = msg.url;
if (url.indexOf("http://localhost/index.html") == 0) {
// If the URL is a redirect URL, strip of the destination and go to
// that directly. This is necessary because the Google news
// redirector blocks use of the redirects in this case.
var index = url.indexOf("&url=");
if (index >= 0) {
url = url.substring(index + 5);
index = url.indexOf("&");
if (index >= 0)
url = url.substring(0, index);
}
}
showUrl(url);
}
}
return;
}
}
}
window.addEventListener("message", iframeMessageHandler);
</script>
Thanks again for the help.
-Mike

Resources