Using encodeURIComponent in XPages - replace

In the W3Schools they give this example:
var uri = "http://w3schools.com/my test.asp?name=ståle&car=saab";
var res = encodeURIComponent(uri);
Which does what I want however, when I run it I get an error that encodeURIComponent is not implemented.
try{
var str:String = "Contracts and Leases";
var rtn = encodeURIComponent(str);
}catch(e){
println(e)
}
added the above to a button i get the not implemented error. Is there an equivalent I just need to replace the spaces with %20s.

Use java.net.URLEncoder.encode(stringToEncode, "utf-8") so in your case do this:
try{
var str:String = "Contracts and Leases";
var rtn = java.net.URLEncoder.encode(str, "utf-8");
}catch(e){
println(e)
}

Related

PowerBIClient does not have any value

I am trying to read powerbi report using powerbi SDk. I got correct access token (tested in postman). Same access token is passed for TokenCredentials. but not getting any value in _powerBIClient. it has no value. I'm using below code.
var functionCred = new Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential(_configuration[BotConfigurationEnum.FunctionClientId.GetDescription()], _configuration[BotConfigurationEnum.FunctionClientSecret.GetDescription()]);
var userAssertion = (!string.IsNullOrWhiteSpace(token)) ? new Microsoft.IdentityModel.Clients.ActiveDirectory.UserAssertion(token, "urn:ietf:params:oauth:grant-type:jwt-bearer") : null;
var context = new AuthenticationContext("https://login.microsoftonline.com/{tenentid}");
var res = await context.AcquireTokenAsync("https://analysis.windows.net/powerbi/api",
functionCred, userAssertion);
var tokenCredentials = new TokenCredentials(res.AccessToken, "Bearer");
var _powerBIClient = new PowerBIClient(new Uri("https://api.powerbi.com/"), tokenCredentials);
var pbiReport = _powerBIClient.Reports.GetReport(reportId);
there was small correction in my code.. I have removed '/' in new Uri and it worked. I know its silly..
var _powerBIClient = new PowerBIClient(new Uri("https://api.powerbi.com"), tokenCredentials);

Issues with textfinder and IF

I have a piece of code that was scrounged together from another code that is known working. What it does is searches a column using textfinder for a value, in this case, yesterday's date, if nothing is found, it should send an email.
function findAndSendMail() {
var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('FormResponses');
var ss2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('AlertDate');
var search = ss2.getRange("B2").getValue(); //cell has yesterday's date
var lastRow = ss.getLastRow();
var range = ss.getRange(1,4,lastRow); //define range for column D, column D contains dates
//find all occurrences of search key in column D and push range to array
var ranges = range.createTextFinder(search).findAll();
if (ranges!==null) {
var message = '';
}else {
var message = 'Test';
}
var emailRange = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("EmailGroup").getRange("A1");
var emailAddress = emailRange.getValues();
var subject = 'Subject';
var link = "blahblahblah"
if (message) {
MailApp.sendEmail(emailAddress, subject, '**This is an automated message**\n\n' + message + '\n\n**This is an automated message**\n' + link);
}
}
As you see, it should search column D, then, if it finds something, the message variable will be blank, else if it finds nothing, it will send an email to the email addresses chosen. I'm not sure how the results from a textfinder work with this and I think the way it is written is incorrect. Any help is appreciated, unfortunately, I cannot share the document in question as my company doesn't allow sharing outside of the domain. Thank you!
Try this:
You will need to update the sheet names I moved them to end of the line comments
function findAndSendMail() {
var ss=SpreadsheetApp.getActive()
var sh1=ss.getSheetByName('Sheet1');//FormResponses
var sh2=ss.getSheetByName('Sheet2');//AlertDate
var d1=new Date(sh2.getRange("B2").getValue()); //cell has yesterday's date
var d2=new Date(d1.getFullYear(),d1.getMonth(),d1.getDate()).valueOf();
var rg1 = sh1.getRange(1,4,sh1.getLastRow(),1);
var vA=rg1.getValues().map(function(r){
var dt=new Date(r[0]);
var dtv=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
return dtv;
});
if(vA.indexOf(d2)==-1) {
var message='test';
var emailAddress = ss.getSheetByName("Sheet3").getRange("A1").getValue();//EmailGroup
var subject = 'Subject';
var link = "blahblahblah"
}
if (message) {
MailApp.sendEmail(emailAddress, subject, '**This is an automated message**\n\n' + message + '\n\n**This is an automated message**\n' + link);
//SpreadsheetApp.getUi().alert('I found something');//just for testing
}
}
This version sends an email if yesterday is not found.
In answer to you last question:
function findAndSendMail() {
var ss=SpreadsheetApp.getActive()
var sh1=ss.getSheetByName('Sheet1');//FormResponses
var sh2=ss.getSheetByName('Sheet2');//AlertDate
var d1=new Date(sh2.getRange("B2").getValue()); //cell has yesterday's date
if(isDate(d1)) {
var d2=new Date(d1.getFullYear(),d1.getMonth(),d1.getDate()).valueOf();
var rg1 = sh1.getRange(1,4,sh1.getLastRow(),1);
var vA=rg1.getValues().map(function(r){
var dt=new Date(r[0]);
var dtv=new Date(dt.getFullYear(),dt.getMonth(),dt.getDate()).valueOf();
return dtv;
});
if(vA.indexOf(d2)==-1) {
var message='test';
var emailAddress = ss.getSheetByName("Sheet3").getRange("A1").getValue();//EmailGroup
var subject = 'Subject';
var link = "blahblahblah"
}
if (message) {
MailApp.sendEmail(emailAddress, subject, '**This is an automated message**\n\n' + message + '\n\n**This is an automated message**\n' + link);
//SpreadsheetApp.getUi().alert('I found something');//just for testing
}
}else{
SpreadsheetApp.getUi().alert('Data is sheet2!B2 is not a date')
return;
}
}
function isDate(date){
return(Object.prototype.toString.call(date) === '[object Date]');
}

