I've created this function.
I think I'm missing something very obvious but when I call this function, it keeps running where instead I only want "tweeter" to run once when it is called. Instead, it seems to be looping every minute or so and then posting again.
Any help would be greatly appreciated.
function tweeter() {
//Fetch API Documentation
fetch('[MY API URL]').then(response=> response.json()).then(function (data) {
//Function to create array
//Define Array
var array =[];
let tweetText ='';
//Loop data.data
for (var i = 0; i < data.data.length; i++) {
var minutes = (data.data[i][1]);
//Push values to Array
array.push(minutes);
}
//SUM of array
var sum = array.reduce(function(a, b){
return a + b;
}, 0);
//Return rounded value of average of Cork City sensors.
let sensorAverage = (Math.round(sum / data.data.length));
/* Messaging based on the SensorAverage returned.
Based on EU PM2.5 AQI
0-10:
10-20:
20-25:
50-75:
75-800:
800:
*/
if(sensorAverage <= 10){
tweetText = " \n\n0-10 = Good. \n\nThe air quality is good in Cork City at the moment. \nEnjoy your usual outdoor activities worry-free. " ;
} else if((sensorAverage >=10.1) && (sensorAverage <=19.9)){
tweetText = "\n\n10-20 = Fair. \n\nThe air quality is fair in Cork City at the moment.. \nEnjoy your usual outdoor activities.";
} else if((sensorAverage >=20) && (sensorAverage <=24.9)){
tweetText = "\n\n20-25 = Moderate. \n\nThe air quality is moderate in Cork City at the moment. \nEnjoy your usual outdoor activities. Sensitive groups should consider reducing intense outdoor activities, if you experience symptoms.";
} else if((sensorAverage >=25) && (sensorAverage <=49.9)){
tweetText = "\n\n20-25 = Moderate. \n\nThe air quality is moderate in Cork City at the moment. \nEnjoy your usual outdoor activities. Sensitive groups should consider reducing intense outdoor activities, if you experience symptoms.";
}else if((sensorAverage >=50) && (sensorAverage <=74.9)){
tweetText = "\n\n50-75 = Very Poor. \n\nThe air quality is very poor in Cork City at the moment. \nConsider reducing intense activities outdoors. Sensitive groups should reduce physical activities.";
} else if((sensorAverage >=75) && (sensorAverage <=)){
tweetText = "\n\n75-800 = Extremely Poor. \n\nThe air quality is very poor in Cork City at the moment. \nReduce physical activities outdoors. Sensitive groups should avoid physical activities outdoors.";
} else if (sensorAverage > 800){
tweetText = "\n\n>800 = Catastrophicly Poor. \n\nThe air quality is catastrophic in Cork City at the moment. \nAvoid outdoor activities.";
}
var tweet = "The average reading across Cork City is currently " + sensorAverage + "*. " + tweetText + "\n\n*Based on EU PM2.5 AQI. \n\n#CorkAirQuality";
T.post('statuses/update', { status: tweet }, tweeter);
});
}
I am thinking it's this line :-
T.post('statuses/update', { status: tweet }, tweeter);
This can be possible if you're passing tweeter as a callback function to your T.post code (I am not aware of how you implemented it).
So everytime the POST request completes, the tweeter callback might be getting triggered.
Related
I'm working on a tuition calculator for students and updating it to reflect the current year, in changing the year, every time the #variable option is selected to Variable (inherited code, not my choice of name) the output duplicates all of the fees. I've revised the functions, and code, where is this issue arising?
(my current version with issues: https://tarleton.edu/scripts/tuitioncal/default-trial.asp)
At first I thought it was a year issue, but after reading through previous documentation, I corrected it but issue is still arising.
I'm assuming that the issue arises here and that it runs through this if/else statement twice, though the information is not changing:
$('input#submit').click(function() {
var currentDate = new Date();
var currentYear = currentDate.getFullYear(); //Currently in the middle of
the academic year, so the adjustment had to be made.
var adjustedYear = 0;
var adjustmentForYear = 0;
if ($('select#semester option:selected').hasClass('current-academic-year')){ adjustmentForYear = parseInt(-1); }
else if ($('select#semester option:selected').hasClass('future-academic-year')) { adjustmentForYear = parseInt(0); }
else if ($('select#semester option:selected').hasClass('last-year')) { adjustmentForYear = parseInt(-2); }
if ($("select#variable option:selected").val() != "variable" || $('select#classification option:selected').val() == "4")
{
//Handles ALL Guaranteed Tuition Plans and Graduate Plan
adjustedYear = (parseInt($('select#semester option:selected').val()) +
adjustmentForYear - $('select#classification option:selected').val());
}
else
{ //Handles Variable Tuition Plans for Freshmen, Sophomores, Juniors, and Seniors
adjustedYear = currentYear + adjustmentForYear;
}
I expect a non duplicated output that includes University Services fee to be $91.66, but instead see University Services fee: $991.66 AND $117.89.
I came across this program from a You Don't Know JS books book on github:
const SPENDING_THRESHOLD = 200;
const TAX_RATE = 0.08;
const PHONE_PRICE = 99.99;
const ACCESSORY_PRICE = 9.99;
var bank_balance = 303.91;
var amount = 0;
function calculateTax(amount) {
return amount * TAX_RATE;
}
function formatAmount(amount) {
return "$" + amount.toFixed( 2 );
}
// keep buying phones while you still have money
while (amount < bank_balance) {
// buy a new phone!
amount = amount + PHONE_PRICE;
// can we afford the accessory?
if (amount < SPENDING_THRESHOLD) {
amount = amount + ACCESSORY_PRICE;
}
}
// don't forget to pay the government, too
amount = amount + calculateTax( amount );
console.log(
"Your purchase: " + formatAmount( amount )
);
// Your purchase: $334.76
// can you actually afford this purchase?
if (amount > bank_balance) {
console.log(
"You can't afford this purchase. :("
);
}
// You can't afford this purchase. :(
My issue is that it does not matter if I change the value of bank_balance to a higher value, but it keeps printing : You can't afford this purchase.
I have try to make it so it does not print : You can't afford this purchase.
I can't make it work. I'm starting to think that the program is wrong, but I think is just me.
I know the solution is simple but I cant see it nor find it.
It comes from your while(amount < bank_balance). You increase amount until it's bigger than bank_balance. So obviously, it's bigger than bank_balance after that.
Also, you can use the developer tools available in every modern browser (F12 for Chrome or Firefox will open them), where you can put break points and follow your code's flow.
I don't know what the program is meant to do but it doesn't seem to make much sense to me.
It "buys" phones as long as you have money, but doesn't check if you have enough money for an additional phone.
So in the end of the while loop you have spend exactly your whole money on phones or (much more likely) spend more money than you have.
On top of this there are accessorizes and taxes. So in the end, you won't ever be able to afford your purchase.
And no matter how high you raise you balance, the program is written to exceed it.
The programm would work probably better with the line
while (amount + PHONE_PRICE + calculateTax(amount + PHONE_PRICE) <= bank_balance)
or even
while (amount + PHONE_PRICE + ACCESSORY_PRICE + calculateTax(amount + PHONE_PRICE + ACCESSORY_PRICE)<= bank_balance)
Although I have to admit that I'm not sure what the purpose of the SPENDING_THRESHOLD is.
You keep adding new phones and accessories until it reaches the total amount. I guess total cost becomes very close to the amount hence when you add the tax on top of that it crosses the limit and you see that message. I would suggest you to compare(in the while loop) the phone price along with the tax. Something like:
while (amount + PHONE_PRICE + calculateTax( PHONE_PRICE ) < bank_balance) {
// buy a new phone!
amount = amount + PHONE_PRICE + calculateTax( PHONE_PRICE );
// can we afford the accessory?
if (amount < SPENDING_THRESHOLD) {
amount = amount + ACCESSORY_PRICE;
}
}
Refer https://jsfiddle.net/Lxwscbbq/
Open the browser console to see the messages.
Program is not wrong it is simple:
var bank_balance = 303.91;
which is global. Suppose you provided
amount = 200;
amount = amount + calculateTax( amount );
amount = 200 + calculateTax(200);
if you check condition and you can see amount is grater than entered amount. Thats why you are getting "You can't afford purchase"
if (amount > bank_balance) {
console.log(
"You can't afford this purchase. :("
);
}
I'm making a game where the player can pick 3 different characters. However I am running into a glaring problem, that being, when I create a function (like a attack function), it is linked to only 1 specific character.
I would rather have my code be written where when the person picks their character, all can use the same attack skill without me having to write 3 different ones. Also, the attack skills are linked to a button, so it must be diverse.
I can't have a designated attack button for X player. So how do I make my code so it can add all characters instead of just 1 specified character?
Example: Looking at my function below for the strike attack. I can set it to dwarf & angel which is fine. However what if the player picks a ELF character instead? Then the function will not work because it believes the character is a dwarf, fighting a angel. How can I fix this?
New=Object.create;
actor = {
primaryStats: function (level, hp, hpcap, balance, balancecap, exp){
this.level = level;
this.hp = hp;
this.hpcap = hpcap;
this.balance = balance;
this.balancecap = balancecap;
this.exp = exp;
},
player = New (actor),
monster = New (actor),
dwarf = New(player),
human = New(player),
elf = New(player),
angel = New(monster),
demon = New(monster),
dragon = New(monster);
//ATTACK SKILL ONE
dom.el("strike").onclick = function strike() {
playerHitCalc(dwarf, angel);
};
playerHitCalc = function(character, boss){
roll = Math.floor(Math.random() * character.accuracy + 1);
if (roll > boss.agility){
var hit = true;
}
else {
hit = false;
logMessage(boss.ID + " " + "has evaded your attack!")
}
playerDamCalc = function(){
if (hit == true){ //If you score a successful hit
var damage = Math.floor(Math.random() * character.strength + 1);
var totalDamage = damage - boss.armor; // Subtract Damage from Bosses Armor
if(totalDamage <= 0)totalDamage += boss.armor; // Add boss armor to prevent Negative Numbers
boss.hp -= totalDamage; // Subtract bosses HP from damage.
character.exp += totalDamage * 0.25; // Gain 1 exp point per 4 damage done
dom.setText("bosshealthcounter", boss.hp) // Update Bosses Health
logMessage("You hit " + boss.ID + " for " + totalDamage + " damage!");
}
You can use data attributes to link a dom element to particular characters. For example -
<button class="attack-btn" data-attacker="dwarf" data-target="angel">Attack</button>
Then in the on click handler, you can extract that particular element's attributes attacker and target instead of hardcoding the values.
Hope that helps!
One thing you are doing is creating Player and Monster from Actor and then specific player class from Player and the same for monster.
Problem lies in that now you have a specific handle for each type of player and each type of monster.
If we would want to edit current code, you would have to add currentPlayer and currentMonster variables that you would make equal to the Player and Monster you want to fight. Then you could avoid referencing specific player and specific monster and just use
playerHitCalc(currentPlayer, currentMonster);
But I would suggest changing things a little bit and create objects in a little different way.
I'm trying to allow my prices to display under 2 conditions
sales price must be less than the base price
"don't show pricing is unchecked" (yes or no) in our system
var basPrc = "$5000";
var onlnPrc = "<%=getAttribute('item','382798','salesprice')%>";
var CallForPrice = "<%=getAttribute('item','382798','dontshowprice')%>";
if (onlnPrc < basPrc || CallForPrice == "No") {
document.write('<span class="strike">Base Price: <span>'+basPrc+'</span></span>')
document.write("<br /><strong class=\"saleprice\">Our Price: <%=getAttribute('item','382798','salesprice')%></strong><br />");
//savings
var savings = onlnPrc - basPrc;
document.write ('<span class="save">You Save: <span class="red">'+ savings +'</span></span><br />');
}
//if don't show pricing is checked
if (CallForPrice = "Yes") {
var basPrc = null;
var onlnPrc = null;
document.write('<br /><strong class="saleprice">Call For Pricing<strong><br />');
}
//if no online pricing
else {document.write('<br /><strong class="saleprice">Our Price: '+basPrc+' <strong><br />');}
I tried the "&&" operators and no luck, any idea on what I should do next?
Your basPrc is a String, not a Number; you should initialize it to 5000, not "$5000" (the lack of quotes being important here). I'm not sure at all what onlnPrc will be. You need to make sure both are numbers. Otherwise, when you do basPrc > onlnPrc you will be doing a String comparison, not a numeric one.
// Base Price defaults to 5000
var basPrc = 5000;
// Parse the Online Price as a floating point number;
// if the result is NaN, default it to 0
var onlnPrc = parseFloat("<%=getAttribute('item','382798','salesprice')%>") || 0;
You should endeavor to make sure that basPrc and onlnPrc are always numbers since you are doing calculations with them. Leave the display of currency symbols or decimal points to the pieces of the code where you actually display the data.
Unrelated question: Where does this code live? What's it for? I've never seen NetSuite code that looked anything like this.
I hope someone can help with this:
I am currently working on a motor dealership website. On this website is a car loan calculator that calculates your monthly repayments. I have successfully created a basic calculator that calculates the correct amount.
The client isn't happy with that. They want a more advanced calculator that calculates the monthly repayments with balloon considerations and a deposit and initiation and admin fees.
I altered the code to reflect that, but now the thing won't work anymore. I can't find any error in my code.
Here's the Javascript that's supposed to do the calculation:
function calculate() {
// Get the user's input from the form. Assume it is all valid.
// Convert interest from a percentage to a decimal, and convert from
// an annual rate to a monthly rate. Convert payment period in years
// to the number of monthly payments.
var principal = document.loandata.principal.value;
var lessDeposit = document.loandata.deposit.value;
var adminFee = document.loandata.admin.value;
var initiationFee = document.loandata.initiation.value;
var interest = document.loandata.interest.value / 100 / 12;
var payments = document.loandata.years.value * 12;
var balloonPercent = document.loandata.balloon.value / 100;
// Now compute the monthly payment figure, using esoteric math.
var balloonFinal = (principal * balloonPercent);
var totalPrincipal = (principal + initiationFee + balloonfinal - lessDeposit);
var x = Math.pow(1 + interest, payments);
var monthly = (totalPrincipal*x*interest)/(x-1);
// Check that the result is a finite number. If so, display the results
if (!isNaN(monthly) &&
(monthly != Number.POSITIVE_INFINITY) &&
(monthly != Number.NEGATIVE_INFINITY)) {
document.loandata.payment.value = round(monthly + adminFee);
document.loandata.total.value = round(monthly * payments);
document.loandata.totalinterest.value =
round((monthly * payments) - principal);
}
// Otherwise, the user's input was probably invalid, so don't
// display anything.
else {
document.loandata.payment.value = "";
document.loandata.total.value = "";
document.loandata.totalinterest.value = "";
}
}
// This simple method rounds a number to two decimal places.
function round(x) {
return Math.round(x*100)/100;
}
Also, if possible, there needs to be some validation. Like purchase price, interest rate and payment period are required fields. But the rest are not. So if someone fills in the required fields but not the rest, the calculator still needs to work, but if someone does NOT complete one of the required fields, they need to be prompted to do so.
For those who don't know what a balloon payment is, here's an example;
Purchase Price is R117 000
You decide on a balloon payment of 30%. On the initial purchase price, the 30% amounts to R35 100. This amount is then subtracted from your initial purchase price so that means your purchase is now R81 900. After that comes the deposit, which is subtracted, and the extras and the admin and initiation fees. So the monthly repayments are calculated using this new purchase price of R81 900 + extras - deposit (if any). For interest sake, after your contract ends, you have to pay the balloon amount in full or re-finance the vehicle.
PS: I'm a complete newbie when it comes to JavaScript. So any help would be greatly appreciated.
If the result is nothing, one of these three conditions is likely triggering the else statement:
if (!isNaN(monthly) &&
(monthly != Number.POSITIVE_INFINITY) &&
(monthly != Number.NEGATIVE_INFINITY)) {
You have a typo in the JS, you need to change balloonfinal to be balloonFinal with a capital F in the var totalPrincipal = line of code.
The principal, lessDeposit, adminFee, initiationFee may also need to be typecast as an integer/float.