Code gives out "strange output" - google-apps-script

I am haveing some trubble witht this code. My output will look somthing like this. "29 days, 29 days, 0 hours, 29 minutes". The only variable outside of the code is toon.lastModified. it can be somthing like 1431769709000 . The task for the code is to tell how mutch time that have passed from now, untill there was a change in the JSON. I got the feeling that the problem is that + is used to add numbers and to set strings into each other.
var nowTime = new Date()
var timeStamp = nowTime.getTime()
var lastModTS = ((timeStamp-toon.lastModified)/1000).toFixed(0)
var lastModS = (lastModTS%60)
var lastModMin = (((lastModTS-lastModS)/60)%60)
var lastModH = (((lastModTS-(lastModS+lastModMin*60))/60)%24)
var lastModDay = (Math.floor((lastModTS-(lastModS+lastModMin*60+lastModH*60^2))/(24*60^2)))
var sinceLastMod=""
if (lastModDay==1){
sinceLastMod=lastModDay+" day, "
} else if (lastModDay>1){
sinceLastMod=lastModDay+" days, "
} if (lastModH==1){
sinceLastMod=sinceLastMod+lastModH+" hour, "
} else if (lastModH==0&&lastModDay==0){
sinceLastMod=""
} else {
sinceLastMod=sinceLastMod+sinceLastMod+lastModH+" hours, "
} if (lastModMin==1){
sinceLastMod=lastModDay+" minute, "
} else if (lastModMin==0&&lastModH==0&&lastModDay==0){
sinceLastMod=">1 minute"
} else if (lastModMin>1){
sinceLastMod=sinceLastMod+lastModMin+" minutes"
}
return sinceLastMod //it does not look like this in the code, as it is retuned in an array
EDIT
found another thing
at the end of lastModDay, Google would not do the expotensial, i had to wright it to 60*60 for it to get it.

This line:
sinceLastMod=sinceLastMod+sinceLastMod+lastModH+" hours, "
Should be:
sinceLastMod=sinceLastMod+lastModH+" hours, "
Remove one of the sinceLastMod variables. You've got it in there twice.

Related

Comparing 2 strings from HTML file - Angular

I am using angular 7 and I would like to know how to compare two strings. In this case, each of my strings simulates one date, let's say "2019-12-26" and "2018-12-26".
In Javascript is pretty simple to compare them since I just need to use the operators:
console.log(today > "2018-12-06");
It is working how I supposed it was gonna work. It basically returns true. Nevertheless, I am trying to do exactly the same from my HTML file
<div *ngIf="today > example.endDate">
being today and 'example.endDate' two strings containing exactly the same strings that I used for the Javascript example, but it does not show any of them.
Is there any other way to make this comparison?
Regards,
Mario
UPDATE
I have had a second look at the problem and it seems that the comparison is not a problem, but the way of getting the variable is.
I get a variable in ngOnInit().
ngOnInit() {
this.getCurrentDate();
}
//Get current date
getCurrentDate() {
let aux = new Date();
//2 characteres
let dd = String(aux.getDate()).padStart(2, "0");
let mm = String(aux.getMonth() + 1).padStart(2, "0"); //January is 0!
let yyyy = aux.getFullYear();
let today = yyyy + "-" + mm + "-" + dd;
let other = "2019-01-31";
}
The problem is that I use this variable directly in my HTML how I previously showed. The error I get is the following:
ERROR Error: ExpressionChangedAfterItHasBeenCheckedError: Expression
has changed after it was checked. Previous value: 'ngIf: undefined'.
Current value: 'ngIf: true'.
So the problem is that I am using a variable in the HTML file before getting the value. Or at least it is what I understand
To check this error I have created a Stackblitz representation. On it, I have created two examples:
Variables not on ngOnInit()
Variables in ngOnInit()
https://stackblitz.com/edit/angular-jjgsmq?file=src%2Fapp%2Fhello.component.ts
the most simple solution is just to
and are you sure that ngOnInit is the right LifeCycle hook for you?
I would try ngAfterContentInit() if the component is "heavy" to render other wise ngAfterViewInit() would have been my choice
<div *ngIf="IsTodayBigger()">
ngOnInit() {
this.getCurrentDate();
}
IsTodayBigger(): boolean {
today=this.getCurrentDate()
exampleEndDate= example.endDate;//use binding or ViewChild if needed
return today&&exampleEndDate&& today> example.endDate
}
//Get current date
getCurrentDate() {
let aux = new Date();
//2 characteres
let dd = String(aux.getDate()).padStart(2, "0");
let mm = String(aux.getMonth() + 1).padStart(2, "0"); //January is 0!
let yyyy = aux.getFullYear();
today = yyyy + "-" + mm + "-" + dd;
let other = "2019-01-31";
}

