I have constructed a Grid in Vaadin 14 using a parser to extract from files as shown below:
Grid<String[]> grid = new Grid<>();
try {
List<String[]> entries = reader.readAll();
// Assume the first row contains headers
String[] headers = entries.get(0);
for (int i = 0; i < headers.length-1; i++) {
final int columnIndex = i;
String header = headers[i];
String humanReadableHeader = SharedUtil.camelCaseToHumanFriendly(header);
grid.addColumn(str -> str[columnIndex]).setHeader(humanReadableHeader).setSortable(true).setWidth("100px");
}
grid.setItems(entries.subList(1, entries.size()));
What I want to do next is add a CheckBox to every row that would return a visualization of the data in the corresponding row. So my question is two-fold:
Is there a function that already exists to emulate this behavior via clicking anywhere on a row?
If not, what would be the best way to initialize a Grid to accommodate this?
Simply add a component column:
Grid<String[]> grid = new Grid<>();
try {
List<String[]> entries = reader.readAll();
// Assume the first row contains headers
String[] headers = entries.get(0);
for (int i = 0; i < headers.length-1; i++) {
final int columnIndex = i;
String header = headers[i];
String humanReadableHeader = SharedUtil.camelCaseToHumanFriendly(header);
grid.addColumn(str -> str[columnIndex]).setHeader(humanReadableHeader).setSortable(true).setWidth("100px");
}
// Here goes your checkbox column
grid.addComponentColumn(item -> {
// Create the checkbox
}).setHeader("<the header>");
grid.setItems(entries.subList(1, entries.size()));
Related
I'm doing a project with Arduino, I'm trying to post variable's data into google sheet integration but the code doesn't work.
I tried to correct it, but it doesn't post anyway....this is the code.
The error was
ss.sheet.getSheetByName it's not a function
I took the code from Arduino IoT Cloud Google sheet Integration
function myFunction() {
// get sheet named RawData
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Dati");
var MAX_ROWS = 1440; // max number of data rows to display
// 3600s / cloud_int(30s) * num_ore(12h)
var HEADER_ROW = 1; // row index of header
var TIMESTAMP_COL = 1; // column index of the timestamp column
function doPost(e) {
var cloudData = JSON.parse(e.postData.contents); // this is a json object containing all info coming from IoT Cloud
//var webhook_id = cloudData.webhook_id; // really not using these three
//var device_id = cloudData.device_id;
//var thing_id = cloudData.thing_id;
var values = cloudData.values; // this is an array of json objects
// store names and values from the values array
// just for simplicity
var incLength = values.length;
var incNames = [];
var incValues = [];
for (var i = 0; i < incLength; i++) {
incNames[i] = values[i].name;
incValues[i] = values[i].value;
}
// read timestamp of incoming message
var timestamp = values[0].updated_at; // format: yyyy-MM-ddTHH:mm:ss.mmmZ
var date = new Date(Date.parse(timestamp));
/*
This if statement is due to the fact that duplicate messages arrive from the cloud!
If that occurs, the timestamp is not read correctly and date variable gets compromised.
Hence, execute the rest of the script if the year of the date is well defined and it is greater
then 2018 (or any other year before)
*/
if (date.getYear() > 2018) {
// discard all messages that arrive 'late'
if (sheet.getRange(HEADER_ROW+1, 1).getValue() != '') { // for the first time app is run
var now = new Date(); // now
var COMM_TIME = 5; // rough overestimate of communication time between cloud and app
if (now.getTime() - date.getTime() > COMM_TIME * 1000) {
return;
}
}
// this section write property names
sheet.getRange(HEADER_ROW, 1).setValue('timestamp');
for (var i = 0; i < incLength; i++) {
var lastCol = sheet.getLastColumn(); // at the very beginning this should return 1 // second cycle -> it is 2
if (lastCol == 1) {
sheet.getRange(HEADER_ROW, lastCol + 1).setValue(incNames[i]);
} else {
// check if the name is already in header
var found = 0;
for (var col = 2; col <= lastCol; col++) {
if (sheet.getRange(HEADER_ROW, col).getValue() == incNames[i]) {
found = 1;
break;
}
}
if (found == 0) {
sheet.getRange(HEADER_ROW, lastCol+1).setValue(incNames[i]);
}
}
}
// redefine last column and last row since new names could have been added
var lastCol = sheet.getLastColumn();
var lastRow = sheet.getLastRow();
// delete last row to maintain constant the total number of rows
if (lastRow > MAX_ROWS + HEADER_ROW - 1) {
sheet.deleteRow(lastRow);
}
// insert new row after deleting the last one
sheet.insertRowAfter(HEADER_ROW);
// reset style of the new row, otherwise it will inherit the style of the header row
var range = sheet.getRange('A2:Z2');
//range.setBackground('#ffffff');
range.setFontColor('#000000');
range.setFontSize(10);
range.setFontWeight('normal');
// write the timestamp
sheet.getRange(HEADER_ROW+1, TIMESTAMP_COL).setValue(date).setNumberFormat("yyyy-MM-dd HH:mm:ss");
// write values in the respective columns
for (var col = 1+TIMESTAMP_COL; col <= lastCol; col++) {
// first copy previous values
// this is to avoid empty cells if not all properties are updated at the same time
sheet.getRange(HEADER_ROW+1, col).setValue(sheet.getRange(HEADER_ROW+2, col).getValue());
for (var i = 0; i < incLength; i++) {
var currentName = sheet.getRange(HEADER_ROW, col).getValue();
if (currentName == incNames[i]) {
// turn boolean values into 0/1, otherwise google sheets interprets them as labels in the graph
if (incValues[i] == true) {
incValues[i] = 1;
} else if (incValues[i] == false) {
incValues[i] = 0;
}
sheet.getRange(HEADER_ROW+1, col).setValue(incValues[i]);
}
}
}
} // end if (date.getYear() > 2018)
}
}
You are trying to push data directly to the Google sheet on the cloud but it's URL uses https for security reasons. The encryption for https is rather complex and SSL crypto is required. Arduino hardware is normally not fast enough to do SSL. You need more powerful hardware like Raspberry Pi to write directly to the Google Cloud.
However, you can use PushingBox, a cloud that can send notifications based on API calls, to do the hard work for you if you insist on using Arduino ( any variant) in your IOT project. Here you send your data to Pushingbox, it uses http URL, and it will in turn the data to Google sheet.
In Dart I want to take input from user 100 data into a list from console. How can I do that?
void main() {
int value;
List<int> list = [0];
var largest = list[0];
for (var i = 0; i < list.length; i++) {
list.add(stdin.readByteSync());
if (list[i] > largest) {
largest = list[i];
}
}
print(largest);
}
After some dialog in the chat we ended up with the following solution:
import 'dart:io';
void main() {
// Create empty list
final list = <int>[];
// Number of numbers we want to take
const numbersWeWant = 100;
// Loop until we got all numbers
for (var i = 0; i < numbersWeWant; i++) {
int? input;
// This loop is for asking again if we get something we don't see as a number
do {
print('Input number nr. $i:');
// Get a number. input is going to be null if the input is not a number
input = int.tryParse(stdin.readLineSync() ?? '');
} while (input == null); // loop as long as we don't got a number
// Add the number we got to the list
list.add(input);
}
// Use list.reduce to find the biggest number in the list by reducing the
// list to a single value using the compare method.
print('Largest number: ${list.reduce((a, b) => a > b ? a : b)}');
}
I want to accomplish something like this:
I have a sort of "Relational" Spreadsheet, and I want rows to be colored according.
I manually choosing a unique color for each Category on the "Categories" Sheet or generating a unique color based on the string content, either would work for my use case.
Not the best solution but it works
function onEdit(e) {
if(e){
var ss = e.source.getActiveSheet();
var range = e.source.getActiveRange();
var r1 = range.getRow();
var c1 = range.getColumn();
var rowsCount = range.getNumRows();
for(var i=0; i<rowsCount; i++){
var row = ss.getRange(r1+i,1,1,ss.getMaxColumns());
updateRow(row, ss);
}
}
}
function updateRow(row, ss){
if (ss.getName() == "Entries") { // This is the sheet name
var cell = row.getCell(1,1);
var firstCellValue = cell.getValue();
if(firstCellValue){
cell.setBackgroundColor(stringToColor(firstCellValue));
}
else{
cell.setBackgroundColor(null);
}
}
}
function stringToColor(str) {
var hash = 0;
for (var i = 0; i < str.length; i++) {
hash = str.charCodeAt(i) + ((hash << 5) - hash);
}
var colour = '#';
for (var i = 0; i < 3; i++) {
var value = (hash >> (i * 8)) & 0xFF;
colour += ('00' + value.toString(16)).substr(-2);
}
return colour;
}
Based on this answer
in conditional formatting select the range you want to apply colors, select color, choose Text is exactly and set value:
I’m using Google Sheets to conduct some text analysis. I would like to automate the process by linking a spreadsheet to a Google doc file on my GDrive to extract text directly. It doesn’t have to structured/formatted. It just has to be a plain text. Does it take a comprehensive scripting or the task of copying text is simple?
I searched the web but couldn’t find one.
To help you start, here is an SO thread.
Same scenario: Get data from the Google Sheets and copy it to the Google Docs.
A reference from Open Source Hacker: Script for generating Google documents from Google spreadsheet data source.
Here is the code provided in the article. You can modify it by yourself depending on your use.
/**
* Generate Google Docs based on a template document and data incoming from a Google Spreadsheet
*
* License: MIT
*
* Copyright 2013 Mikko Ohtamaa, http://opensourcehacker.com
*/
// Row number from where to fill in the data (starts as 1 = first row)
var CUSTOMER_ID = 1;
// Google Doc id from the document template
// (Get ids from the URL)
var SOURCE_TEMPLATE = "xxx";
// In which spreadsheet we have all the customer data
var CUSTOMER_SPREADSHEET = "yyy";
// In which Google Drive we toss the target documents
var TARGET_FOLDER = "zzz";
/**
* Return spreadsheet row content as JS array.
*
* Note: We assume the row ends when we encounter
* the first empty cell. This might not be
* sometimes the desired behavior.
*
* Rows start at 1, not zero based!!! 🙁
*
*/
function getRowAsArray(sheet, row) {
var dataRange = sheet.getRange(row, 1, 1, 99);
var data = dataRange.getValues();
var columns = [];
for (i in data) {
var row = data[i];
Logger.log("Got row", row);
for(var l=0; l<99; l++) {
var col = row[l];
// First empty column interrupts
if(!col) {
break;
}
columns.push(col);
}
}
return columns;
}
/**
* Duplicates a Google Apps doc
*
* #return a new document with a given name from the orignal
*/
function createDuplicateDocument(sourceId, name) {
var source = DocsList.getFileById(sourceId);
var newFile = source.makeCopy(name);
var targetFolder = DocsList.getFolderById(TARGET_FOLDER);
newFile.addToFolder(targetFolder);
return DocumentApp.openById(newFile.getId());
}
/**
* Search a paragraph in the document and replaces it with the generated text
*/
function replaceParagraph(doc, keyword, newText) {
var ps = doc.getParagraphs();
for(var i=0; i<ps.length; i++) {
var p = ps[i];
var text = p.getText();
if(text.indexOf(keyword) >= 0) {
p.setText(newText);
p.setBold(false);
}
}
}
/**
* Script entry point
*/
function generateCustomerContract() {
var data = SpreadsheetApp.openById(CUSTOMER_SPREADSHEET);
// XXX: Cannot be accessed when run in the script editor?
// WHYYYYYYYYY? Asking one number, too complex?
//var CUSTOMER_ID = Browser.inputBox("Enter customer number in the spreadsheet", Browser.Buttons.OK_CANCEL);
if(!CUSTOMER_ID) {
return;
}
// Fetch variable names
// they are column names in the spreadsheet
var sheet = data.getSheets()[0];
var columns = getRowAsArray(sheet, 1);
Logger.log("Processing columns:" + columns);
var customerData = getRowAsArray(sheet, CUSTOMER_ID);
Logger.log("Processing data:" + customerData);
// Assume first column holds the name of the customer
var customerName = customerData[0];
var target = createDuplicateDocument(SOURCE_TEMPLATE, customerName + " agreement");
Logger.log("Created new document:" + target.getId());
for(var i=0; i<columns.length; i++) {
var key = columns[i] + ":";
// We don't replace the whole text, but leave the template text as a label
var text = customerData[i] || ""; // No Javascript undefined
var value = key + " " + text;
replaceParagraph(target, key, value);
}
}
i have a jqxgrid with a dropdown column. Now, if in a row a dropdown item is selected, this dropdown item should be deactivated in all following rows.
So, first i have to get all rows:
var rows = $('#jqxgridpop').jqxGrid('getboundrows');
then get all cells containing the dropdown
for (var i = 0; i < rows.length; i++) {
var cell = $('#jqxgridpop').jqxGrid('getcell', i, 'languageddl');
and then, whit some magic, get the dropdowncontrol from the cell to disable the item. This is where i’m stuck..
Any hints or is this not possible?
Thanks in advance
I became an answer on the jqwidget forums, here the solution:
editor.bind('open', function (event) {
var rows = $('#jqxgridpop').jqxGrid('getboundrows');
for (var i = 0; i < rows.length; i++) {
var value = $('#jqxgridpop').jqxGrid('getcellvalue', i, "languageCode");
var item = editor.jqxDropDownList('getItemByValue', value);
editor.jqxDropDownList('disableItem', item);
};
});