GAS - Script execution time too long / Workaround? - google-apps-script

I have a script that takes more than 5 minutes to execute. So it will be aborted after 5 minutes with the information that the execution time is too long.
Now I am looking for a solution to handle this. In the following example I would like to interrupt when var = i has reached a value of 300 and then continue with i = 301. Is this an option for a workaround? If so, how has the code to be adapted?
var xy = 1100;
for (var = i; i<= xy; i++){
{
do_some_stuff();
}
}
In practice my code is the following....and the loop is starting with for(var i = 3; i <= lastrow +1; i++) lastrow has a value of 1500.
function Create_geodata()
{
var Geodata = getSheetById(1702838837);
var Geojson_Data = getSheetById(1515926044);
var Control_Panel = getSheetById(1102907697);
Geodata.getRange('I4').setValue('Yes');
var Hyperlink_Geodata = Control_Panel.getRange('O18').getValue();
var document_missing_ID = Control_Panel.getRange('O24').getValue();
var Umap_Hyperlink = Control_Panel.getRange('L20').getValue();
var umap_zoom = Control_Panel.getRange('N22').getValue();
var Own_ID_Sort_Setting = Control_Panel.getRange('O30').getValue();
var Own_ID_Sort = Control_Panel.getRange('M32').getValue();
var Threshold_Altitude = Control_Panel.getRange('N28').getValue();
var Automatic_Altitude_Removal = Control_Panel.getRange('O26').getValue();
var Cat_A = Control_Panel.getRange('C36').getValue();
var Cat_B = Control_Panel.getRange('C38').getValue();
var Cat_C = Control_Panel.getRange('C40').getValue();
RESET_Geodata(); //Clear data before proceed
if (Own_ID_Sort_Setting)
{standard_sort_column = Own_ID_Sort}
else
{standard_sort_column = "name"}
var data = Geojson_Data.getDataRange().getValues();
var col1 = data[0].indexOf(standard_sort_column) + 1;
var col2 = data[0].indexOf('coordinates') + 1;
var col3 = data[0].indexOf('name') + 1;
var col4 = data[0].indexOf('description') + 1;
var col1_Char = columnToLetter(col1); //last row of column where sort-criteria is located
var col2_Char = columnToLetter(col2);
var col3_Char = columnToLetter(col3);
var col4_Char = columnToLetter(col4);
var lastrow_col1 = Geojson_Data.getRange(col1_Char + ':' + col1_Char).getValues();
lastrow_col1 = lastrow_col1.filter(String).length;
var lastrow = Geojson_Data.getLastRow();//last row of complete sheet
var lc = Geojson_Data.getLastColumn(); //last column
var lc_Char = columnToLetter(lc);
var dc = 0;
Geojson_Data.getRange('N1').setValue(col1);
if (!document_missing_ID)
{
for(var t = 2; t <= lastrow; t++)
{
if (Geojson_Data.getRange(t,col1).getValue() == "")
{
Geojson_Data.deleteRow(t);
}
}
}
else
{
for(var t = 2; t <= lastrow; t++)
{
if (Geojson_Data.getRange(t,col1).getValue() == "")
{
dc++;
var formattedNumber = ("000" + dc).slice(-4);
Geojson_Data.getRange(t,col1).setValue('ZZ_' + formattedNumber);
}
}
}
Geojson_Data.getRange('A2:' + lc_Char + lastrow).sort(col1);
Geojson_Data.getRange(col1_Char + 2 + ':' + col1_Char + lastrow).copyTo(Geodata.getRange('A3:A' + lastrow),{contentsOnly: true});
Geojson_Data.getRange(col2_Char + 2 + ':' + col2_Char + lastrow).copyTo(Geodata.getRange('F3:F' + lastrow),{contentsOnly: true});
Geojson_Data.getRange(col3_Char + 2 + ':' + col3_Char + lastrow).copyTo(Geodata.getRange('B3:B' + lastrow),{contentsOnly: true});
Geojson_Data.getRange(col4_Char + 2 + ':' + col4_Char + lastrow).copyTo(Geodata.getRange('D3:D' + lastrow),{contentsOnly: true});
var geodata_sorted = '';
var route_length = 0;
for(var i = 3; i <= lastrow +1; i++)
{
var pr = 0;
var fl = false;
var distance_neighbour_points = 0;
var Ar = Geodata.getRange('F' + i).getValue();
Ar = Ar.split(',');
var Ar_Anz = Ar.length - 1;
for(var b = 0; b <= Ar_Anz; b=b+2)
{
if ((Ar_Anz - b) != 0)
{
var E_Lat = Ar[b];
var E_Lon = Ar[b + 1];
if (fl)
{
var A_Lat = Ar[b - 2];
var A_Lon = Ar[b - 1];
distance_neighbour_points = distVincenty(A_Lat, A_Lon, E_Lat, E_Lon);
if (Automatic_Altitude_Removal && (distance_neighbour_points > Threshold_Altitude))
{
b++;
E_Lat = Ar[b];
E_Lon = Ar[b + 1];
A_Lat = Ar[b - 3];
A_Lon = Ar[b - 2];
}
route_length = route_length + distVincenty(A_Lat, A_Lon, E_Lat, E_Lon);
}
pr++;
fl = true;
}
geodata_sorted = geodata_sorted + E_Lat + ',' + E_Lon;
if ((Ar_Anz - b) < 2)
{
}
else
{
geodata_sorted = geodata_sorted + ',';
}
if ((Ar_Anz - b) < 2)
{
pr = parseInt(pr / 2) * 2 + 1;
var Ay = geodata_sorted.split(',');
var Geo_Mitte_Lon = Ay[pr - 1];
var Geo_Mitte_Lat = Ay[pr];
var googlemaps = 'https://maps.google.com/?q=' + Geo_Mitte_Lat + ',' + Geo_Mitte_Lon;
var umap = 'https://umap.openstreetmap.fr/de' + '/map/' + Umap_Hyperlink + '#' + umap_zoom + '/' + Geo_Mitte_Lat + '/' + Geo_Mitte_Lon;
Geodata.getRange(i, 3).setValue(route_length / 1000);
Geodata.getRange(i, 6).setValue(geodata_sorted);
Geodata.getRange(i, 7).setValue(googlemaps);
Geodata.getRange(i, 8).setValue(umap);
//Verlinkung
if (Hyperlink_Geodata)
{
var displayName1 = Geodata.getRange(i,1).getValue();
var displayName2 = Geodata.getRange(i,2).getValue();
Geodata.getRange(i,1).setFormula('=HYPERLINK(\"' + googlemaps + '\";\"' + displayName1 + '\")');
Geodata.getRange(i,2).setFormula('=HYPERLINK(\"' + umap + '\";\"' + displayName2 + '\")');
}
geodata_sorted = '';
route_length = 0;
}
}
//Set categories Cat_A,B,C...
var description_content = Geodata.getRange(i,4).getValue();
var regExpA = new RegExp('/*' + Cat_A, 'gi');
var regExpB = new RegExp('/*' + Cat_B, 'gi');
var regExpC = new RegExp('/*' + Cat_C, 'gi');
var compareA = regExpA(description_content);
var compareB = regExpB(description_content);
var compareC = regExpC(description_content);
if (compareC == Cat_C) Geodata.getRange(i,5).setValue(Cat_C);
if (compareB == Cat_B) Geodata.getRange(i,5).setValue(Cat_B);
if (compareA == Cat_A) Geodata.getRange(i,5).setValue(Cat_A);
}
SpreadsheetApp.getActiveSpreadsheet().setActiveSheet(Geodata);
Geodata.getRange('I4').setValue('No');
}

