Google Places Photos .GetUrl is adding width and height to url - google-places-api

I'm trying to get images from google places. All is working for details: reviews, address... but when I try to get photos, I get a 404.
if(place.photos != null){
for(var i = 0; i < place.photos.length; i++){
var str = place.photos[i].getUrl({"maxWidth": 100, "maxHeight": 100});
var res = str.replace("w100-h100-p", "p");
self.pacPhotos.push({
id : res
});
}
}else {
console.log("no photo");
}
}
This will return the list ok but the URL is formatted wrong. it comes out like this.
" https://lh3.googleusercontent.com/w100-h100-p/AF1QipN3xzffYDPCyEIWnvAQGd3RwNs2C14sVlSqrrAh=k "
What I gather it wants is this.
" https://lh3.googleusercontent.com/p/AF1QipN3xzffYDPCyEIWnvAQGd3RwNs2C14sVlSqrrAh=k "
The only difference is the "w100-h100-"
*** There is a great work-around here from "Sulyman". I know it's not a long term solution as I'm sure google will fix their results (as discussed here Place API - getting place photo as marker icon )
For now I've adjusted the code above to reflect Sulymans suggestion. ***

it seems like every API Key generates different path
for example you got w100-h100-p and i got w200-p
and the good news that this section whatever it is...is fixed so you can replace it with another string which is p
var str = place.photos[0].getUrl();
var res = str.replace(""w100-h100-p", "p");
or you can delete the w100-h100-

Related

How to reduce time of script execution with FormApp...getResponses()?

The Email collection function built into the form is in the Text format. We have a lot of employees filling out this form, so it would be more convenient to choose from a drop-down list than to manually enter an email for each employee. The built-in function of collecting emails does not allow using the Dropdown list question type, so I had to disable it and send the response to the email using a script.
In addition, when you select one of the options (Transfer) in the form, you need to insert an additional correction row with data. This is also done by the script.
The script works fine, but unfortunately, its execution time reaches 45 seconds. I think this is abnormally large.
Updated code:
var FORM_ID = '#####';
var SHEET_NAME = 'Operations';
function sendFormToEmail() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
console.time('section10'); // 25579ms
var sheet = ss.getSheetByName(SHEET_NAME);
console.timeEnd('section10');
// Open a form by ID and log the responses to each question.
var form = FormApp.openById(FORM_ID);
var formResponses = form.getResponses();
var i = formResponses.length - 1;
var formResponse = formResponses[i]; // Last item
var itemResponses = formResponse.getItemResponses();
var length = itemResponses.length;
Logger.log("length = " + length);
var emailTo = itemResponses[0].getResponse(); // Returns the email if given
var cp = itemResponses[1].getResponse(); // Counterparty
var subject = "Input form: "+ cp;
var datePay = itemResponses[2].getResponse(); // Date of the operation
var dateAccept = itemResponses[3].getResponse(); // Date of acceptance
var sum = itemResponses[4].getResponse() ; // Amount
var what = itemResponses[5].getResponse(); // Operation type
var comm = "Correction " + itemResponses[length - 1].getResponse(); // Last response
var sum_1 = parseFloat(sum.replace(/,/, '.')) * (-1); // Amount * (-1)
var timestamp = new Date();
var textBody = "Operation: " + timestamp + ";\n";
for (var j = 0; j < itemResponses.length; j++) {
var itemResponse = itemResponses[j];
var resp = itemResponse.getResponse();
textBody += itemResponse.getItem().getTitle() + "=" + resp + ";\n";
}
if (what == 'Transfer') { // If the transfer between your accounts
var lr = sheet.getLastRow();
sheet.insertRowBefore(lr);
var values = [datePay, dateAccept, "", sum_1, "", "", "", "", comm, "", "", "", what, timestamp, "", "", ""];
Logger.log(values);
console.time('section12'); // 19449ms
sheet.getRange(lr, 2, 1, 17).setValues([values]);
console.timeEnd('section12')
}
if(emailTo !== undefined){
GmailApp.sendEmail(emailTo, subject, textBody);
}
}
At first I thought it was the large size of the acceptance sheet (about 13 thousand rows). I created a copy of the table, reduced it to several dozen rows, but the speed did not increase much.
Then I deleted the answers from the form (there were just under 9000 of them) - the same thing, I didn't get much performance gain.
Anyone have any ideas how to change the script algorithm to improve its performance?
===
Conclusions
Thanks to #TheMaster for the help with console.time(). Thanks to this tool I found bottlenecks in the code. More precisely, the code works well, but it's about the structure of the spreadsheets system with which the code interacts. The structure needs to be optimized.
There was also an idea addressed, probably, to Google developers. It would be great if there was a tool that visually (graphically) displays the relationships between spreadsheets and sheets that make up a single system. Perhaps with some kind of numerical characteristics that reflect, for example, the interaction time between its blocks. This would make it possible to quickly eliminate such bottlenecks in the system and improve it.
Investigation:
Pinpointing the issue is done using console.time() and console.timeEnd() of each section of code and calculating the time taken by reachl each section of code.
Issue:
As discussed in the question comment chain, This is due to a bloated spreadsheet with many sheets and import formulas. This caused more time to get the exact sheet and to use setValues:
console.time('section10'); // 25579ms
var sheet = ss.getSheetByName(SHEET_NAME);
console.timeEnd('section10');
//....
console.time('section12'); // 19449ms
sheet.getRange(lr, 2, 1, 17).setValues([values]);
console.timeEnd('section12')
Possible solutions:
Reduce number of sheets
Reduce interconnected spreadsheets (=import* formulas)
Delete empty rows on the bottom and empty columns on the right of each sheet.

