Google fusion query Unable to use aggregate functions - "Could not parse query" - google-fusion-tables

Am trying out google fusion table queries ….
I can’t seem to use aggregate functions or Upper() etc… it works fine without them.
error: "Could not parse query".
http://jsfiddle.net/leebasky/j7kok7yz/
google.setOnLoadCallback(drawTable);
function drawTable() {
var opts = {sendMethod: 'auto'};
var query = new google.visualization.Query('https://www.google.com/fusiontables/gvizdata?&tq=', opts);
query.setQuery('SELECT col0 as test, upper(col2) from 1198pzojwSFwuyeL8hsrmKYVHNLdNsB44bxecZYs0 limit 10');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {showRowNumber: true});
}

As mentioned in the comment, the desired functions are currently not available.
But when you only want to apply a different format for the data this may be achieved.
The uppercase may be done via CSS text-transform: uppercase.
The YEAR you may get via a date-formatter :{pattern: 'yyyy'}
google.setOnLoadCallback(drawTable);
function drawTable() {
var opts = {
sendMethod: 'auto'
};
var query = new google.visualization.Query('https://www.google.com/fusiontables/gvizdata?&tq=', opts);
query.setQuery('SELECT col0 as test, col2 from 1198pzojwSFwuyeL8hsrmKYVHNLdNsB44bxecZYs0 limit 10');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
var formatter = new google.visualization.DateFormat({
pattern: 'yyyy'
});
formatter.format(data, 0);
var table = new google.visualization.Table(document.getElementById('table_div'));
table.draw(data, {
showRowNumber: true
});
}
#table_div tbody tr td:nth-child(3){
text-transform: uppercase;
}
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['table']}]}"></script>
<div id="table_div"></div>

Related

Is there some kind of limit when using IMPORTXML? [duplicate]

I am stucking on a "scraping problem" right now. Especially i want to extract the name of the author from a webpage to google spreadsheet. Actually the function =IMPORTXML(A2,"//span[#class='author vcard meta-item']") is working, but after i raise the amount of links to scrape it just starts to load endless.
So i researched and find out, that this problem is due to the fact, that there is a limit of google.
Does anybody know of to exceed the limit or a script, which i could "easily copy" ? - i really do not have a hunch of coding.
I created a custom import function that overcomes all limits of IMPORTXML I have a sheet using this in about 800 cells and it works great.
It makes use of Google Sheet’s custom scripts (Tools > Script editor…) and searches through content using regex instead of xpath.
function importRegex(url, regexInput) {
var output = '';
var fetchedUrl = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
if (fetchedUrl) {
var html = fetchedUrl.getContentText();
if (html.length && regexInput.length) {
output = html.match(new RegExp(regexInput, 'i'))[1];
}
}
// Grace period to not overload
Utilities.sleep(1000);
return output;
}
You can then use this function like any function.
=importRegex("https://example.com", "<title>(.*)<\/title>")
Of course, you can also reference cells.
=importRegex(A2, "<title>(.*)<\/title>")
If you don’t want to see HTML entities in the output, you can use this function.
var htmlEntities = {
nbsp: ' ',
cent: '¢',
pound: '£',
yen: '¥',
euro: '€',
copy: '©',
reg: '®',
lt: '<',
gt: '>',
mdash: '–',
ndash: '-',
quot: '"',
amp: '&',
apos: '\''
};
function unescapeHTML(str) {
return str.replace(/\&([^;]+);/g, function (entity, entityCode) {
var match;
if (entityCode in htmlEntities) {
return htmlEntities[entityCode];
} else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
return String.fromCharCode(parseInt(match[1], 16));
} else if (match = entityCode.match(/^#(\d+)$/)) {
return String.fromCharCode(~~match[1]);
} else {
return entity;
}
});
};
All together…
function importRegex(url, regexInput) {
var output = '';
var fetchedUrl = UrlFetchApp.fetch(url, {muteHttpExceptions: true});
if (fetchedUrl) {
var html = fetchedUrl.getContentText();
if (html.length && regexInput.length) {
output = html.match(new RegExp(regexInput, 'i'))[1];
}
}
// Grace period to not overload
Utilities.sleep(1000);
return unescapeHTML(output);
}
var htmlEntities = {
nbsp: ' ',
cent: '¢',
pound: '£',
yen: '¥',
euro: '€',
copy: '©',
reg: '®',
lt: '<',
gt: '>',
mdash: '–',
ndash: '-',
quot: '"',
amp: '&',
apos: '\''
};
function unescapeHTML(str) {
return str.replace(/\&([^;]+);/g, function (entity, entityCode) {
var match;
if (entityCode in htmlEntities) {
return htmlEntities[entityCode];
} else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
return String.fromCharCode(parseInt(match[1], 16));
} else if (match = entityCode.match(/^#(\d+)$/)) {
return String.fromCharCode(~~match[1]);
} else {
return entity;
}
});
};
There is no such script to exceed the limits. Since the code is run on a Google machine (server) you can not cheat.
Some limits are bind to your spreadsheet, so you could try to use multiple spreadsheets, if that helps.