Regex in Google App Script to enclose each word inside an Array inside quotes

For example I want to enclose each word in the following array inside quotes.
{seguridad=0, funcionalidad=1, instalaciones=si, observaciones=si,
areas=Pasillos, limpieza=no, pintura=tal vez}
Into:
{"seguridad"="0", "funcionalidad"="1", "instalaciones"="si",
"observaciones"="si", "areas"="Pasillos", "limpieza"="no",
"pintura"="tal vez"}
This is my unsuccesful script so far.
function Enclose() {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("1iXQxyL3URe1X1FgbZ76mEFAxLnxegyDzXOMF6WQ5Yqs"));
var sheet = doc.getSheetByName("json");
var sheet2 = doc.getSheetByName("tabla de frecuencias");
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var prelast = sheet.getRange("A1:A").getValues();
var last = prelast.filter(String).length;
var json = sheet2.getRange("B11").getValues();
var regExp = new RegExp("/[\w]+", "g");
/* var match = json.replace(regExp,""); */
var match = regExp.exec(match);
sheet2.getRange("C11").setValue("\"" + match + "\"");
}
You may try the following approach :
First you wrap all , and = by quotes "" by using the following regex:
/(\s*[,=]\s*)/
Then you replace the opening brackets separately using the following two regex:
/(\s*{)/gm
/(\s*})/gm
const str = `{seguridad=0, funcionalidad=1, instalaciones=si, observaciones=si, areas=Pasillos, limpieza=no, pintura=tal vez}`;
var result = str.replace(/(\s*[,=]\s*)/gm,`"$1"`);
result=result.replace(/(\s*{)/gm,`$1"`);
result=result.replace(/(\s*})/gm,`"$1`);
console.log(result);
How about this sample?
Sample script :
var json = "{seguridad=0, funcionalidad=1, instalaciones=si, observaciones=si, areas=Pasillos, limpieza=no, pintura=tal vez}";
var res = json.replace(/(\d+|[a-zA-Z]+)=(\d+|[a-zA-Z\s]+)/g, "\"$1\"=\"$2\"");
Logger.log(res)
Result :
var json = "{seguridad=0, funcionalidad=1, instalaciones=si, observaciones=si, areas=Pasillos, limpieza=no, pintura=tal vez}";
var res = json.replace(/(\d+|[a-zA-Z]+)=(\d+|[a-zA-Z\s]+)/g, "\"$1\"=\"$2\"");
console.log(res)
When this is reflected to your script, the modified script is as follows.
Modified script :
function Enclose() {
var doc = SpreadsheetApp.openById(SCRIPT_PROP.getProperty("1iXQxyL3URe1X1FgbZ76mEFAxLnxegyDzXOMF6WQ5Yqs"));
var sheet = doc.getSheetByName("json");
var sheet2 = doc.getSheetByName("tabla de frecuencias");
var rows = sheet.getDataRange();
var numRows = rows.getNumRows();
var values = rows.getValues();
var prelast = sheet.getRange("A1:A").getValues();
var last = prelast.filter(String).length;
var json = sheet2.getRange("B11").getValue();
// var regExp = new RegExp("/[\w]+", "g");
// /* var match = json.replace(regExp,""); */
// var match = regExp.exec(match);
match = json.replace(/(\d+|[a-zA-Z]+)=(\d+|[a-zA-Z\s]+)/g, "\"$1\"=\"$2\"");
sheet2.getRange("C11").setValue("\"" + match + "\"");
}

