Show cell data within listFilesInFolder Function - java

I have this formula, which successfully lists all of my files in a folder. Awesome. But, can I also, within this script list some specific cell data from each file?
function listFilesInFolder() {
var folder = DocsList.getFolder("1- Summaries");
var contents = folder.getFiles();
var file;
var data;
var sheet = SpreadsheetApp.getActiveSheet();
sheet.clear();
sheet.appendRow(["Name", "Date", "Size", "URL", "Download", "Description", "Type"]);
for (var i = 0; i < contents.length; i++) {
file = contents[i];
if (file.getFileType() == "SPREADSHEET") {
continue;
}
data = [
file.getName(),
file.getDateCreated(),
file.getValue(B10), **(THIS IS WHERE I WOULD LIKE TO GET DATA, but it does not work)**
file.getUrl(),
"https://docs.google.com/a/acme.com/spreadsheet/ccc?key=" + file.getId(),
file.getDescription(),
"audio/mp3"
]
sheet.appendRow(data);

You can read from the spreadsheet, yes.
In the place where if (file.getFileType()... is, put this:
var cellValue;
if (file.getFileType() === "SPREADSHEET") {
cellValue = SpreadsheetApp.openById(file.getId()).getSheetByName("NameOfSheet")
.getRange("B10").getValue();
} else {
cellValue = null; // specify some default value here!
}
...
Then in your data array:
data = [
file.getName(),
file.getDateCreated(),
cellValue,
...

Related

Cant fill json array to array list android development

I was trying to send json array from my web into an arraylist in a class with volley libarary
Here is array that i want to be filled
i want to replace dummy data in function getBestSelling() with data from web
Filename = DummyDataSource.kt (it is just plain kotlin class)
fun getBestSelling(): Observable<ArrayList<ProductEntity>> {
val dummy1 = ProductEntity(name = "Bell Pepper Red", description = "1kg, Priceg",
price = 20000,
picture = R.drawable.iv_pepper_red,
id = 5
)
val dummy2 = ProductEntity(name = "Beef bone", description = "1kg, Priceg",
price = 25000,
picture = R.drawable.iv_beef_bone,
id = 6
)
val dummy3 = ProductEntity(name = "Boiler Chicken", description = "1kg, Priceg",
price = 15000,
picture = R.drawable.iv_boiler_chicken,
id = 7
)
val dummy4 = ProductEntity(name = "Ginger", description = "250gm, Priceg",
price = 22000,
picture = R.drawable.iv_ginger,
id = 4
)
val data = listOf(dummy1, dummy2, dummy3, dummy4)
return Observable.just(ArrayList(data))
}
Here are what i do to get array filled
fun getBestSelling(): Observable<ArrayList<ProductEntity>> {
var url:String="http:// 192.168.56.1/toko-online/mobile/pro_kategori.php"
var rq : RequestQueue = Volley.newRequestQueue(this)
var data = ArrayList<ProductEntity>()
var js = JsonArrayRequest(Request.Method.GET,url,null, Response.Listener{ response ->
for (x in 0..response.length()-1){
data.add(ProductEntity(response.getJSONObject(x).getInt("id"),
response.getJSONObject(x).getInt("id"),response.getJSONObject(x).getString("name"),
response.getJSONObject(x).getString("url"),response.getJSONObject(x).getString("description"),
response.getJSONObject(x).getInt("price"),response.getJSONObject(x).getInt("stock"),
response.getJSONObject(x).getInt("category_id")))
}
}, Response.ErrorListener { error ->
Toast.makeText(this,error.message,Toast.LENGTH_LONG).show()
})
rq.add(js)
return Observable.just(data)
}
The error come from line " var rq : RequestQueue = Volley.newRequestQueue(this)"
it says
"Type mismatch: inferred type is DummyDataSource but Context! was expected"
so i copied this code
fun getdata(): Observable<ArrayList<ProductEntity>> {
var url:String="http:// 192.168.56.1/toko-online/mobile/pro_kategori.php"
var rq : RequestQueue = Volley.newRequestQueue(this)
var data = ArrayList<ProductEntity>()
var js = JsonArrayRequest(Request.Method.GET,url,null, Response.Listener{ response ->
for (x in 0..response.length()-1){
data.add(ProductEntity(response.getJSONObject(x).getInt("id"),
response.getJSONObject(x).getInt("id"),response.getJSONObject(x).getString("name"),
response.getJSONObject(x).getString("url"),response.getJSONObject(x).getString("description"),
response.getJSONObject(x).getInt("price"),response.getJSONObject(x).getInt("stock"),
response.getJSONObject(x).getInt("category_id")))
}
}, Response.ErrorListener { error ->
Toast.makeText(this,error.message,Toast.LENGTH_LONG).show()
})
rq.add(js)
return Observable.just(data)
}
into oncreate in the main activity. But because of that i cant fill array within getBestSelling() in DummyDataSource.kt because the function getdata() only return data to oncreate
Is there any way to make data go to getBestSelling() in DummyDataSource.kt ?
Move your function back out of onCreate and replace "this" with a context reference (requreContext() or create a Context var in onCreate to reference)

StringTokenizer is not getting right value after delimiter

I'm trying to get the string from ARCHIVE_FILE_EXTENSION_FILTER but somehow it is not taking the first value and returning NULL
Below is the properties info
#indicate any file extensions to filter by - must be comma-delimited. Enter 'none' to get all files
Text.FileArchiver.INV_ARCHIVE_FILE_EXTENSION_FILTER=done , proc
May I know why it's not working the value and any issue with my code
String extension = env.getProperty(trimIni(ARCHIVE_FILE_EXTENSION_FILTER));
if (Objects.nonNull(extension) && !NONE.equalsIgnoreCase(extension)) {
StringTokenizer token = new StringTokenizer(extension, ",");
int i = 0;
String[] tmpExtensions = {};
if (token.countTokens() > 0) {
tmpExtensions = new String[token.countTokens()];
}
while (token.hasMoreTokens()) {
tmpExtensions[i] = token.nextToken();
}
extensions = tmpExtensions;
}

Set custom column width size in google sheets

I'm using this Java code to generate Google sheets data from Java application.
List < RowData > rowDataValues = new ArrayList < > ();
List < CellData > headerValues = new ArrayList < > ();
headerValues.add(new CellData().setNote("ID")
.setUserEnteredValue(new ExtendedValue()
.setStringValue("#")).setUserEnteredFormat(myFormat));
.setStringValue("Environment")).setUserEnteredFormat(myFormat));
.........
headerValues.add(new CellData()
.setUserEnteredValue(new ExtendedValue()
.setStringValue("Name")).setUserEnteredFormat(myFormat));
RowData setHeaderValues = new RowData();
setHeaderValues.setValues(headerValues);
rowDataValues.add(setHeaderValues);
requests.add(new Request()
.setUpdateCells(new UpdateCellsRequest()
.setStart(new GridCoordinate()
.setSheetId(randomSheetId)
.setRowIndex(0)
.setColumnIndex(0))
.setRows(rowDataValues)
.setFields("*")));
BatchUpdateSpreadsheetRequest body = new BatchUpdateSpreadsheetRequest().setRequests(requests);
BatchUpdateSpreadsheetResponse response = service.spreadsheets().batchUpdate(spreadsheetId, body).execute();
How I can set custom width for each column?
Update:
This is what i've tried so far :
new UpdateDimensionPropertiesRequest().setRange(
new DimensionRange()
.setDimension("COLUMNS")
.setStartIndex(0).setEndIndex(1)
)
.setProperties(new DimensionProperties().setPixelSize(400)).setFields("pixelSize"));
You need to create UpdateDimensionPropertiesRequest. In your case you can use this sample code, which increases the size of first column (startIndex = 0, endIndex = 1) .
requests.add(new Request().setUpdateDimensionProperties(
new UpdateDimensionPropertiesRequest()
.setRange(
new DimensionRange()
.setSheetId(randomSheetId)
.setDimension("COLUMNS")
.setStartIndex(0)
.setEndIndex(1)
)
.setProperties(new DimensionProperties().setPixelSize(400)).setFields("pixelSize"))));
In here i used setDimension("COLUMNS") to change column(s) width, it is possible to change row(s) height by using setDimension("ROWS").
Additional problem from #PeterPenzov 's comment :
I get "Invalid requests.updateDimensionProperties: No grid with id: 0",
You'll get this error when your sheetId is not set properly.
From API v4 documentation SheetId is ;
Individual sheets in a spreadsheet have titles (which must be unique) and IDs. The sheetId is used frequently in the Sheets API to specify which sheet is being read or updated
So you need to set sheetId of DimensionRange Object. In your case you need to use your sheetId as randomSheetId(i've updated the code above).
Spreadsheet spreadsheet = service.spreadsheets().get(spreadsheetId).execute();
spreadsheet.getSheets().stream()
.map(s->s.getProperties().getSheetId())
.forEach(System.out::println);
Please take a look into dev documentation:
{
"requests": [
{
"updateDimensionProperties": {
"range": {
"sheetId": sheetId,
"dimension": "COLUMNS",
"startIndex": 0,
"endIndex": 1
},
"properties": {
"pixelSize": 160
},
"fields": "pixelSize"
}
}
]
}
Request body from the example for column width could be translated into the next Java code:
public void updateFirstColumnWidth(Sheets sheetService, String sheetId) throws IOException {
final Spreadsheet spreadsheet = sheetService.spreadsheets()
.get(sheetId)
.execute();
final var sheets = spreadsheet.getSheets();
final var sheet = sheets.get(0); // get your specific sheet
final int sheetUuid = sheet.getProperties().getSheetId();
final var batchRequest = new BatchUpdateSpreadsheetRequest();
List<Request> requests = List.of(getColumnWidthRequest(sheetUuid, 160));
batchRequest.setRequests(requests);
final BatchUpdateSpreadsheetResponse response = sheetService.spreadsheets()
.batchUpdate(sheetId, batchRequest)
.execute();
}
private Request getColumnWidthRequest(int sheetUuid, int width) {
return new Request()
.setUpdateDimensionProperties(
new UpdateDimensionPropertiesRequest()
.setRange(
new DimensionRange()
.setSheetId(sheetUuid)
.setDimension("COLUMNS")
.setStartIndex(0)
.setEndIndex(1)
)
.setProperties(new DimensionProperties().setPixelSize(width))
.setFields("pixelSize")
);
}

Whats the best way to read multiline input format to one record in spark?

Below is the input file(csv) looks like:
Carrier_create_date,Message,REF_SHEET_CREATEDATE,7/1/2008
Carrier_create_time,Message,REF_SHEET_CREATETIME,8:53:57
Carrier_campaign,Analog,REF_SHEET_CAMPAIGN,25
Carrier_run_no,Analog,REF_SHEET_RUNNO,7
Below is the list of columns each rows has:
(Carrier_create_date, Carrier_create_time, Carrier_campaign, Carrier_run_no)
Desired output as dataframe:
7/1/2008,8:53:57,25,7
Basically the input file has column name and value on each rows.
What I have tried so far is:
import org.apache.log4j.{Level, Logger}
import org.apache.spark.sql.hive.HiveContext
import org.apache.spark.{SparkContext, SparkConf}
object coater4CR {
// Define the application Name
val AppName: String = "coater4CR"
// Set the logging level.ERROR)
Logger.getLogger("org.apache").setLevel(Level.ERROR)
def main(args: Array[String]): Unit = {
// define the input parmeters
val input_file = "/Users/gangadharkadam/myapps/NlrPraxair/src/main/resources/NLR_Praxair›2008›3QTR2008›Coater_4›C025007.csv"
// Create the Spark configuration and the spark context
println("Initializing the Spark Context...")
val conf = new SparkConf().setAppName(AppName).setMaster("local")
// Define the Spark Context
val sc = new SparkContext(conf)
// Read the csv file
val inputRDD = sc.wholeTextFiles(input_file)
.flatMap(x => x._2.split(" "))
.map(x => {
val rowData = x.split("\n")
var Carrier_create_date: String = ""
var Carrier_create_time: String = ""
var Carrier_campaign: String = ""
var Carrier_run_no: String = ""
for (data <- rowData) {
if (data.trim().startsWith("Carrier_create_date")) {
Carrier_create_date = data.split(",")(3)
} else if (data.trim().startsWith("Carrier_create_time")) {
Carrier_create_time = data.split(",")(3)
} else if (data.trim().startsWith("Carrier_campaign")) {
Carrier_campaign = data.split(",")(3)
} else if (data.trim().startsWith("Carrier_run_no")) {
Carrier_run_no = data.split(",")(3)
}
}
(Carrier_create_date, Carrier_create_time, Carrier_campaign, Carrier_run_no)
}).foreach(println)
}
}
issues with the above code
when I run the above code I am getting an empty list as below
(,,,)
when I change
Carrier_campaign = data.split(",")(3)
to
Carrier_campaign = data.split(",")(2)
I am getting the below output which is somewhat closer
(REF_SHEET_CREATEDATE,REF_SHEET_CREATETIME,REF_SHEET_CAMPAIGN,REF_SHEET_RUNNO)
(,,,)
some how the above code is not able to pick the last column position from the data row but is working for column positions 0,1,2.
So my questions are-
whats wrong with the above code
whats the efficient approach to read this multiline input and load it in tabular format to database
Appreciate any help/pointers on this. Thanks.

Dart Parse JSON into Table

I'm trying to figure out how to parse a JSON feed into a table in Dart. I'm not sure if I should use a Map but if I do, I'm not sure how to approach extracting data. I want to have one cell to hold the assetID, then another for domain name, and another for IP address. Please let me know if you need more information.
Dart:
void loadData()
{
var url = "http://localhost:8080/***selectAll";
//call the web server asynchronously
var request = HttpRequest.getString(url).then(onDataLoaded);
}
void onDataLoaded(String response)
{
TableElement table = querySelector("#domainTableSelector");
//table.children.add();
var jsonString = response;
// print(jsonString);
List<String> list = new List<String>();
list.add(jsonString);
for (var x = 0; x < list.length; x++)
{
//create new table row
TableRowElement row = table.insertRow(x+1);
TableCellElement cell = row.insertCell(x);
cell.text = list.toString();
// print(list);
}
// Iterator itr= list.iterator();
//
// print("Displaying List Elements,");
//
// while(itr.hasNext())
// {
// print(itr.next());
// }
}
JSON
[{"serviceResponseValue":[{"assetId":"8a41250446b89b5f0146b04d49910023","oplock":0,"longitude":115.86,"domainName":"free-aus-trip.au","latitude":-31.95,"ipAddress":"6.0.0.6"},{"assetId":"8a49859246918966014691b1aac9000c","oplock":0,"longitude":-65.30,"domainName":null,"latitude":-24.18,"ipAddress":"4.0.0.4"},{"assetId":"8a49859246876566014691b1437512e4","oplock":0,"longitude":77.60,"domainName":"allmovies.cn","latitude":12.97,"ipAddress":"14.0.0.14"},{"assetId":"8a49850446b04b5f0146b04d49910000","oplock":0,"longitude":112.47,"domainName":"getrichez.cn","latitude":32.98,"ipAddress":"5.0.0.5"},{"assetId":"8a498592469189660146919b7a210006","oplock":0,"longitude":-37.61,"domainName":"googles.com","latitude":55.75,"ipAddress":null},{"assetId":"8a42250876b89b5f0876b04d49910763","oplock":0,"longitude":-68.90,"domainName":"lolcatzfun.net","latitude":-22.48,"ipAddress":"8.0.0.8"},{"assetId":"8a498592469189660146919f8d700008","oplock":0,"longitude":113.50,"domainName":"ccn.com","latitude":52.03,"ipAddress":null},{"assetId":"8a45250446b89b5f0876b04d49910187","oplock":0,"longitude":115.84,"domainName":"free-aus-trip.au","latitude":-31.86,"ipAddress":"7.0.0.7"},{"assetId":"8a49859246918966014691aeda76000a","oplock":0,"longitude":3.38,"domainName":"cashnow.net","latitude":6.52,"ipAddress":"2.0.0.2"},{"assetId":"8a49859246918966014691ae19df0009","oplock":0,"longitude":7.48,"domainName":"free-money.tv","latitude":9.07,"ipAddress":"222.222.222.222"},{"assetId":"8a498592469189660146919e09900007","oplock":0,"longitude":30.34,"domainName":"facebok.com","latitude":59.93,"ipAddress":"111.111.111.222"},{"assetId":"8a49859246918966014691b14375000b","oplock":0,"longitude":116.41,"domainName":null,"latitude":39.90,"ipAddress":"0.0.0.111"}],"messages":{"messages":[]}}]
To work with JSON, you have in dart a great thing : dart:convert => JSON
here some example of use:
var encoded = JSON.encode([1, 2, { "a": null }]);
var decoded = JSON.decode('["foo", { "bar": 499 }]');
I have done some thing but i'm not sure that is fit perfectly with your need
import 'dart:html';
import 'dart:convert';
void loadData()
{
var url = "http://localhost:8080/***selectAll";
//call the web server asynchronously
var request = HttpRequest.getString(url).then(onDataLoaded);
}
void onDataLoaded(String response)
{
TableElement table = querySelector("#domainTableSelector");
//table.children.add();
var jsonString = response;
// print(jsonString);
var jsonObject = JSON.decode(jsonString);
for (var x = 0; x < jsonObject.length; x++)
{
//create new table row
TableRowElement row = table.insertRow(x+1);
for (var d in jsonObject[x]["serviceResponseValue"]) {
TableCellElement cell = row.insertCell(x);
cell.text = d["assetId"];
cell = row.insertCell(x);
cell.text = d["domainName"];
cell = row.insertCell(x);
cell.text = d["ipAddress"];
print(d["assetId"]);
print(d["domainName"]);
print(d["ipAddress"]);
}
// print(list);
}
}
You parse JSON into a Dart data structure using
import 'dart:convert' show JSON;
var decoded = JSON.decode(jsonString);
see also How to handle JSON in Dart (Alexandres answer)
decoded is then a Dart data structure (lists, maps, values) that you can iterate over or investigate in the debugger. If you need further assistance please add a comment.

Categories

Resources