const textEditor = vscode.window.activeTextEditor;
if (!textEditor) {
return; // No open text editor
}
for(var i=0;i<textEditor.document.lineCount;i++)
{
var textLine = textEditor.document.lineAt(i);
for(var j=textLine.range.start.character; j<=textLine.range.end.character; j++)
{
var startposition = new vscode.Position(i,j);
var endposition = new vscode.Position(i,j+1);
var range = new vscode.Range(startposition,endposition);
var text = textEditor.document.getText(range);
if(text === "\'"){
textEditor.edit(editBuilder => editBuilder.replace(range,"\""));
}
}
}
I need to replace all the single quotes with double quotes. But what happens is the
textEditor.edit(editBuilder => editBuilder.replace(range,"\"")); only replaces the 1st occurence. I need to replace all of the occurence in the document.
let doc = vscode.window.activeTextEditor.document;
let editor = vscode.window.activeTextEditor;
var j=0;
editor.edit(editBuilder => {
for(var i=0;i<doc.lineCount;i++)
{
var line = doc.lineAt(i);
for(j=0;j<line.range.end.character;j++)
{
var startposition = new vscode.Position(i,j);
var endingposition = new vscode.Position(i,j+1);
var range = new vscode.Range(startposition,endingposition);
var charac = editor.document.getText(range);
if(charac == '\'')
{
editBuilder.replace(range,'\"');
console.log(startposition);
}
}
}
})
`
Related
I am learning Javascript and this is my first time working with Google Sheets Apps Script. What I am doing is taking a large JSON file and importing it into my sheet. After that I am populating a few hundred properties based on the key:value found in the JSON.
This is how it kinda works right now:
Go to first column and first row of my sheet.
Get the name (property name).
Search the JSON for the key and then grab the value.
Update a neighbor cell with the value found in the JSON.
Right now it all works the only issue is it seems to be pretty slow. It takes about .5-1 second per lookup and when I have 200+ properties it just seems slow. This might just be a limitation or it might be my logic.
My sheet can be found here: https://docs.google.com/spreadsheets/d/1tt3eh1RjL_CbUIaPzj10DbocgyDC0iNRIba2B4YTGgg/edit#gid=0
My function that does everything:
function parse() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var range = sheet.getRange(2,1);
var range1 = sheet.getRange("A2");
var cell = range.getCell(1, 1);
var event_line = cell.getValue();
var tmp = event_line.split(". ");
var col_number = tmp[0];
var event_name = tmp[1];
event_json = get_json_from_cell(col_number);
const obj = JSON.parse(event_json);
var traits = obj.context.traits;
var properties = obj.properties;
//Get the range for the section where properties are
var traits_range = sheet.getRange("contextTraits");
var allprop = sheet.getRange("testAll");
var alllen = allprop.getNumRows();
var length = traits_range.getNumRows();
for (var i = 1; i < length; i++) {
var cell = traits_range.getCell(i, 1);
var req = traits_range.getCell(i, 4).getValue();
var trait = cell.getValue();
var result = traits[trait];
var result_cell = traits_range.getCell(i, 3);
if (result == undefined) {
if (req == "y"){
result = "MISSING REQ";
result_cell.setBackground("red");
} else {
result = "MISSING";
result_cell.setBackground("green");
}
} else {
result_cell.setBackground("blue");
}
result_cell.setValue(result);
Logger.log(result);
}
for (var i = 1; i < alllen; i++) {
var cell = allprop.getCell(i,1);
var req = allprop.getCell(i, 4).getValue();
var prop = cell.getValue();
var result = properties[prop];
var result_cell = allprop.getCell(i, 3);
if (result == undefined) {
if (req == "y"){
result = "MISSING REQ";
result_cell.setBackground("red");
} else {
result = "MISSING";
result_cell.setBackground("green");
}
} else {
result_cell.setBackground("blue");
}
result_cell.setValue(result);
}
Logger.log(result);
}
i have a xml string that i will replace all values of specific tags using javascript,
and this is the code :
function replaceDomainName (xmlPayload,domainId)
{
var oldDomain = '<DOMAIN_NAME>OOO';
var oldDomain2 = '<DomainName>OOO';
var newDomain = '<DOMAIN_NAME>'+domainId ;
var newDomain2 = '<DomainName>'+domainId ;
var xmlString = xmlPayload.toString();
var x = xmlString.replace(/oldDomain/g,newDomain)
x = x.replace(/oldDomain2/g,newDomain2)
console.log(x);
return x ;
}
when I try to invoke the function with the following XML it throws error
<TransmissionHeader xmlns:tran="http://xmlns.oracle.com/apps/otm/TransmissionService" xmlns="">
<Version>20b</Version>
<TransmissionCreateDt>
<GLogDate>20200819124057</GLogDate>
<TZId>UTC</TZId>
<TZOffset>+00:00</TZOffset>
</TransmissionCreateDt>
<TransactionCount>1</TransactionCount>
<SenderHostName>https://xxx</SenderHostName>
<SenderSystemID>https:xxx</SenderSystemID>
<UserName>OOO</UserName>
<SenderTransmissionNo>404836</SenderTransmissionNo>
<ReferenceTransmissionNo>0</ReferenceTransmissionNo>
<GLogXMLElementName>PlannedShipment</GLogXMLElementName>
<NotifyInfo>
<ContactGid>
<Gid>
<DomainName>OOO</DomainName>
<Xid>SYS</Xid>
</Gid>
</ContactGid>
<ExternalSystemGid>
<Gid>
<DOMAIN_NAME>OOO</DOMAIN_NAME>
<Xid>IOT_SYSTEM</Xid>
</Gid>
</ExternalSystemGid>
</NotifyInfo>
</TransmissionHeader>
error: unknown: Unexpected token (14:23)
x.replace(/<DOMAIN_NAME>OOO/g,'<DomainName>'+domainId)
use this
While you can get a lot done with Regex, it can get really complicated when parsing XML.
See this example of using DOMParser and XMLSerializer:
https://jsfiddle.net/o1cenvs3/
const XML = `<TransmissionHeader xmlns:tran="http://xmlns.oracle.com/apps/otm/TransmissionService" xmlns="">
<Version>20b</Version>
<TransmissionCreateDt>
<GLogDate>20200819124057</GLogDate>
<TZId>UTC</TZId>
<TZOffset>+00:00</TZOffset>
</TransmissionCreateDt>
<TransactionCount>1</TransactionCount>
<SenderHostName>https://xxx</SenderHostName>
<SenderSystemID>https:xxx</SenderSystemID>
<UserName>OOO</UserName>
<SenderTransmissionNo>404836</SenderTransmissionNo>
<ReferenceTransmissionNo>0</ReferenceTransmissionNo>
<GLogXMLElementName>PlannedShipment</GLogXMLElementName>
<NotifyInfo>
<ContactGid>
<Gid>
<DomainName>OOO</DomainName>
<Xid>SYS</Xid>
</Gid>
</ContactGid>
<ExternalSystemGid>
<Gid>
<DOMAIN_NAME>OOO</DOMAIN_NAME>
<Xid>IOT_SYSTEM</Xid>
</Gid>
</ExternalSystemGid>
</NotifyInfo>
</TransmissionHeader>`;
if(typeof(String.prototype.trim) === "undefined")
{
String.prototype.trim = function()
{
return String(this).replace(/^\s+|\s+$/g, '');
};
}
function replaceDomainName (xmlPayload, oldValue, newValue)
{
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(xmlPayload,"text/xml");
for(let tagName of ['DOMAIN_NAME', 'DomainName']) {
const instances = xmlDoc.getElementsByTagName(tagName);
for (let instance of instances) {
if(instance.innerHTML.trim() == oldValue )
instance.innerHTML = newValue;
}
};
const s = new XMLSerializer();
const d = document;
const result = s.serializeToString(xmlDoc);
return result;
}
const resultXML = replaceDomainName(XML, 'OOO', 'new.com');
console.log('resultXML', resultXML);
const textarea = document.createElement("textarea");
textarea.innerHTML = resultXML;
textarea.cols = 80;
textarea.rows = 24;
document.body.appendChild(textarea);
I am trying to make a script to automate deleting duplicate data based on column A. This is the current script I am using and it works.
// This scripts works but deleting new data instead of old data
function removeDuplicates() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName(sheetName);
var vA = sh.getDataRange().getValues();
var hA = vA[0];
var hObj = {};
hA.forEach(function(e, i) {
hObj[e] = i;
});
var uA = [];
var d = 0;
for (var i = 0; i <= vA.length; i++) {
if (uA.indexOf(vA[i][hObj['key']]) == -1) {
uA.push(vA[i][hObj['key']]);
} else {
//sh.deleteRow(i + 1 - d++);
sh.deleteRow((parseInt(i)+1) - d);
d++;
}
}
};
But this one is deleting the newly added row, what I want to achieve is it should delete the old duplicate row instead. How can I do that?
In else part instead of using i which represent your current row, use the indexOf the row you want to delete. Delete it first and then push the new one into array
// This scripts works but deleting new data instead of old data
function removeDuplicates() {
var sheetName = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getName();
var ss = SpreadsheetApp.getActive();
var sh = ss.getSheetByName(sheetName);
var vA = sh.getDataRange().getValues();
var hA = vA[0];
var hObj = {};
hA.forEach(function(e, i) {
hObj[e] = i;
});
var uA = [];
var d = 0;
for (var i = 0; i <= vA.length; i++) {
if (uA.indexOf(vA[i][hObj['key']]) == -1) {
uA.push(vA[i][hObj['key']]);
} else {
//sh.deleteRow(i + 1 - d++);
let j = uA.indexOf(vA[i][hObj['key']]);
sh.deleteRow((parseInt(j)+1) - d);
d++;
uA.push(vA[i][hObj['key']]);
}
}
};
I got a csv-reader directive and let's user upload a csv file. I noticed that when I upload a file with spaces between words for example:
abc
abc
abc
abc
abc
this gets shown. I want to delete all the blank lines Not sure what to do.
var reader = new FileReader();
reader.onload = function(e) {
var contents = e.target.result;
var rows = contents.split('\n');
// Check if the last row is empty. This works
if(rows[rows.length-1] ===''){
rows.pop()
}
}
// this doesn't work for some reason. It doesn't detect the '' in the middle of the arrays.
for( var i=rows.length-1;i>0;i--){
if(rows[i] === ''){
rows.splice(i,1)
}
}
Try using Array.prototype.filter()
var rows = contents.split('\n').filter(function(str){
return str;
});
From what you have shown it looks like you want to check if each item in the csvModel is an empty string, rather than newValue
Something like:
for( var i=0 ;i< $scope.csvModel.length; i++){
if (csvModel[i] == "") {
$scope.csvModel.splice(i,1);
}
}
var text = [];
var target = $event.target || $event.srcElement;
var files = target.files;
if(Constants.validateHeaderAndRecordLengthFlag){
if(!this._fileUtil.isCSVFile(files[0])){
alert("Please import valid .csv file.");
this.fileReset();
}
}
var input = $event.target;
var reader = new FileReader();
reader.readAsText(input.files[0], 'UTF-8');
reader.onload = (data) => {
let csvData = reader.result;
let csvRecordsArray = csvData.split(/\r\n|\n/);
if (csvRecordsArray[csvRecordsArray.length - 1] === '') {
csvRecordsArray.pop();
}
var headerLength = -1;
if(Constants.isHeaderPresentFlag){
let headersRow = this._fileUtil.getHeaderArray(csvRecordsArray, Constants.tokenDelimeter);
headerLength = headersRow.length;
}
this.csvRecords = this._fileUtil.getDataRecordsArrayFromCSVFile(csvRecordsArray,
headerLength, Constants.validateHeaderAndRecordLengthFlag, Constants.tokenDelimeter);
if(this.csvRecords===null){
this.csvRecords=[];
}
else if(this.csvRecords!==null) {
if ((JSON.stringify(this.csvRecords[0])) === (JSON.stringify(this.csvFormate))) {
alert("format matches");
this.displayCsvContent = true;
for (let i = 0; i < this.csvRecords.length; i++) {
if (i !== 0) {
this.csvRecords[i].push(this.recordInsertedFlag);
}
}
}
else {
alert("format not matches");
}
}
if(this.csvRecords == null){
this.displayCsvContent=false;
//If control reached here it means csv file contains error, reset file.
this.fileReset();
}
};
reader.onerror = function () {
alert('Unable to read ' + input.files[0]);
};
I need to process a text file one line at a time. In BASIC, I could use a readline command, which would read until the next carriage return/line feed.
How would you write a function for looping through a file one line at a time in AIR?
var myDir = air.File.documentsDirectory;
var myFile = myDir.resolvePath("Test.txt");
if (myFile.exists) {
var myFileStream = new air.FileStream();
myFileStream.open(myFile, air.FileMode.READ);
var myByteArray = new air.ByteArray();
myFileStream.readBytes(myByteArray,0,myFileStream.bytesAvailable);
air.Introspector.Console.log(myByteArray.length);
} else {
alert ('File not found.');
}
var LineNumber;
var ItemCode;
var OrderCode;
var Qty;
var myDir = air.File.documentsDirectory;
var myFile = myDir.resolvePath("Test.txt");
if (myFile.exists) {
var myFileStream = new air.FileStream();
myFileStream.open(myFile, air.FileMode.READ);
var myData = new air.ByteArray();
myFileStream.readBytes(myData,0,myFileStream.bytesAvailable);
var str = myData.toString();
var Pos = 0;
var Tab = 0;
var CRLF = 0;
EOL = str.indexOf("\r",Pos);
while (EOL > 0) {
Tab = str.indexOf('\t',Pos);
LineNumber = str.substring(Pos,Tab);
Pos = Tab + 1;
Tab = str.indexOf('\t',Pos);
ItemCode = str.substring(Pos,Tab);
Pos = Tab + 1;
Tab = str.indexOf('\t',Pos);
OrderCode = str.substring(Pos,Tab);
Pos = Tab + 1;
CRLF = str.indexOf('\r',Pos);
Qty = str.substring(Pos,CRLF);
Pos = EOL+1;
EOL = str.indexOf("\r",Pos);
}
} else {
alert ('File not found.');
}