Optimizely Sticky Session

I have just tried Optimizely. The problem is it will show different variations to a user. Sometimes we don't expect this behaviour. For example if I change color to red from blue, Optimizely will randomly select between the orginal (blue) and the variation (red) for the same user which is inconsistent. How can I make Optimizely to always show the same variation to a user?
Place the following code in your Experiment JavaScript:
setCookie = function (c_name,value,exdays) {
var exdate=new Date();
exdate.setDate(exdate.getDate() + exdays);
var expires = exdate.toUTCString();
var isIE8 = (document.documentMode !== undefined);
if (exdays == 0) {
expires = (isIE8 == true) ? "" : "0";
}
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+expires);
document.cookie=c_name + "=" + c_value;
}
Within each variant (e.g. Blue Variant, Red Variant, etc.), call setCookie and check whether the cookie exists for a user in that particular variant. If the cookie does exist, then run whatever code you want that particular variant to run. Below is an example of setting a cookie called tester that will expire after 30 days.
setCookie('tester',true,30);
if(document.cookie.indexOf('tester')>-1){
//RUN YOUR CODE HERE IF THIS VISITOR HAS THIS COOKIE
}
Hi there I am an engineer at Optimizely,
You could alternatively try the Fullstack product, which is more developer-oriented. With this you get an SDK that you install with your bundle and you implement your testing logic using code.
Example:
npm install optimizely-client-sdk
const optimizely = require('optimizely-client-sdk');
const optimizelyClient = optimizely.createInstance({
datafile: {} // this is your experiment config which you get from the Optimizely UI
});
const variation = optimizelyClient.activate('color_experiment', 'user_1');
if (variation === 'blue') {
// do something for blue
} else if (variation === 'red') {
// do something for red
} else {
// default case
}
And as long as you pass in the exact same user_id as the second argument to activate, you are guaranteed to always get the same variation for that user.
For more information or details on getting started please take a look at: https://developers.optimizely.com/x/solutions/sdks/getting-started/index.html?language=javascript
Also keep in mind that Optimizely gets blocked by adblockers, it can happen if a user turns their adblocker on after they've been on the page and served up an experiment to see - they would get the original version.

C# random imgur generator to use with Skypetool

I'm trying to create skype tool and I'm trying to make a command for it what would give the user a random imgur link, I tried first to just random generate string like so:
var chars ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[8];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
var finalString = new String(stringChars);
string imgur = "http://imgur.com/" + finalString;
But of course it just gave me random imgur links which don't work, how could I check if the link is valid and then give it to the user or how could I use imgurs own "https://imgur.com/gallery/random" and return the link from that?
Imgur API exposes a function to fetch a random set of gallery images:
https://api.imgur.com/endpoints/gallery#gallery-random
Method GET
Route https://api.imgur.com/3/gallery/random/random/{page}

Break line in long label text