Get term for selected autocomplete when multiple are on one page

I have a page where I am adding jquery-ui autocompletes dynamically
My .autocomplete() code includes a $.getJSON('my_url', my_payload) where, in my_payload,' I am trying to send the request.term (what I typed into the jqueryui textbox) as well as the id of the jquery ui text box.
The problem is, for all the dynamically added textboxes, they were just picking up the term and id of the original autocomplete.
I managed to find a way to get the id of the added (not original) autocomplete by wrapping the autocomplete in a function that has the added field passed in as a parameter, but because the 'term' is in the request, which comes from .autocomplete, I do not know how to get this for the new ones.
https://jsfiddle.net/amchugh89/1L8jvea5/4/
//=======dynamic formset script from https://medium.com/all-about-
django/adding-forms-dynamically-to-a-django-formset-375f1090c2b0======
function updateElementIndex(el, prefix, ndx) {
var id_regex = new RegExp('(' + prefix + '-\\d+)');
var replacement = prefix + '-' + ndx;
if ($(el).attr("for")) $(el).attr("for", $(el).attr("for").replace(id_regex, replacement));
if (el.id) el.id = el.id.replace(id_regex, replacement);
if (el.name) el.name = el.name.replace(id_regex, replacement);
}
function cloneMore(selector, prefix) {
var newElement = $(selector).clone(true);
var total = $('#id_' + prefix + '-TOTAL_FORMS').val();
newElement.find(':input:not([type=button]):not([type=submit]):not([type=reset])').each(function() {
if ($(this).attr('name')){
var name = $(this).attr('name').replace('-' + (total-1) + '-', '-' + total + '-');
var id = 'id_' + name;
$(this).attr({'name': name, 'id': id}).val('').removeAttr('checked');
if($(this).attr('id').includes('gl')){
console.log($(this).attr('id'))
make_autocomplete($(this))
}
}
});
newElement.find('label').each(function() {
var forValue = $(this).attr('for');
if (forValue) {
forValue = forValue.replace('-' + (total-1) + '-', '-' + total + '-');
$(this).attr({'for': forValue});
}
});
total++;
$('#id_' + prefix + '-TOTAL_FORMS').val(total);
$(selector).after(newElement);
var conditionRow = $('.form-row:not(:last)');
conditionRow.find('.btn.add-form-row')
.removeClass('btn-success').addClass('btn-danger')
.removeClass('add-form-row').addClass('remove-form-row')
.html('<span class="glyphicon glyphicon-minus" aria-hidden="true"></span>');
return false;
}
function deleteForm(prefix, btn) {
var total = parseInt($('#id_' + prefix + '-TOTAL_FORMS').val());
if (total > 1){
btn.closest('.form-row').remove();
var forms = $('.form-row');
$('#id_' + prefix + '-TOTAL_FORMS').val(forms.length);
for (var i=0, formCount=forms.length; i<formCount; i++) {
$(forms.get(i)).find(':input').each(function() {
updateElementIndex(this, prefix, i);
});
}
}
return false;
}
$(document).on('click', '.add-form-row', function(e){
e.preventDefault();
cloneMore('.form-row:last', 'form');
return false;
});
$(document).on('click', '.remove-form-row', function(e){
e.preventDefault();
deleteForm('form', $(this));
return false;
});
//====================
//AUTOCOMPLETE==(that allows for multiple ACs
https://stackoverflow.com/questions/24656589/using-jquery-ui-autocomplete-
with-multiple-input-fields)===================================
function make_autocomplete(ee) {
ee.on("focus", function(){ //.autocomplete({
$(this).autocomplete({
minLength: 2,
source: function( request, response ) {
var term = request.term;
//with the formset, I want to get the row for which I am typing in the
'term'
var this_formset_row_autocomplete_id
=ee.attr('id');//$(this.element).prop("id");//
$(this).attr('id');
console.log(this_formset_row_autocomplete_id);
var corresponding_branch_html_id =
this_formset_row_autocomplete_id.replace('gl_account','branch');
var this_formset_row_branch_sym_id =
$('#'+corresponding_branch_html_id).val();
//console.log(corresponding_branch_html_id, this_formset_row_branch_sym_id)
var appended_data={term:term,
this_formset_row_branch_sym_id:this_formset_row_branch_sym_id};
console.log(appended_data);
$.getJSON( "{% url 'dashapp:account_autocomplete' %}", appended_data,
function( data,
status, xhr ) {
//cache[ term ] = data;
response( data );
});
}
});
});
}//end function make_autocomplete
var ee =$( ".account_autocomplete" )
make_autocomplete(ee)
//===============
You may want to try to make it more simple for testing. Something like:
function make_autocomplete(obj) {
obj.autocomplete({
minLength: 2,
source: function(req, resp) {
var myData = {
term: req.term,
original_form_branch_id: $(this).closest("form").attr("id"),
this_formset_row_branch_sym_id: $(this).closest(".row").find("select").val()
}
$.getJSON("myurl", myData, function(results) {
resp(results);
});
}
});
}
Fiddle: https://jsfiddle.net/Twisty/pywb9nhv/23/
This uses .closest() to gather details from the relative objects. Also I do not see any benefit to initializing Autocomplete on focus event.
If you would like further help, please provide Example Data that can be used in a working example.
Hope that helps a little.