Related

Array Length To Limit Number of Columns

I'm attempting to limit the number of columns pulled from a data source. The source has 10 columns, I only need the first 4 columns. Seems I am confusing myself on userData and var j plus var k and var l when attempting to create an HTML table of the output.
When I use var i = 0; i < values.length; i++ and var j = 0; j < header.length; j++ with var k = 0; k < userData.length; k++ and var l = 0; l < userData[0].length; l++ the HTML output returns all the columns.
How can I limit the output to just the first 4 columns?
var sheetID = 'example';
var dataSheet = 'SOP Update ACK';
var emailHeader = 'Email Address';
var activeUser = Session.getActiveUser();
var ss = SpreadsheetApp.openById(sheetID);
function doGet(e) {
return HtmlService.createHtmlOutputFromFile('Index').setTitle('My SOP Updates');
}
function currentUser() {
if (activeUser !== '') {
return activeUser.getEmail();
} else {
return "Couldn't detect user!!!";
}
}
function getData() {
var sheetName = dataSheet;
var activeSheet = ss.getSheetByName(sheetName);
var values = activeSheet.getDataRange().getDisplayValues();
var header = values[0];
var emailIndex = header.indexOf(emailHeader);
var userData = [];
for (var i = 0; i < values.length; i++) {
if (values[i][emailIndex] == activeUser) {
userData.push(values[i]);
}
}
if (userData.length > 0) {
var tableStart = '\n<table class="table table-hover table-sm">';
var tableHead = '\n<thead>\n<tr>';
for (var j = 0; j < header.length; j++) {
tableHead = tableHead + '\n<th>' + header[j] + '</th>';
}
tableHead = tableHead + '\n</tr>\n</thead>';
var tableBody = '\n<tbody>';
for (var k = 0; k < userData.length; k++) {
tableBody = tableBody + '\n<tr>';
for (var l = 0; l < userData[0].length; l++) {
tableBody = tableBody + '\n<td>' + userData[k][l] + '</td>';
}
tableBody = tableBody + '\n</tr>\n';
}
var tableEnd = '</tbody>\n</table>';
var tableHtml = tableStart + tableHead + tableBody + tableEnd;
return tableHtml;
} else {
return '<table class="table"><tbody><tr><td>No data found.</td></tr></tbody></table>';
}
}
I got this to work:
You will have to make some minor modification to get it to work for you because I tested it on my temp data since you did not provide any
function getData() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Sheet0");
const [header, ...values] = sh.getDataRange().getDisplayValues();
const emailIndex = header.indexOf('Email Address');
const userData = [];
const activeUser = Session.getActiveUser();
for (let i = 0; i < values.length; i++) {
if (values[i][emailIndex] == activeUser) {
userData.push(values[i].slice(0,4));
}
}
if (userData.length > 0) {
let tableStart = '\n<table class="table table-hover table-sm">';
let tableHead = '\n<thead>\n<tr>';
for (let j = 0; j < header.length; j++) {
tableHead = tableHead + '\n<th>' + header[j] + '</th>';
}
tableHead += '\n</tr>\n</thead>';
let tableBody = '\n<tbody>';
for (let k = 0; k < userData.length; k++) {
tableBody = tableBody + '\n<tr>';
for (let l = 0; l < userData[0].length; l++) {
tableBody = tableBody + '\n<td>' + userData[k][l] + '</td>';
}
tableBody = tableBody + '\n</tr>\n';
}
let tableEnd = '</tbody>\n</table>';
let tableHtml = tableStart + tableHead + tableBody + tableEnd;
return tableHtml;
} else {
return '<table class="table"><tbody><tr><td>No data found.</td></tr></tbody></table>';
}
}

