google visualization Query second iteration - google-visualization

I am using google.visualization.Query to get data from a Google Sheet. I am noticing the result does not include a comma between rows, which is causing an issue because I am trying to create an array. How can I fix this?
Rows:
4,1,some text,2/25/2021,3/2/2021
9,1,some text,2/25/2021,3/1/2021
Query:
function initialize() {
var opts = {sendMethod: 'auto'};
var queryString = encodeURIComponent('SELECT A, B, D, F, G WHERE B=1 offset 1');
var query = new google.visualization.Query(
'https://docs.google.com/spreadsheets/d/1jyiF2nZsqkxzSndIaiZEVivFB7EzozHHuE0Qx2hU1T4/gviz/tq?tq=' + queryString);
query.send(handleQueryResponse);
}
Query Result:
4,1,some text,2/25/2021,3/2/2021 9,1,some text,2/25/2021,3/1/2021
Iterate in an Array:
dataTable.addRows([
[ '+myArray[0]+', <div class="ggl-tooltip">'+myArray[1]+'</div>', myArray[2], myArray[3) ]
]);

in the query's response function, you can get the data from the response argument.
function handleQueryResponse(response) {
var data = response.getDataTable();
this will return a google data table, which can then be used to draw a chart.
if you need the raw data in an array, you can use the toJSON method.
var data = response.getDataTable();
var rawData = data.toJSON();
the json will be returned in the format found here...

Related

Making a list using api in google sheets

I am attempting to pull faction information from torns api but it puts all data into a single cell rather than listing. heres what ive got so far.
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Faction members')
.addItem('Pulls faction member info','callNumbers')
.addToUi();
}
function callNumbers() {
var response = UrlFetchApp.fetch("https://api.torn.com/faction/42911?selections=basic&key=xFtPCG2ygjbhmKWI");
Logger.log(response.getContentText());
var fact = response.getContentText();
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1,2).setValue([fact]);
}```
You could try to parse the information using JSON.parse. Something like:
function callNumbers() {
var response = UrlFetchApp.fetch("https://api.torn.com/faction/42911?selections=basic&key=xFtPCG2ygjbhmKWI");
Logger.log(response.getContentText());
var fact = response.getContentText();
var myObject = JSON.parse(fact);
// define an array of all the object keys
var headerRow = Object.keys(myObject);
// define an array of all the object values
var row = headerRow.map(function(key){ return myObject[key]});
// define the contents of the range
var contents = [
headerRow,
row
];
// select the range and set its values
var ss = SpreadsheetApp.getActive();
var rng = ss.getActiveSheet().getRange(1, 1, contents.length, headerRow.length )
rng.setValues(contents)
}

Google Script App Delete Duplicate Rows with a Specific Value in Specific Column in Google Sheet

I have a google sheet where people submit tasks they are working on and they'll submit a status update which is either 'in progress' or 'complete' for let's say task A. Task A is in column D[4] and Status is in column E[5]. I'm trying to get this code to only delete the 'in progress' row for Task A when there is duplicate Task A with the status being 'Complete'. This works for identifying the duplicate and removes the duplicate rows in order, but I'm not sure how to get it to only delete duplicate 'Task A' 'In Progress' rows when there is a 'Task A' 'Complete' row. Any help would be much appreciated!
function removeDuplicates() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet2");
var data = sheet.getDataRange().getValues();
var newData = [];
for (i in data) {
var row = data[i];
var duplicate = false;
for (j in newData) {
if(row[3] == newData[j][3]){
duplicate = true;
}
}
if (!duplicate) {
newData.push(row);
}
}
sheet.clearContents();
sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
I would try
function removeDuplicates()
{
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("test");
var dataRange = sheet.getDataRange();
var data = dataRange.getValues();
var indexOfStatusColumn = 4;
var newData = [];
data.forEach(function (row, rowI){
var isDuplicate = false
if (newData.length)
newData.forEach(function (dup, dupI)
{
if (dup[3] == row[3])
{
if (row[indexOfStatusColumn] == "Complete" && dup[indexOfStatusColumn] != "Complete")
newData[dupI][indexOfStatusColumn] = "Complete";
isDuplicate = true;
return (false);
}
})
if (!isDuplicate)
newData.push(row);
});
dataRange = sheet.getRange(2, 1, dataRange.getLastRow() - 1, dataRange.getLastColumn());
dataRange.clearContent();
sheet.getRange(1, 1, newData.length, newData[0].length).setValues(newData);
}
few things
I use forEach()loop it's more efficient
break loop by returning falseto avoid parsing trough all your newDatauselessly
when I find a duplicate I perform some of this actions
Check if duplicate is Complete on data and not on newData if so
change the value in newDatato "Complete" this way it will keep the complete status (be careful if there's different datas on both rows it will probably twist datas).
also use clearContent() from a range to avoid removing all the content of the sheet but only a specific portion of it. Here I've rebuilded it to keep the header
REFERENCES
forEach()
Tanaike benchmark
clearContent()

How to find and replace date, on timebased trigger by using ScriptApp Custom function

I have a Google Document with only one date in the body of the document. I am trying to write a script that updates the date every 24 hours.
The date in the document is currently set to "11/01/2016" as text, 1 day less than today (12/01/2016). I assumed using a replaceText() would work.
This is my script at the moment.
ScriptApp.newTrigger("myFunction")
.timeBased()
.atHour(24)
.everyDays(1)
.inTimezone("GMT")
function myFunction()
{
var date = Utilities.formatDate(new Date(), "GMT", "dd/MM/yyy");
var doc = DocumentApp.openById("ID of Document");
doc.replaceText(date-1,date) ;
}
What I am doing wrong here?
You can't replace text on document object, you need to get document body. your date is a string, you can't get yesterday by date-1. refer the date conversion too.
function myFunction()
{
var body = DocumentApp.getActiveDocument().getBody();
var d = new Date();
var yesterdayDate = Utilities.formatDate(new Date(d.getTime()-1*(24*3600*1000)), "GMT", "dd/MM/yyy");
var todayDate = Utilities.formatDate(d, "GMT", "dd/MM/yyy");
body.replaceText(yesterdayDate,todayDate) ;
}

How to retrieve a total result count from the Sitecore 7 LINQ ContentSearch API?

In Lucene.Net, it is possible to retrieve the total number of matched documents using the TopDocs.TotalHits property.
This functionality was exposed in the Advanced Database Crawler API using an out parameter in the QueryRunner class.
What is the recommended way to retrieve the total result count using Sitecore 7's new LINQ API? It does not seem possible without enumerating the entire result set. Here is what I have so far:
var index = ContentSearchManager.GetIndex("sitecore_web_index");
using (var context = index.CreateSearchContext())
{
var query = context.GetQueryable<SearchResultItem>()
.Where(item => item.Content == "banana");
var totalResults = query.Count(); // Enumeration
var topTenResults = query.Take(10); // Enumeration again? this can't be right?
...
}
Try this:
using Sitecore.ContentSearch.Linq; // GetResults on IQueryable
var index = ContentSearchManager.GetIndex("sitecore_web_index");
using (var context = index.CreateSearchContext())
{
var query = context.GetQueryable<SearchResultItem>()
.Where(item => item.Content == "banana");
var results = query.GetResults();
var totalResults = results.TotalSearchResults;
var topTenResults = results.Hits.Take(10);
...
}
To get more info about sitecore and linq you can watch this session and look at this repo.

How to disable a date range in Jquery datepicker

I want to disable a range of dates which I are fetched using Ajax. I'm doing it as follows -
$("#date_frm").datepicker({
dateFormat: 'yy-mm-dd',
constrainInput: true,
beforeShow:function(input, inst) {
$.ajax({
type: "POST",
url: "/admin/get_time_span",
data: "",
success: function(data) {
disabled_day = data;
},
});
},
beforeShowDay: disableRangeOfDays
});
function disableRangeOfDays(d)
{
//var arr = "2012-04-19 to 2012-04-26,";
var arr = disabled_day.split(",");
var arr = arr.split(",");
var cnt = arr.length-1;
for(i=0; i<cnt; i++) {
arr1 = arr[i].split(" to ");
//create date for from_date
frm_dt = arr1[0].split('-');
//create date for to_date
to_dt = arr1[1].split('-');
if(d >= new Date(frm_dt[0],(frm_dt[1]-1),frm_dt[2]) &&
d <= new Date(to_dt[0],(to_dt[1]-1),to_dt[2])) {
return [false];
}
}
return [true,''];
}
This works but not for the first time. When I open the date picker first time, the date range still selectable. But, after I close and reopen it, the date range is disabled. Also, if I change the month and come back to the current month then also it works. How can I disable the date range for the first time I open the date picker ? Also, for each month, I want to fetch the date ranges and disable them. How can I do this ?
After spending much time in checking possibilities, I fetched all the date ranges only once while loading the page and assigned all to a hidden field. I removed the Ajax call and used the value of the hidden field directly in the function disableRangeOfDays(d) and it worked as expected.