Why my md-autoComplete is not displaying return values

I am using Angular Material for the first time. I am stuck with an issue with autocomplete. Below is my template:
<md-autocomplete class="flex"
md-no-cache="true"
md-selected-item="c.receipt"
md-item-text="item.name"
md-search-text="SearchText"
md-items="item in querySearch(SearchText)"
md-floating-label="search">
<md-item-template>
<span><span class="search-result-type">{{item.GEOType}}</span><span md-highlight-text="SearchText">{{item.GEOName+(item.country?' / '+item.country:'')}}</span></span>
</md-item-template>
<md-not-found>No matches found.</md-not-found>
</md-autocomplete>
And in ctrl I have:
$scope.querySearch = function (query) {
var GeoDataAPIUrl = '/api/TargetSettings/RetrieveCorridorLeverValues';
if (query.length < 5)
return;
else {
var GeoDataSearchUrl = GeoDataAPIUrl + '?' + 'strGeoName=' + query;
$http
.get(GeoDataSearchUrl)
.then(function (geoAPIResponse) {
console.log("GeoAPIResponse was ", geoAPIResponse);
return geoAPIResponse.data;
},
function (geoAPIError) {
console.log("GeoAPI call failed ", geoAPIError);
});
}
};
With above code, I am getting nothing as suggestions, only my not-found text is displayed, while my http call return an array which is printed in console too. Am I missing something??
I saw at many places, people have used some filters with autocomplete, I dont think that is something essential.
Pls advice how to make above work.
$http returns promise and md-autocomplete uses same promise to display the result. In your case you are returning result but not promise. Your code should be
$scope.querySearch = function (query) {
var GeoDataAPIUrl = '/api/TargetSettings/RetrieveCorridorLeverValues';
if (query.length < 5)
return;
else {
var GeoDataSearchUrl = GeoDataAPIUrl + '?' + 'strGeoName=' + query;
var promise = $http.get(GeoDataSearchUrl).then(function (geoAPIResponse) {
console.log("GeoAPIResponse was ", geoAPIResponse);
return geoAPIResponse.data;
},
function (geoAPIError) {
console.log("GeoAPI call failed ", geoAPIError);
});
return promise;
}
};
It will work now.