"Lock wait timeout exceeded" when sending data from Google Sheets to MySQL

I wrote an Apps Script macro to send data from a Google spreadsheet to a MySQL table. In a first time, in delete some rows in the table and then I add rows in this table. I sometimes get a "Lock wait timeout exceeded; try restarting transaction" error. Sometimes it runs after 100 seconds, sometimes 4 minutes.
I don't understand what is wrong with this code.
//classeur.insertSheet("feuillebis")
//feuillebis=classeur.getSheets()[1]
//var feuillebis=classeur.getSheetByName('feuillebis')
var classeur = SpreadsheetApp.getActiveSpreadsheet() ;
var feuille = classeur.getActiveSheet();
var host = "107.167.186.180";
var databaseName = "eatology";
var userName = "root";
var password = "eatology";
var port = 3306;
var tableName = "weekly_order";
var url = 'jdbc:mysql://' + host + ':' + port + '/' + databaseName;
var nbrow = feuille.getMaxRows()
function Send_Weekly_Order_To_Data_Base() {
///here are all the connection parameters
var classeur = SpreadsheetApp.getActiveSpreadsheet();
var feuille = classeur.getActiveSheet();
var nbrow = feuille.getMaxRows();
var host = "107.167.186.180";
var databaseName = "eatology";
var userName = "root";
var password = "eatology";
var port = 3306;
var tableName = "weekly_order";
var url = 'jdbc:mysql://' + host + ':' + port + '/' + databaseName;
var conn = Jdbc.getConnection(url, userName, password);
conn.setAutoCommit(false);
///get the weekly_order as an array from the sql
var rowcount = 0;
var stmt2 = conn.createStatement();
var results = stmt2.executeQuery("SELECT * FROM eatology.weekly_order");
while (results.next()) {
if (results.getInt(1) > rowcount){
rowcount = results.getInt(1)
}
}
conn.commit();
results.close();
stmt2.close();
///delete the rows from the current week where we are running the macro
var timezone1 = classeur.getSpreadsheetTimeZone();
var date1 = Utilities.formatDate(feuille.getRange(2, 2).getValue(), timezone1, "yyyy-MM-dd");
var date2 = Utilities.formatDate(feuille.getRange(2, 3).getValue(), timezone1, "yyyy-MM-dd");
var date3 = Utilities.formatDate(feuille.getRange(2, 4).getValue(), timezone1, "yyyy-MM-dd");
var date4 = Utilities.formatDate(feuille.getRange(2, 5).getValue(), timezone1, "yyyy-MM-dd");
var date5 = Utilities.formatDate(feuille.getRange(2, 6).getValue(), timezone1, "yyyy-MM-dd");
var date6 = Utilities.formatDate(feuille.getRange(2, 7).getValue(), timezone1, "yyyy-MM-dd");
///clear the table weekly-order in the database
var stmt1 = conn.createStatement();
var result = stmt1.executeUpdate("DELETE FROM eatology.weekly_order where `Date` = " + "'" + date1 + "'" +" or `Date` = " + "'" + date2 + "'" +" or `Date` = " + "'" + date3 + "'" +" or `Date` = "+ "'" + date4 + "'" +" or `Date` = " + "'" + date5 + "'" +" or `Date` = "+ "'" + date6 + "'" );
//var result = stmt1.executeUpdate("DELETE FROM eatology.weekly_order where `Date` = " + "'" + date1 +"'");
conn.commit();
stmt1.close();
conn.close();
rowcount = rowcount + 1;
var conn = Jdbc.getConnection(url, userName, password);
conn.setAutoCommit(false);
var stmt = conn.prepareStatement('INSERT INTO eatology.weekly_order '
+ '(`Uid`, `Date`, `MP`, `Cname`, `Pname`, `Breakfast`, `Snack1`, `Lunch`, `Snack2`, `Dinner`) values (?,?,?,?,?,?,?,?,?,?)');
var program_name_line = 0;
var array = feuille.getRange(1, 1, nbrow, 7).getValues();
for (var j = 1; j < 7; j = j + 1) {
var inside = 0;
var i = 1;
while (array[i][0] != "Total" && i < 1000) {
i = i + 1
var color = feuille.getRange(i + 1, j + 1).getBackgrounds()
var fi1 = array[i][0].toString();
var fij = array[i][j].toString();
var empty = (fij == "");
var already = 0;
var test11111 = (color != "#5d31ce");
var cas1 = ((empty == false) && (fi1 != "Total") && (inside == 0));
var cas2 = (color == "#5d31ce" && inside == 1);
var cas3 = (empty == false);
if ((fi1 != "Total") && (inside == 0) && color != "#5d31ce") {
program_name_line = i;
inside = 1;
if (empty == false) {
var Uid = rowcount;
var Date1 = (Utilities.formatDate(array[1][j], timezone1, "yyyy-MM-dd"));
var MP = (array[program_name_line][0]);
var place = ((fij).indexOf("-"));
var length = (fij.length);
var Pname = ((fij).substring(place + 1, length));
var Cname = ((fij).substring(0, place));
var list = (meal(MP, Pname));
var Breakfast = list[0];
var Snack1 = list[1];
var Lunch = list[2];
var Snack2 = list[3];
var Dinner = list[4];
if (MP == "TM") {
var Breakfast = 1;
var Snack1 = 1;
var Lunch = 1;
var Snack2 = 1;
var Dinner = 1;
}
rowcount = rowcount + 1;
stmt.setInt(1, Uid);
stmt.setString(2, Date1);
stmt.setString(3, MP);
stmt.setString(4, Cname);
stmt.setString(5, Pname);
stmt.setInt(6, Breakfast);
stmt.setInt(7, Snack1);
stmt.setInt(8, Lunch);
stmt.setInt(9, Snack2);
stmt.setInt(10, Dinner);
stmt.addBatch();
}
}
else if (color == "#5d31ce" && inside == 1) {
inside = 0;
}
else if (empty == false && color != "#5d31ce") {
var Uid = rowcount ;
var Date1 = (Utilities.formatDate(array[1][j], timezone1, "yyyy-MM-dd"));
var MP = (array[program_name_line][0].toString());
var place = ((fij).indexOf("-"));
var length = (fij.length);
var Pname = ((fij).substring(place + 1, length));
var Cname = ((fij).substring(0, place));
var list = (meal(MP, Pname));
var Breakfast = (list[0]);
var Snack1 = (list[1]);
var Lunch = (list[2]);
var Snack2 = (list[3]);
var Dinner = (list[4]);
if (MP == "TM") {
var Breakfast = 1;
var Snack1 = 1;
var Lunch = 1;
var Snack2 = 1;
var Dinner = 1;
}
rowcount = rowcount+1;
stmt.setInt(1, Uid);
stmt.setString(2, Date1);
stmt.setString(3, MP);
stmt.setString(4, Cname);
stmt.setString(5, Pname);
stmt.setInt(6, Breakfast);
stmt.setInt(7, Snack1);
stmt.setInt(8, Lunch);
stmt.setInt(9, Snack2);
stmt.setInt(10, Dinner);
stmt.addBatch();
}
}
}
stmt.executeBatch();
conn.commit();
stmt.close();
conn.close();
}
function meal(MP, Pname){
var result= [0, 0, 0, 0, 0]
//in order to know if we have two snacks or only one because if the programm has more than 1200 cal, there are two snacks, otherwise, only one snack
var two_snacks = 1
if (MP.indexOf("1200") > -1) {
two_snacks = 0
}
//if the program type is '3'
if (Pname.indexOf("3") > -1) {
result[0] = 1;
result[1] = 1;
result[2] = 1;
result[4] = 1;
if (two_snacks == 1) {
result[3] = 1;
}
}
//if the program type is '2'
if (Pname.indexOf("2") > -1 && Pname.indexOf("S") == -1) {
result[0] = 1;
result[1] = 1;
result[2] = 1;
if (two_snacks == 1) {
result[3] = 1;
}
}
//if there is the B letter
if (Pname.indexOf("B") > -1) {
result[0] = 1;
}
//if there is the L letter
if (Pname.indexOf("L") > -1) {
result[2] = 1;
}
//if there is the D letter
if (Pname.indexOf("D") > -1) {
result[4] = 1;
}
//if there is the 2S letter
if (Pname.indexOf("2S") > -1) {
result[1] = 1;
result[3] = 1;
}
//if there is the 1S letter
if (Pname.indexOf("1S") > -1) {
result[1] = 1;
result[1] = 1;
}
return result
}

