Issue with assigning Google Map Autocomplete results to variables - google-maps

I have issue with with this line:
var user-city = addressObj[j].long_name;
I see proper value in console log but can't assign it to the variable.
function onPlaceChanged() {
var places = autocomplete.getPlace();
//console.log(places);
// var place = places[0];
console.log(places);
console.log(places.address_components);
user_home_address = places.name;
for(var i = 0; i < places.address_components.length; i += 1) {
var addressObj = places.address_components[i];
for(var j = 0; j < addressObj.types.length; j += 1) {
if (addressObj.types[j] === 'locality') {
// console.log(addressObj.types[j]); // confirm that this is 'city'
var user-city = addressObj[j].long_name;
// console.log(addressObj.long_name); // confirm that this is the city name
}
}
for(var j = 0; j < addressObj.types.length; j += 1) {
if (addressObj.types[j] === 'administrative_area_level_1') {
// console.log(addressObj.types[j]); // confirm that this is 'province'
// console.log(addressObj.short_name); // confirm that this is the province name
}
}
}

Related

Retrieving google form response data

I have a google form, where I need to use item ID and get all the response for that Item.
I have the below script which will timeout if the form has more than 3000 responses, as its inefficient
How Do I optimize it to retrieve all the items in a short span of time
fO.items = ["ItemID1","ItemID2","ItemID3"...];
for (var i = 0; i < responses.length; i++) {
var response = responses[i];
var otherItems = '';
var flag = true;
for (var j = 0; j < fO.items.length; j++) {
var item = form.getItemById(parseInt(fO.items[j]));
if (response.getResponseForItem(item))
var otherItems = otherItems + "\t" + response.getResponseForItem(item).getResponse();
else
flag = false;
}
if (flag) {
columnData.push(otherItems);
responseIds.push(response.getId());
}
}
Currently, your code is getting the item object with the following line:
var item = form.getItemById(parseInt(fO.items[j]));
So, that line of code is reading the Form many times.
You could try getting the item objects once, putting them into a JSON object, and then retrieving them as needed.
I haven't tested this code, and I don't know if it will work, or if it will be faster if it does work. But thought I'd share the idea.
function getSomeAnswers() {
var form,flag,i,item,itemID,itemList,itemsObject,
k,L,L_items,otherItems,responses,response,thisAnswer;
itemList = ["ItemID1","ItemID2","ItemID3"];
form = FormApp.getActiveForm();
responses = FormApp.getActiveForm().getResponses();
itemsObject = {};
L_items = itemList.length;
for (i = 0; i < L; i++) {//Compile a list of item objects
itemID = parseInt(itemList[i]);
itemsObject[itemID] = form.getItemById(itemID);
}
L = responses.length;
for (i = 0; i < L; i++) {
response = responses[i];
otherItems = '';
flag = true;
for (k in itemsObject) {//Loop through every item to get
item = itemsObject[k];
thisAnswer = response.getResponseForItem(item);
Logger.log(thisAnswer)
if (thisAnswer)
otherItems = otherItems + "\t" + response.getResponseForItem(item).getResponse();
else
flag = false;
}
/*
if (flag) {
columnData.push(otherItems);
responseIds.push(response.getId());
}
*/
}
}

use .removeFromThreads in more than 100 threads inside a google app script

i have a script that removes every thread within a label and all sublabels.This was workng fine, but recently i got an error that says that the operation childrens[i].removeFromThreads(threads); can not be applied to more that 100 threads... How can i fix this?
function removingThreadsfromLabel() {
var parentlabelstring = 'THELabel';
var parentlabel = GmailApp.getUserLabelByName(parentlabelstring);
var childrens = children(parentlabel);
for (var i = 0; i < childrens.length; i++){
var threads = childrens[i].getThreads();
childrens[i].removeFromThreads(threads);
}
}
function children(parent) {
var name = parent.getName() + '/';
return GmailApp.getUserLabels().filter(function(label) {
return label.getName().slice(0, name.length) == name;
});
}
For now i have done the following, but it is not optimal...
function removingThreadsfromLabel() {
var parentlabelstring = 'THELabel';
var parentlabel = GmailApp.getUserLabelByName(parentlabelstring);
var childrens = children(parentlabel);
for (var i = 0; i < childrens.length; i++){
var threads = childrens[i].getThreads();
Logger.log(threads.length);
while (threads.length>100){
childrens[i].removeFromThread(threads[0]);
var threads = childrens[i].getThreads();
}
childrens[i].removeFromThreads(threads);
}
}
Regards,
Ok, i figure out how to do it in batch, so it is better that my first solution:
function removingThreadsfromLabel() {
var batchSize = 100;
var parentlabelstring = 'THELabel';
var parentlabel = GmailApp.getUserLabelByName(parentlabelstring);
var childrens = children(parentlabel);
for (var i = 0; i < childrens.length; i++){
var threads = childrens[i].getThreads();
Logger.log(threads.length);
for (var j = 0; j < threads.length; j+=batchSize) {
childrens[i].removeFromThreads(threads.slice(j, j+batchSize));
}
var threads = childrens[i].getThreads();
childrens[i].removeFromThreads(threads);
}

Checking for straight combination in poker

I want to check for a straight combination in a poker game.
So, I have this array: var tempArr:Array = new Array;
I have this for sorting the array:
for (i = 0; i < 7; i++)
{
tempArr[i] = pValue[i];
}
tempArr.sort( Array.NUMERIC );
pValue is the value of the cards, it's have range from 2 to 14.
So, if I have this Array: tempArray = [2,3,3,4,5,5,6];
How can I check if I have a straight combination in my hand?
Set a bucket array to save if you got a card in hand
var t:Array = [];
//t[2] = 1;mean you have 2
// t[3] = 0;mean you don't have 3
//first initialize t
for(var i:int = 0; i < 15; i++)
{
t[i] = 0;
}
//then set the values from tempArray
for (var j:int = 0; j < tempArray.length; j++)
{
t[tempArray[j]] = 1;
}
//if you have a straight combination in your hand
//you will get a k that t[k] & t[k-1]& t[k-2] & t[k-3] & t[k-4] == 1
var existed:boolean = false;//the flag save if you got a straight combination
for (var k:int = t.length - 1; k >= 4; k--)
{
if (t[k] == 0)
{
continue;
}
if ((t[k] & t[k-1] & t[k-2] & t[k-3] & t[k-4]) == 1)
{
existed = true;
break;
}
}

Accessing variable names dynamically

I have the following scenario:
if (event.status == AMFResultEvent.SUCCESS) {
var lev1:uint = 0;
var lev2:uint = 0;
var lev3:uint = 0;
var lev4:uint = 0;
var lev5:uint = 0;
var lev6:uint = 0;
for (var i:int = 0; i < event.result.length; i++) {
if (mainLevel == "1") {
lev1++;
}
if (mainLevel == "2") {
lev2++;
}
if (mainLevel == "3") {
lev3++;
}
if (mainLevel == "4") {
lev4++;
}
if (mainLevel == "5") {
lev5++;
}
if (mainLevel == "6") {
lev6++;
}
}
for (var j:int = 1; j < 7; j++) {
_row = new StatisticsRow(event.result[j], this);
_rowsPlace.addChild(_row);
_row.y = (_row.height +1) * j;
_row.codeLevel.htmlText = j; // works as it should
// need to access variables lev1 - lev6, called by something like "lev"+j here:
_row.amount.htmlText =
}
// traces correct amounts of mainLevels from the i loop:
trace ("level 1: " + lev1);
trace ("level 2: " + lev2);
trace ("level 3: " + lev3);
trace ("level 4: " + lev4);
trace ("level 5: " + lev5);
trace ("level 6: " + lev6);
}
I'm missing something obvious here, as the ["lev"]+j doen't work. How can I dynamically acces the lev1 - lev6 in the j-loop? As the code comment at the bottoms shows, this traces as expected.
Thanks in advance!
You can access them with brackets, string concatenation, and the this keyword. Here's an example of how you would use bracket notation in a loop:
for (var i:int = 0; i <= 6; i++) {
var currLev = this["lev"+i];
// do stuff to currLev
}
Thanks for answering guys!
I had a lousy approach to my problem anyway, and should have used an array right away:
var mainLevels:Array = new Array();
for (var n:int = 1; n < 7; n++) {
mainLevels[n] = 0;
}
if (event.status == AMFResultEvent.SUCCESS) {
for (var i:int = 0; i < event.result.length; i++) {
var data = event.result[i];
var correctCode:String = data["correct"];
var mainLevelFound:uint = uint(correctCode.substr(0, 1));
for (var k:int = 1; k < 7; k++) {
if (k == mainLevelFound) {
mainLevels[k]++;
}
}
}
for (var j:int = 1; j < 7; j++) {
_row = new StatisticsRow(event.result[j], this);
_rowsPlace.addChild(_row);
_row.y = (_row.height +1) * j;
_row.codeLevel.htmlText = j;
// Now this works as a reference to mainLevels[*] created above!
_row.amount.htmlText = mainLevels[j];
}
Thanks again for your effort :)

Getting 'TypeError' response for Gmail Meter Script.

I'm getting the following error:
"TypeError: Cannot read property "0.0" from null. (line227)"
I've been looking through the documentation here: https://developers.google.com/apps-script/articles/gmail-stats#section1
But haven't been able to troubleshoot.
Line227:
variables.dayOfEmailsReceived[day]++;
Sorry, new to stackoverflow but any help greatly appreciated.
Reference:
var BATCH_SIZE = 50;
var ss = SpreadsheetApp.getActiveSpreadsheet();
// If you are using several email addresses, list them in the following variable
// - eg 'romain.vialard#gmail.com,romain.vialard#example.com'
var aliases = 'romain.vialard#euromed-management.com';
function activityReport() {
var status = ScriptProperties.getProperty("status");
if (status == null) {
// If the script is triggered for the first time, init
init_();
}
else {
status = Utilities.jsonParse(status);
var previousMonth = new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1).getMonth();
if (status == null || (status.customReport == false && status.previousMonth != previousMonth)) {
init_();
fetchEmails_(status.customReport);
}
// If report not sent, continue to work on the report
else if (status.reportSent == "no") {
fetchEmails_(status.customReport);
}
}
}
function fetchEmails_(customReport) {
var variables = Utilities.jsonParse(ScriptProperties.getProperty("variables"));
if (!customReport) {
var query = "after:" + variables.year + "/" + (variables.previousMonth) + "/31";
query += " before:" + new Date().getYear() + "/" + (variables.previousMonth + 1) + "/31";
}
else {
var query = "after:" + Utilities.formatDate(new Date(variables.startDate), variables.userTimeZone, 'yyyy/MM/dd');
query += " before:" + Utilities.formatDate(new Date(variables.endDate), variables.userTimeZone, 'yyyy/MM/dd');
}
query += " in:anywhere -label:sms -label:call-log -label:chats -label:spam -filename:ics";
query += " -from:maestro.bounces.google.com -from:unified-notifications.bounces.google.com -from:docs.google.com";
query += " -from:group.calendar.google.com -from:apps-scripts-notifications#google.com";
query += " -from:sites.bounces.google.com -from:noreply -from:notify -from:notification";
var startDate = new Date(variables.startDate).getTime();
var endDate = new Date(variables.endDate).getTime();
var conversations = GmailApp.search(query, variables.range, BATCH_SIZE);
variables.nbrOfConversations += conversations.length;
var sheets = ss.getSheets();
var people = sheets[0].getDataRange().getValues();
var record = [];
for (var i = 0; i < conversations.length; i++) {
Utilities.sleep(1000);
var conversationId = conversations[i].getId();
var firstMessageSubject = conversations[i].getFirstMessageSubject();
var starred = false;
if (conversations[i].hasStarredMessages()) {
variables.nbrOfConversationsStarred++;
starred = true;
}
var important = false;
if (conversations[i].isImportant()) {
variables.nbrOfConversationsMarkedAsImportant++;
important = true;
}
var location = "";
var labels = conversations[i].getLabels();
var nbrOfLabels = labels.length;
if (nbrOfLabels == 0) {
if (conversations[i].isInInbox()) {
variables.nbrOfConversationsInInbox++;
location += "Inbox,";
}
else if (conversations[i].isInTrash()) {
variables.nbrOfConversationsInTrash++;
location += "Trashed,";
}
else {
variables.nbrOfConversationsArchived++;
location = "Archived";
}
}
else {
variables.nbrOfConversationsInLabels++;
for (var j = 0; j < nbrOfLabels; j++) {
location += labels[j].getName() + ",";
}
}
var youReplied = false;
var youStartedTheConversation = false;
var someoneAnswered = false;
var messages = conversations[i].getMessages();
var nbrOfMessages = messages.length;
variables.nbrOfEmailsPerConversation[nbrOfMessages]++;
for (var j = 0; j < 10; j++) {
if (variables.topThreads[j][1] < nbrOfMessages) {
variables.topThreads.splice(j, 0, [firstMessageSubject, nbrOfMessages]);
variables.topThreads.pop();
j = 10;
}
}
var timeOfFirstMessage = 0;
var waitingTime = 0;
for (var j = 0; j < nbrOfMessages; j++) {
var process = true;
var date = messages[j].getDate();
var month = date.getMonth();
if (customReport) {
if (date.getTime() < startDate || date.getTime() > endDate) {
process = false;
}
}
else {
if (month != variables.previousMonth) {
process = false;
}
}
if (process) {
//////////////////////////////////
// Fetch sender of each emails
//////////////////////////////////
var from = messages[j].getFrom().replace(/"[^"]*"/g,'');
if (from.match(/</) != null) {
from = from.match(/<([^>]*)/)[1];
}
var time = Utilities.formatDate(date, variables.userTimeZone, "H");
var day = Utilities.formatDate(date, variables.userTimeZone, "d") - 1;
// Use function from Utilities file
variables = countSendsPerDaysOfWeek_(variables, date, from);
var body = messages[j].getBody();
// Use function from Utilities file
var resultsFromCalcMessagesLength = calcMessagesLength_(variables, body, from);
variables = resultsFromCalcMessagesLength[0];
var messageLength = resultsFromCalcMessagesLength[1];
var cc = messages[j].getCc().replace(/"[^"]*"/g,'').split(/,/);
for (var k = 0; k < cc.length; k++) {
if (cc[k].match(/</) != null) {
cc[k] = cc[k].match(/<([^>]*)/)[1];
}
}
var reg = new RegExp(from, 'i');
if ((variables.user + aliases).search(reg) != -1) {
if (j == 0) {
youStartedTheConversation = true;
timeOfFirstMessage = date.getTime();
}
if (j > 0 && !youStartedTheConversation) {
if (!youReplied) {
youReplied = true;
// Use function from Utilities file
variables = calcWaitingTime_(variables, date, timeOfFirstMessage, youStartedTheConversation);
}
}
variables.nbrOfEmailsSent++;
variables.timeOfEmailsSent[time]++;
variables.dayOfEmailsSent[day]++;
if (customReport) {
variables.monthOfEmailsSent[month]++;
}
var sharedWithTheOutsideWorld = false;
var to = messages[j].getTo().replace(/"[^"]*"/g,'').split(/,/);
for (var k = 0; k < to.length; k++) {
if (to[k].match(/</) != null) {
to[k] = to[k].match(/<([^>]*)/)[1];
}
if (to[k].search(variables.companyname) == -1){
sharedWithTheOutsideWorld = true;
}
var found = false;
for (var l = 0; l < people.length; l++) {
if (to[k] == people[l][0]) {
people[l][2]++;
found = true;
}
}
if (!found) {
people.push([to[k], 0, 1]);
}
}
if(!sharedWithTheOutsideWorld){
variables.sharedInternally++;
}
}
else {
if (j == 0) {
timeOfFirstMessage = date.getTime();
}
else if (youStartedTheConversation && !someoneAnswered) {
someoneAnswered = true;
// Use function from Utilities file
variables = calcWaitingTime_(variables, date, timeOfFirstMessage, youStartedTheConversation);
}
var found = false;
for (var k = 0; k < people.length; k++) {
if (from == people[k][0]) {
people[k][1]++;
found = true;
}
}
if (!found) {
people.push([from, 1, 0]);
}
var to = messages[j].getTo().replace(/"[^"]*"/g,'');
var checkSendToYou = false;
var aliasesTemp = new Array(variables.user).concat(aliases.split(','));
for(var k = 0; k < aliasesTemp.length; k++){
if(aliasesTemp[k] != ''){
var reg = new RegExp(aliasesTemp[k], 'i');
if (to.search(reg) != -1) {
checkSendToYou = true;
}
}
}
if(checkSendToYou)variables.sentDirectlyToYou++;
var sharedWithTheOutsideWorld = false;
to = to.split(/,/);
for (var k = 0; k < to.length; k++) {
if (to[k].match(/</) != null) {
to[k] = to[k].match(/<([^>]*)/)[1];
}
if (to[k].search(variables.companyname) == -1){
sharedWithTheOutsideWorld = true;
}
}
if(sharedWithTheOutsideWorld == false && from.search(variables.companyname) != -1){
variables.sharedInternally++;
}
variables.nbrOfEmailsReceived++;
variables.timeOfEmailsReceived[time]++;
variables.dayOfEmailsReceived[day]++;
if (customReport) {
variables.monthOfEmailsReceived[month]++;
}
}
if (to != null) {
to = to.toString();
}
if (cc != null) {
cc = cc.toString();
}
var dayOfWeek = Utilities.formatDate(date, variables.userTimeZone, "EEEE");
record.push([date, dayOfWeek, firstMessageSubject, from, to, cc, messageLength, location]);
}
}
if (youStartedTheConversation) {
variables.nbrOfConversationsStartedByYou++;
}
if (youReplied) {
variables.nbrOfConversationsYouveRepliedTo++;
}
}
variables.range += BATCH_SIZE;
ScriptProperties.setProperty("variables", Utilities.jsonStringify(variables));
sheets[0].getRange(1, 1, people.length, 3).setValues(people);
if (record[0] != undefined && sheets[1].getMaxRows() < 38000) {
sheets[1].getRange(sheets[1].getLastRow() + 1, 1, record.length, record[0].length).setValues(record);
}
if (conversations.length < BATCH_SIZE) {
sendReport_(variables);
}
}
It's a timezone issue. Go to your Gmail Meter file on your Google Drive account and then:
File -> Spreadsheet settings...
Change the timezone to your current time zone. I assume your Gmail account changes timezones automatically, but not your spreadsheet.
The error indicates that and day is 0 variables.dayOfEmailsReceived is null. It's not possible to refer to an index of null. variables.dayOfEmailsReceived is created in the init_() function, so check that you have that function defined and are using it correctly.