on() doesn't work with live data using jQuery, how to?

i have some dynamic data that gets appended to a list and any links in that data doesnt seem to work.
i am using jquery 1.8.3 and on() should account for the live method, i think
setInterval(function () {
getNot();
}, 2000);
function getNot() {
var data = {
t1: 'test1',
t2: 'test2',
t3: 'test3'
};
var size = 0,
li = '';
$.each(data, function (k, v) {
li += '<li>' +
'<a href="#" class="add" data-listid="' + k + '">' +
'<h2>load data - ' + k + '</h2>' +
'</a>' +
'</li>';
size++;
});
var but = $('#not'),
ul = $('#not_ul');
but.find('span').text(size + ' Notifications');
ul.html(li);
ul.listview().listview("refresh");
}
// this doesn't seem to work
$('.add').on("click", function () {
var listId = $(this).data('listid');
console.log(listId);
return false;
});
see full example here
any ideas on this issue?
$('.add').on("click", function () {
You need to pass a selector to make on generate a delegate event:
$('#{containerId}').on("click", '.add', function () {
var listId = $(this).data('listid');
console.log(listId);
return false;
});
containerId should be the closest static element to the dynamic created .adds elements.

Does the iPad have a governor?

I loop through an ajax recordset and insert rows into an html5 database.
In Google Chrome, the program inserts 581 rows, whereas on the iPad, it only inserts between 20 and 80 rows.
I output the commands to the document body just to make sure they are being run, so I know there are 581 insert statements being run on the iPad, but then the table only has a handful.
OK, here's how I do it.
I first drop the table, then when that's done, I create the table.
Then when that's done, I do my ajax call.
When that comes back, I loop through the recordset and insert into the html5 local database.
var DropTableiUsr = function() {
var DropTableDeferred = new $.Deferred();
var CreateTableDeferred = new $.Deferred();
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'drop table iUsr;'
,[]
,DropTableDeferred.resolve()
);
});
DropTableDeferred.done(function() {
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'CREATE TABLE IF NOT EXISTS iUsr'
+ '(UsrID Integer NOT NULL PRIMARY KEY'
+ ',UsrGradeDate Varchar(128)'
+ ');'
,[]
,CreateTableDeferred.resolve()
);
});
});
CreateTableDeferred.done(function() {
var settings = {};
settings.data = {};
settings.data.method = 'View0';
var myPromise = $(this).myAjax('com/Usr.cfc', settings); // 'this' normally points to the DOM element that is the context of what caused the Ajax call.
myPromise.done(function(result) {
if (result.RTN) {
var qryUsr = result.qry.DATA;
qryUsr.RecordCount = result.qry.ROWCOUNT;
// qryUsr.ColumnList = result.qry.COLUMNS;
for (var CurrentRow=0;CurrentRow < qryUsr.RecordCount;CurrentRow++) {
myFunction(CurrentRow);
};
function myFunction(CurrentRow) {
$('body').append('INSERT INTO iUsr(UsrID,UsrGradeDate) VALUES(' + qryUsr.USRID[CurrentRow] + ',' + qryUsr.USRGRADEDATE[CurrentRow] + ')<br>');
dbo.transaction(function(myTrans) {
myTrans.executeSql(
'INSERT INTO iUsr(UsrID,UsrGradeDate) VALUES(?,?)',
[
qryUsr.USRID[CurrentRow],
qryUsr.USRGRADEDATE[CurrentRow]
]
)
});
};
} else {
$('#msg').text(result.MSG);
}
});
myPromise.fail(function(jqXHR, textStatus,C ) {
alert('PopulateiUsr: ' + C);
$('.container').append(jqXHR.responseText);
})
$('body').append('iUsr<br>');
});
};
$('#Reset').click(function() {
DropTableiUsr();
});
If you move the screen around while something is processing, it stops the processing.
Try displaying a countdown on the INSERT INTO callback, and you will see that it stops the countdown if you scroll the screen down.

Resources