How to Get (& Set) cell values from one sheet to another in Google Sheets?

Looking to get values from several cells in the first sheet (POTemplate) of my Google Sheet file that serves as an order entry form. Line 22 is the first line in the form that collects data from our user regarding items requested for order.
The tab to which I'd like to set these values (POHistory) will serve as a running log of all order details keyed into the POTemplate tab with each order. Each entry recorded in the PO template log should include each orders' unique PO No. (found in cell N3 of the POTemplate tab) & PO Date (cell N4 of the POTemplate tab). I sincerely appreciate the help.
function submit() {
var app = SpreadsheetApp;
var tplSheet = app.getActiveSpreadsheet().getSheetByName("POTemplate");
var tplFRow = 22, tplLRow = tplSheet.getLastRow();
var tplRowsNum = tplLRow - tplFRow + 1;
var tplFCol = 1, tplLCol = 16;
var tplColsNum = tplLCol - tplFCol + 1;
var rangeData = tplSheet.getRange(22, 1, tplRowsNum, tplColsNum).getValues();
var colIndexes = [0, 3, 10, 12, 15];
var fData = filterByIndexes(rangeData, colIndexes);
var target = "POHistory";
var targetSheet = app.getActiveSpreadsheet().getSheetByName(target);
var tgtRow = targetSheet.getLastRow() + 1;
var tgtRowsNum = fData.length - tgtRow + 1;
var tgtCol = 1;
var tgtColsNum = fData[0].length - 1 + 1;
targetSheet.getRange(tgtRow, tgtCol, tgtRowsNum,
tgtColsNum).setValues(fData);
}
function filterByIndexes(twoDArr, indexArr) {
var fData = [];
twoDArr = twoDArr.transpose();
for(var i=0; i<indexArr.length; i++) {
fData.push(twoDArr[indexArr[i]]);
}
return fData.transpose();
}
Array.prototype.transpose = function() {
var a = this,
w = a.length ? a.length : 0,
h = a[0] instanceof Array ? a[0].length : 0;
if (h === 0 || w === 0) {return [];}
var i, j, t = [];
for (i = 0; i < h; i++) {
t[i] = [];
for (j = 0; j < w; j++) {
t[i][j] = a[j][i];
}
}
return t;
}
I can offer you a modification of the submit() function you have given.
function process(){
submit();
submitDate();
}
function submitDate() {
var app = SpreadsheetApp;
var tplSheet = app.getActiveSpreadsheet().getSheetByName("POTemplate");
var tplFRow = 1, tplLRow = 21;
var tplRowsNum = tplLRow - tplFRow + 1;
var tplFCol = 1, tplLCol = 16;
var tplColsNum = tplLCol - tplFCol + 1;
var rangeData = tplSheet.getRange(tplFRow, tplFCol, tplLRow, tplColsNum).getValues();
var colIndexes = [13];
var fData = filterByIndexes(rangeData, colIndexes);
var target = "POHistory";
var targetSheet = app.getActiveSpreadsheet().getSheetByName(target);
var tgtRow = targetSheet.getLastRow() + 1;
var tgtRowsNum = fData.length - tgtRow + 1;
var tgtCol = 1;
var tgtColsNum = fData[0].length - 1 + 1;
Logger.log(fData)
fData=fData.transpose();
Logger.log(fData)
targetSheet.getRange(tgtRow-1, 5, fData.length,
fData[0].length).setValues(fData);
}
function submit() {
var app = SpreadsheetApp;
var tplSheet = app.getActiveSpreadsheet().getSheetByName("POTemplate");
var tplFRow = 22, tplLRow = tplSheet.getLastRow();
var tplRowsNum = tplLRow - tplFRow + 1;
var tplFCol = 1, tplLCol = 16;
var tplColsNum = tplLCol - tplFCol + 1;
var rangeData = tplSheet.getRange(22, 1, tplRowsNum, tplColsNum).getValues();
var colIndexes = [0, 3, 10, 12, 15];
var fData = filterByIndexes(rangeData, colIndexes);
var target = "POHistory";
var targetSheet = app.getActiveSpreadsheet().getSheetByName(target);
var tgtRow = targetSheet.getLastRow() + 1;
var tgtRowsNum = fData.length - tgtRow + 1;
var tgtCol = 1;
var tgtColsNum = fData[0].length - 1 + 1;
targetSheet.getRange(tgtRow, tgtCol, tgtRowsNum,
tgtColsNum).setValues(fData);
}
function filterByIndexes(twoDArr, indexArr) {
var fData = [];
twoDArr = twoDArr.transpose();
for(var i=0; i<indexArr.length; i++) {
fData.push(twoDArr[indexArr[i]]);
}
return fData.transpose();
}
Array.prototype.transpose = function() {
var a = this,
w = a.length ? a.length : 0,
h = a[0] instanceof Array ? a[0].length : 0;
if (h === 0 || w === 0) {return [];}
var i, j, t = [];
for (i = 0; i < h; i++) {
t[i] = [];
for (j = 0; j < w; j++) {
t[i][j] = a[j][i];
}
}
return t;
}
Basically, similar code runs twice. I could be criticized for doing this, but perhaps it is convenient for you this way.