Undefined result from function (html script)

I'm trying to calculate total pay from inputs given by the user in an html script. I keep getting an undefined result for total pay. I've tried calling the calculate_pay function from the second script tags but that didn't change anything. What am I doing wrong?
<!DOCTYPE html>
<head>
<title>Chapter 4 Assignment</title>
<script>
function input_output(netPay)
{
var hoursWorked = prompt("How many hours have you worked?","");
var payRate = prompt ("What is your hourly pay rate?","");
var taxRate = prompt ("What is the tax rate for your state? ex. 11 for 11%","");
var br = "<br>";
document.write("Hours worked: "+hoursWorked+br);
document.write("Pay rate: "+payRate+br);
document.write("Tax rate: "+taxRate+br);
document.write("Total pay: "+netPay+br);
}
function calculate_pay(hoursWorked,payRate,taxRate)
{
var taxRate = taxRate/100;
var grossPay = (hoursWorked*taxRate);
var netPay = grossPay - (taxRate * grossPay);
return netPay;
}
</script>
</head>
<body>
<script>
input_output();
</script>
</body>
</html>
I've tried calling the calculate_pay function in input_output like this:
function input_output(netPay)
{
var hoursWorked = prompt("How many hours have you worked?","");
var payRate = prompt ("What is your hourly pay rate?","");
var taxRate = prompt ("What is the tax rate for your state? ex. 11 for 11%","");
var br = "<br>";
calculate_pay();
document.write("Hours worked: "+hoursWorked+br);
document.write("Pay rate: "+payRate+br);
document.write("Tax rate: "+taxRate+br);
document.write("Total pay: "+netPay+br);
}
As well as calling it in the second script tags and both at the same time but it still returns undefined.
You are only calling the input_output() function, which prompts the user for hoursWorked, payRate, and taxRate, but never calculates anything. The parameter to input_output(), netPay, is probably misplaced. You should call your function calculate_pay() to actually get that value.
The last line in your first function should be
document.write("Total pay: " + calculate_pay(hoursWorked,payRate,taxRate) + br);
But before even getting there, you must take care to convert the input values from String to a Number using parseFloat. That is, for each prompt that you have, do the following:
var hoursWorked = parseFloat(
prompt("How many hours have you worked?","")
);
Whatever the user types will always be a String, so always remember to convert those string values to an actual Number using the parseFloat() method.
I think you want something like this instead:
function input_output() {...} // get rid of the input parameter
Add this after the var taxRate line:
var netPay = calculate_pay(hoursWorked, payRate, taxRate);

Google Docs Script Issue with Split through Function

First time poster here for Google Script related services, hopefully I put it in the right place! I'm encountering an error and I can't seem to find the right terminology to look up a solution. Below is the function. Within it I have a variable, string1, that I apply the split to. If I hard-code the value of the string (in the line commented out in the string), then it works and I receive the correct output. If, on the other hand, I try to pass that string into the function from another function, I receive the following error:
"TypeError: Cannot find function split in object Wed Oct 30 2013 09:00:26 GMT-0400 (EDT),danno,ticket,netid,request,mac,Error - Invalid Mac / Mac Not Found."
Note: My call to the function looks like this - formatEmailRow(completeEmailArray[i])
function formatEmailRow(rowToFormat) {
var formattedString = "";
var array1 = [];
var string1 = "";
///////////////////////
string1 = rowToFormat;
//string1 ="10/30/2013 9:00:26,danno,ticket,netid,request,mac,Error - Invalid Mac / Mac Not Found ";
///////////////////////
array1 = string1.split(",| ,|, ");
if (array1 != ""){
for (var i = 0; i < array1.length; i++) {
formattedString = formattedString + " " +(array1[i]);
}}
return formattedString;
}
Please help!
Thanks ahead of time, any advice is appreciated!
-Danno
You're getting that error because .split() isn't a method contained in the type of object you've passed in. Since you're new to this, it's worth a pause to read up on Objects and Methods - this is a quick overview.
You want to receive a String, but it seems that you're not. The problem will be with the code that's calling formatEmailRow().
My guess is that you're passing an array - probably all the cells in a row - but here's how you can check.
Add this line as the first line in your function:
Logger.log("rowToFormat = " + JSON.stringify(rowToFormat));
... then run, with your error. Check the logs - you want to see that you are getting a simple string. If you're getting an array, then you know what you need to fix. (Maybe you want to get the array after all!)