Is there any trick to break a label text? Because '\n' '\r' '\n\r' don't work.
Many Thanks
if you use those 2 parameters you do what you want don't you ?
app.createLabel(text).setWidth(width).setWordWrap(true)
here is an example (among other widgets ;-):
function showurl() {
var app = UiApp.createApplication();
app.setTitle("Anchor in a popup ;-)");
var panel = app.createFlowPanel()
var image = app.createImage('https://sites.google.com/site/appsscriptexperiments/home/photo.jpg').setPixelSize(50, 50)
var link = app.createAnchor('This is your link', 'https://sites.google.com/site/appsscriptexperiments/home');
var lab = app.createLabel("wrap it because it's too narrow").setWidth(90).setWordWrap(true);
var quit = app.createButton('quit');
panel.add(image).add(link).add(lab).add(quit);
app.add(panel);
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
EDIT : I found an old post(on the Google group forum, thanks again Henrique ;-) about breaking lines in toast messages and here is the code I used for that case... the principle should work for Labels too but I didn't try.
To use it, just use \n (where you want to break the line) in a variable containing your text and pass it through this function. (there are some comment in the script to explain)
function break_(msg){
var temp = escape(msg);// shows codes of all chars
msg = unescape(temp.replace(/%20/g,"%A0")); // replace spaces by non break spaces
temp = msg.replace("\n"," "); // and replace the 'newline' by a normal space
return temp; // send back the result
}
Would something like this work?
//takes a line of text and returns a flex table broken by \n
function breakLabel(text) {
var app = UiApp.getActiveApplication();
var flexTable = app.createFlexTable();
text = text.split('\n'); // split into an array
for (var i=0; i<text.length; i++){
flexTable.setWidget(i, 0, app.createLabel(text[i].toString()));
}
return flexTable;
}
Adding them to a vertical panel helps as well (not the way you want, but still..):
var vPanel = app.createVerticalPanel().setSize(100,100);
var label = app.createLabel('predominantly blabla blala blabla');
app.add(vPanel.add(label));
See reference
For anyone just now stumbling upon this, the best solution seems to be creating an HTML output for anything that needs line breaks.
Documentation
var htmlApp = HtmlService
.createHtmlOutput('<p>A change of speed, a change of style...</p>')
.setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setTitle('My HtmlService Application')
.setWidth(250)
.setHeight(300);
SpreadsheetApp.getActiveSpreadsheet().show(htmlApp);
// The script resumes execution immediately after showing the dialog.

Greasemonkey script to find rows with certain conditions

I tried some different ways do find rows in a table where a columns contain a particular link.
My goal: replace an icon when a link to xyz is in this same row as the image.
This is my snippet so far:
var rows = document.getElementsByTagName("tr");
for(var i = rows.length - 1; i >= 0; i--) {
var links = rows[i].getElementsByTagName("a");
for(var k = links.length - k; k >= 0; k--) {
if (links[k].href =="http://www.XXXX.net/forum/index.php?showforum=121"){
var images = rows[i].getElementsByTagName("img");
for (var j=0;j<images.length;j++) {
images[j].src = "http://www.XXXX.net/forum/folder_post_icons/icon7.gif";
}
}
}
}
I'm pretty sure this is not really the best concept. But as you might see I try to search links in all rows and once the link to forum "121" is found, I try to replace all images in this particular row.
What I get is every image at the site getting replaced.
Since it's simple enough, here's a complete script that does that.
It uses jQuery and here's a handy jQuery reference. See, especially, the Selectors section (which are almost the same as CSS Selectors).
Re: "What I get is every image at the site getting replaced." ...
This maybe because the search criteria is too broad. If it's a poorly designed (uses table layouts) page, every image may be in a table row with a target link!
When posting Greasemonkey questions, link to the target page, or at the very minimum, post enough of the page's HTML that we can adjust the GM script to match.
Anyway, this will work, possibly pending more information about the target page:
// ==UserScript==
// #name _Replace image on custom-targeted row
// #include http://www.XXXX.net/forum/*
// #require http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js
// ==/UserScript==
//--- This may need tuning based on information not provided!
var targetLinks = $("tr a[href*='showforum=121']");
//--- Loop through the links and rewrite images that are in the same row.
targetLinks.each ( function () {
//--- This next assumes that the link is a direct child of tr > td.
var thisRow = $(this).parent ().parent ();
//--- This may need tuning based on information not provided!
var images = thisRow.find ("td img");
//--- Replace all target images in the current row.
images.each ( function () {
$(this).attr (
'src',
'http://www.XXXX.net/forum/folder_post_icons/icon7.gif'
);
} );
} );

Resources