Google Apps Script to remove hangouts links from calendar events

I have successfully accessed a Google calendar event and can change the color, but I'm stuck when it comes to removing the hangouts link.
I'm attempting to use code to automatically remove the hangouts links when I am the meeting originator and have not changed the hangout name, but I'm not having any success in actually changing the link.
Any help greatly appreciated.
function removehangout() {
var calendarId = 'primary';
//var calendars = CalendarApp.getOwnedCalendarsByName('Mirage ELDRIDGE');
var now = new Date();
// Determines how many events are happening in the next 24 hours x 1 days.
var now = new Date();
var endr = new Date(now.getTime() + (1 * 24 * 60 * 60 * 1000));
var events2 = CalendarApp.getDefaultCalendar().getEvents(now, endr);
Logger.log('Number of events: ' + events2.length);
var events = Calendar.Events.list(calendarId, {
timeMin: now.toISOString(),
singleEvents: true,
orderBy: 'startTime',
maxResults: 5
});
if (events.items && events.items.length > 0) {
for (var i = 0; i < events.items.length; i++) {
var event1 = events.items[i];
var d = event1.description;
var ttitle = event1.summary;
var whoby = event1.creator.email;
Logger.log(ttitle + ' by: ' + whoby);
if(whoby.indexOf('mirage.eldridge') != -1){
Logger.log(ttitle + '--> was by mirage');
var hangoutname = event1.hangoutLink;
Logger.log(ttitle + '--> hangout link name --> ' + hangoutname);
if (hangoutname != null) {
if (hangoutname.indexOf('mirage-eldridge') != -1){
//delete this link here
Logger.log(ttitle + '--> remove hangout');
//event.setHangoutLink(null);
//var idno = event.iCalUID
//CalendarApp.getEventSeriesById(idno)
event1.HangoutLink = null;
Logger.log(ttitle + '... ' + event1.hangoutLink);
Logger.log(event1.iCalUID);
//event.setcolorId('11');
var event2 = Calendar.Events.get(calendarId, event1.id)
event2.colorId = 9;
event2.hangoutLink = 'fred';
//Calendar.Events.patch(event2,calendarId,event1.id);
Calendar.Events.update(event2,calendarId,event1.id);
}
} else {
Logger.log(ttitle + ' -- do not remove ' + hangoutname);
}
}
if (!d)
d = '';
//var foundlinkyes = d.indexOf('HangoutLink');
//var actuallink = event.hangoutLink;
//var hasrlink = 'True';
//if (!actuallink) {
//Logger.log(ttitle + ' no link found');
//hasrlink = "False";
//}
//Logger.log('desc: ' + ttitle + '-- foundyes: ' + foundlinkyes);
//if (foundlinkyes == -1 && hasrlink == 'True'){
//if (event.hangoutLink && (d.indexOf('Hangout: ')== -1)){
//Logger.log (event.summary + ' - ' + event.hangoutLink + ' - ' + event.description);
//Logger.log(ttitle + ' added this ' + event.hangoutLink);
//event.description = 'HangoutLink: ' + event.hangoutLink + '\n\n' + d;
//Calendar.Events.update(event, calendarId, event.id);
//foundlinkyes = 0;
//hasrlink = 'True';
//}
//}
}
} else {
Logger.log('No events found.');
}
}