"CalendarApp: Mismatch: etags" when adding reminders - Google Apps Scripts

I have a small Google Apps Script that processes a date column in a spreadsheet and generates entries in a Calendar (birthdays).
Work is fine, but when adding reminders to the (recently-created) CalendarEvent, an error is thrown :
Service error: CalendarApp: Mismatch: etags = ["GUQKRgBAfip7JGA6WhJb"], version = [63489901413]
I've tried to perform 1 second sleep after creating event (wait for changes to be done in calendar), but no luck on this...
BTW, events are created succesfully, only reminders cannot be added.
PD: the calendar is one I own, but not my primary calendar.
Here is part of the code:
try
{
birthday = new Date(Data[i][BirthColumn]);
birthday.setFullYear(today.getFullYear());
birthday.setUTCHours(12);
birthlist += Data[i][NameColumn] + " --> " + birthday + "\n";
calendarevent = cal.createAllDayEventSeries("¡Cumpleaños " + Data[i][NameColumn] + "!", birthday, CalendarApp.newRecurrence().addYearlyRule().times(YearsInAdvance));
if (calendarevent == null)
success = false;
else
{
//This sentence fails every single time.
calendarevent.addEmailReminder(0);
calendarevent.addPopupReminder(0);
calendarevent.addSmsReminder(0);
}
}
catch (ee)
{
var row = i + 1;
success = false;
errlist += "Error on row " + row + ": check name and birth date. Exception Error: " + ee.message + "\n";
}
This is the portion of the code I finally change to make it work, as Serge insas suggest me before:
if (calendarevent == null)
success = false;
else
{
cal.getEventSeriesById(calendarevent.getId()).addEmailReminder(0);
cal.getEventSeriesById(calendarevent.getId()).addPopupReminder(0);
cal.getEventSeriesById(calendarevent.getId()).addSmsReminder(0);
}
This is a known issue
See comment nr 67 for a working workaround : the trick is to re-call the event for every item you want to add (reminder, popup...) using cal.getEventSeriesById(eventID) after you get the Id simply with .getId()
I use it in some scripts and it solved the issue for me.

splite string using mutilple characters

what I need is simple thing, I have string which cantains data - time retrived from mySQL in mySQL format HH:MM:SS YY-MM-DD what I need is to split this string in actionscript to array of numbers like this
HH
MM
SS
YY
MM
DD
so I can compare it with current time, any one know how to splite using multiple delimiters at first, then compare it with current time. this is my work until now
var param:Array = datetime.split(" :-");
var currentTime:Date = new Date();
var seconds:uint = currentTime.getSeconds();
var minutes:uint = currentTime.getMinutes();
var hours:uint = currentTime.getHours();
var days:uint = currentTime.getDay();
var monthes:uint = currentTime.getMonth();
var years:uint = currentTime.getFullYear();
if(int(param[3]) > years)
return years + " سنة ";
if(int(param[4]) > monthes)
return monthes + " شهر ";
if(int(param[5]) > days)
return days + " يوم ";
if(int(param[0]) > hours)
return hours + " ساعة ";
if(int(param[1]) > minutes)
return minutes + " دقيقة ";
if(int(param[2]) > seconds)
return seconds + " ثانية ";
return param[0] + " يوم ";
`
Split allows the delimiter to be a regexp, so you can say this or that. Something like this:
myStr.split(/:|-/)
Good luck!
You can use multiple characters, with separated by pipe |
myStr.split(/:|-|[|\(|\)]/)
make sure to use \ if you use ( ) and similar, so ( )
To solve your specific question, you might consider replacing the characters to be the same, and then split on that one. Use datetime.replace(/[ :-]/g, "|") and then split on "|". (I didn't check the correctness of the regexp). What Tyler says is more elegant: datetime.split(/[ -:]/). I stand for the rest though:
What MySQL outputs (via php?) is a standard date notation. You could try and use the Date.parse(dateString) to get a timestamp from it, and convert that into a date object by passing it as the sole constructor parameter:
recordedTime = new Date(Date.parse(datetime));
You could then compare the two date objects directly.
if (recordedTime.getFullYear() > currentTime.getFullYear()) { ... }
Hope it helps.