AS3 - Replace portion of string with a variable string

Trying to replace a portion of a string with a "-" if it matches a string variable in AS3.
var re:RegExp = new RegExp(imageArray[j][1],"gi");
trace(imageArray[jTemp][2].replace(re,"-"));
imageArray[jTemp][2] is a string
imageArray[j][1] is a string as well
I'm not getting the result I expect. I would like trace above to return 'permanentContainer-' Here are the traces for the above variables
permanentContainer-temporaryContainer-
temporaryContainer
var str:String = "permanentContainer-temporaryContainer-"
var pattern:RegExp = /-[(a-z)]+-/i;
var re:RegExp = new RegExp( "-^-$", "i");
trace( str.replace(pattern,"-"));
// traces
// permanentConta1iner-
Here's what ended up working for me:
var str:String=imageArray[jTemp][2];
var pattern:String=imageArray[j][1];
var regex:RegExp=new RegExp(pattern,"ig");
imageArray[jTemp][2]=str.replace(regex,"-");

RegExp for filtering log messages

I need to filter log messages based on the log level and a text appearing in the log message. These messages are in the following form:
12/23/2009 17:33:26.379 [INFO] TMSNG.Main Channelset configured with url [http://172.16.34.4:8080/tms-flux/messagebroker/streamingamf]
12/23/2009 17:33:26.380 [DEBUG] org.springextensions.actionscript.core.command.CompositeCommand Executing composite command '[object CompositeCommand]' in sequence
I already have the code below that creates 2 regular expressions (one for the level and one for the text) but I was wondering how I could combine these into one. I tried several combinations, but since my regexp skills are non-existing I couldn't get this to work.
Any hints?
Code:
private function filterLogMessage(item:Object):Boolean {
var logMessage:String = String(item);
var levelFilter:String = getLevelFilter();
var levelRegExp:RegExp = new RegExp(levelFilter, "");
var textFilter:String = StringUtils.trim(filterTextInput.text);
var textRegExp:RegExp = new RegExp(textFilter, "");
var match:Boolean = (levelRegExp.test(logMessage) && textRegExp.test(logMessage));
return match;
}
private function getLevelFilter():String {
var result:String = "";
var selectedLevel:String = levelComboBox.selectedLabel;
switch (selectedLevel) {
case "DEBUG":
//result = "\\[(DEBUG|INFO|WARN|ERROR|FATAL)\\]";
break;
case "INFO":
result = "\\[(INFO|WARN|ERROR|FATAL)\\]";
break;
case "WARN":
result = "\\[(WARN|ERROR|FATAL)\\]";
break;
case "ERROR":
result = "\\[(ERROR|FATAL)\\]";
break;
case "FATAL":
result = "\\[(FATAL)\\]";
break;
}
return result;
}
The following should do the trick (never worked with flex before, so not entirely sure whether syntax is correct ;-) )
private function filterLogMessage(item:Object):Boolean {
var logMessage:String = String(item);
var levelFilter:String = getLevelFilter();
var textFilter:String = StringUtils.trim(filterTextInput.text);
var filterRegExp:RegExp = new RegExp(levelFilter + ".*" + textFilter, "");
var match:Boolean = (filterRegExp.test(logMessage));
return match;
}