how to convert seconds to minutes:seconds in as3

hi to all i am new in action script 3 in flash cs6 im creating a game with a timer
i want to make the seconds to minutes:seconds format
example:
120 seconds to 2:00
this is my code:
var countDownDec:Number = 1;
var totalSecs = 120;
var countDownSecs = totalSecs;
counter.text = countDownSecs;
var time:Timer = new Timer(countDownDec*1000);
time.addEventListener(TimerEvent.TIMER, tick);
time.reset();
countDownSecs = totalSecs;
counter.text = countDownSecs;
time.start();
var frameLbl:FrameLabel;
function tick(e:TimerEvent):void {
time.start();
if(countDownSecs == 0){
time.stop();
countDownSecs = totalSecs;
gotoAndPlay('timesUp');
TimesUp.play();
}
else{
countDownSecs = countDownSecs - countDownDec;
counter.text = countDownSecs;
}
}
please help me to my problem
Code 100% working :
var count_down_interval:Number = 1
var total_seconds:Number = 120
var count_down_seconds:Number = total_seconds
var timer:Timer = new Timer(count_down_interval * 1000)
timer.addEventListener(TimerEvent.TIMER, timer_on_Tick)
function timer_on_Tick(e:TimerEvent):void {
if(count_down_seconds == 0){
timer.stop()
count_down_seconds = total_seconds
trace('game over')
} else{
count_down_seconds -= count_down_interval
counter.text = convert_time(count_down_seconds)
}
}
timer.start();
counter.text = convert_time(count_down_seconds)
function convert_time(time) {
var h, m, s:Number, t:String, a:Array
if(isNaN(time)){ // 05:37 -> 337 seconds
t = time
a = t.split(':')
if(a.length > 2){
h = int(a[0]), m = int(a[1]), s = int(a[2])
} else {
h = 0, m = int(a[0]), s = int(a[1])
}
return h*3600 + m*60 + s
} else { // 337 -> 05:37
t = ''
h = int(time/3600)
m = int((time-(h*3600))/60)
if(time >= 3600) t += (h<10 ? '0' : '') + h + ':'
t += (m<10 ? '0' : '') + m + ':'
t += (time % 60<10 ? '0' : '') + int(time % 60)
return t
}
}
Divide by 60 and round down for minutes, modulo (%) 60 for seconds
var totalSecs = 120;
var minutes = Math.floor(totalSecs / 60);
var seconds = totalSecs % 60;
var timeInMinutesSeconds = minutes + ":" + seconds;
EDIT:
Try this:
var countDownDec:Number = 1;
var totalSecs:int = 120;
var countDownSecs:int = totalSecs;
counter.text = getCountDownSecsText(countDownSecs);
var time:Timer = new Timer(countDownDec*1000);
time.addEventListener(TimerEvent.TIMER, tick);
var frameLbl:FrameLabel;
function tick(e:TimerEvent):void {
if(countDownSecs == 0) {
time.stop();
countDownSecs = totalSecs;
gotoAndPlay('timesUp');
TimesUp.play();
} else {
countDownSecs = countDownSecs - countDownDec;
counter.text = getCountDownSecsText(countDownSecs);
}
}
private function getCountDownSecsText(currentAmountSecs:int):String{
var minutes:int = Math.floor(currentAmountSecs / 60);
var seconds:int = currentAmountSecs % 60;
var prependString:String = "";
if( minutes > 9 ) {
prependString = "0";
}
return prependString + minutes + ":" + seconds;
}