Microsoft JScript Compilation error - Un-terminated String Constant - javascript

var newpath= workingDir + "Nodelist_" + ".txt";
iStream=fso.OpenTextFile(newpath, 1, false);
var ss;
ss="";
var sLine = "";
while(!iStream.AtEndOfStream) {
sLine = iStream.ReadLine()
var res = sLine.split("\t");
sLine = res[0]+ "\t" + res[0]
sLine+="\r\n";
ss = ss + sLine;
}
iStream.Close();
if(fso.FileExists(newpath))
fso.DeleteFile(newpath);
varFileObject = fso.OpenTextFile(newpath, 8, true,0);
varFileObject.write(ss)
varFileObject.close()
Orginal file data is in below fashion:
Node Number
2175
2681
2708
2709
2737
2738
2777
2779
2823
2824
2889
11019
11020
12134
12193
12261
12262
12263
12264
12405
This is in one column whole data
I wanted this data to be written in notepad file as
Node Number Node Number
2175 2175
2681 2681
2708 2708
2709 2709
2737 2737
2738 2738
2777 2777
2779 2779
2823 2823
2824 2824
2889 2889
11019 11019
11020 11020
12134 12134
12193 12193
12261 12261
12262 12262
12263 12263
12264 12264
12405 12405
These are in two columns data.
The above script written works well but I wanted to avoid this command sLine+="\r\n" because it is giving me an error of Microsoft J Script compilation error ( Un-terminated string constant ) in some of machines. I do not why. Anyways I just wanted to know if there can be another way of doing above task?

Related

Extract optional arguments / parameters from a string

Lets say I have the following string, which I may receive and require my program to act up on:
ACTION -F filter string -L location string -M message string
How can I reliably extract the 'arguments' from this string, all of which are optional to the user?
I spent a lot of time instead writing ACTION, filter, location, message and using .split(", ") to put the args to an array but found this too difficult to work reliably.
var content = req.body.Body.split(", "); // [ Type, Filter, Location, Message]
var msgType = content[0].trim().toUpperCase();
if (msgType === 'INFO') {
// return info based on remainder of parameters
var filterGroup = content[1].trim();
var destination = content[2].trim();
var message = '';
// The message may be split further if it is written
// with a ',' so concat them back together.
if (content.length > 2) { // Optional message exists
// Message may be written in content[3] > content[n]
// depending how many ', ' were written in the message.
for (var i = 3; i < content.length; i++) {
message += content[i] + ", ";
}
}
}
Is the -a argument format even the best way? Much googling returns information on extracting the arguments used to run a nodeJS program, but that isn't applicable here, as the program is already running and the string not used at runtime. I'm at the design stage so have complete control over the format of the user input, but they're sending a SMS with these commands so the simpler the better!
I'm writing in javascript and would appreciate your thoughts
You can use a regex to match the -X pattern and then use a loop to extract the strings between each pattern match.
The regex here is /(?<=\s)\-[A-Za-z](?=\s)/g, which looks for a dash followed by a letter with a white space character on either side.
const input = "ACTION -F filter string -L location string -M message string";
let regex = /(?<=\s)\-[A-Za-z](?=\s)/g;
let args = [];
while(match = regex.exec(input))
{
args.push(match);
}
let solved = [];
for(let i = 0; i < args.length; i++)
{
let cmd = args[i][0];
let idx = args[i].index;
let val;
if(i + 1 == args.length)
val = input.substr(idx + cmd.length + 1);
else
val = input.substring(idx + cmd.length + 1, args[i + 1].index - 1);
solved.push({
cmd: cmd,
val: val
});
}
console.log(solved);

trying to decompress xref stream from pdf - getting "ERROR incorrect header check"

I am trying to parse the xref stream from PDF in JavaScript. I managed to succesfully isolate the stream itself (I checked that it's ok by comparing it in debugging mode with the value between steram. and endstream tags in PDF.
However, when I try to inflate it using pako lib, I get an error saying: ERROR incorrect header check.
The compression method is FlateDecode, which can be seen from the dictionary.
Here is the code in question:
const dict = pdfStr.slice(pdf.startXRef);
const xrefStreamStart = this.getSubstringIndex(dict, 'stream', 1) + 'stream'.length + 2;
const xrefStreamEnd = this.getSubstringIndex(dict, 'endstream', 1) + 1;
const xrefStream = dict.slice(xrefStreamStart, xrefStreamEnd);
const inflatedXrefStream = pako.inflate(this.str2ab(xrefStream), { to: 'string' });
pdfStr is the whole PDF read as a string, while *pdf.startXRef* holds the value of the position of the xref stream object.
Here's the whole PDF if someone wants to have a look: https://easyupload.io/lzf9he
EDIT: As mcernak has suggested I had a problem that I included /r and /n in the stream. However, now that I corrected the code I got a different error: invalid distance too far back
The stream content is located between stream\r\n and \r\nendstream.
You need to take into account those two additional characters (\r\n) at the beginning and at the end to read the correct data:
const dict = pdfStr.slice(pdf.startXRef);
const xrefStreamStart = this.getSubstringIndex(dict, 'stream', 1) + 'stream'.length + 2;
const xrefStreamEnd = this.getSubstringIndex(dict, 'endstream', 1) - 2;
const xrefStream = dict.slice(xrefStreamStart, xrefStreamEnd);
const inflatedXrefStream = pako.inflate(this.str2ab(xrefStream), { to: 'string' });

Google App Script - How to use methods without defining their object

I am writing the script behind a spreadsheet that has lots of durations on it in the format of (##:##.##) (ex 12:43.76). I need to write some code that converts this to just seconds. I wrote code that did the opposite, made seconds into that format. But when writing a custom formula for this, the .split method does not work.
function MTOS(input){
String(input);
if (typeof(input) != "string") {
Logger.log("Not a string")}
var array = input.split(":");
Logger.log('The original string is: "' + input + '"');
var min = Number(array[0]);
var sec = Number(array[1]);
Logger.log("min=" + min);
Logger.log("sec=" + sec);
var MIN = min*60;
Logger.log(MIN);
var ex = MIN+sec;
Logger.log(ex);
return ex;
}
This is what I have in the script editor. The input is the parameter from the spreadsheet when I write the formula in the sheet itself (ex - =MTOS(3:23.53)). When I run the function in the script editor, it gives me the error "TypeError: Cannot call method "split" of undefined. (line 5, file "MTOS")" and in sheets, it returns "Error : Result was not a number." I understand that this is happening because input is not defined in the function itself, so .split cannot work. But how else can I write the custom formula for sheets?
Thank you.
This seems to work for me: (Perhaps I'm misunderstanding the question).
function MTOS(input){
var iA = input.split(":");
var min = Number(iA[0]);
var sec = Number(iA[1]);
Logger.log('Seconds=%s',min * 60 + sec);
}

Javascript works as expected on Windows, errors on Linux

I have a script that parses through an xml file and copies an image path field to a new file. It works exactly as intended on a windows machine using the bash terminal. I tested it on a Ubuntu machine with the exact same code and xml files, and I am getting a TypeError. Here's where it is giving me trouble on Ubuntu:
if (catalogLine.indexOf('<image path="') !== -1){
//if we have an image, read the image file list line by line
var imageCount = 0;
var image = '';
var whitespace = catalogLine.match(/^\s*/)[0].length;
lineReader.eachLine(resources.fileListToCompare, function(imageLine, imageLast, imageCB) {
if (catalogLine.indexOf(imageLine) !== -1) {
//if we match an image, make a copy and store outside of scope
imageCount++;
image = ' '.repeat(whitespace) + '<image path="' + imageLine + '"/>';
}
And here is the traceback:
/vagrant/ChalkTalkTool/ImageRemoval.js:23
image = ' '.repeat(whitespace) + '<image path="' + imageLine + '"/>'
^
TypeError: Object has no method 'repeat'
at /vagrant/ChalkTalkTool/ImageRemoval.js:23:17
at /vagrant/ChalkTalkTool/node_modules/line-reader/lib/line_reader.js:277:11
at getLine (/vagrant/ChalkTalkTool/node_modules/line-reader/lib/line_reader.js:166:7)
at Object.nextLine (/vagrant/ChalkTalkTool/node_modules/line-reader/lib/line_reader.js:183:7)
at Object.readNext [as _onImmediate] (/vagrant/ChalkTalkTool/node_modules/line-reader/lib/line_reader.js:269:14)
at processImmediate [as _immediateCallback] (timers.js:363:15)
So I see that the error is in the line:
image = ' '.repeat(whitespace) + '<image path="' + imageLine + '"/>';
I can assume that it has do with the empty space character, but I want to understand why this happens on Ubuntu, and a way around it so that I can make my code more portable across different systems (I have tried using the character
" "
instead of a space to no avail).
The issue is that the repeat() function is only available in ES6 and higher. I'm assuming the Ubuntu instance you have running is running ES5.
You can test this theory by installing a polyfill, or write one yourself at the top of your code:
if (!String.prototype.repeat) {
String.prototype.repeat = function(howManyTimes) {
var result = '';
for (var i = 0; i < howManyTimes; i++) {
result += this;
}
return result;
}
}

Markdown And Escaping Javascript Line Breaks

I am writing a markdown compiler in Erlang for server-side use. Because it will need to work with clients I have decided to adopt the client side library (showdown.js) as the specification and then test my code for compatibility with that.
In the first couple of iterations I built up 260-odd unit tests which checked that my programme produced output which was compatible with what I thought was valid markdown based on reading the syntax notes.
But now I am trying to write a javascript programme to generate my unit tests.
I have an input like:
"3 > 4\na"
I want to run 'showdown' on it to get:
"<p>3 > 4\na</p>"
and I want to stitch this up into an EUnit assertion:
"?_assert(conv(\"3 > 4\na\") == \"<p>3 > 4\na</p>\"),",
which is the valid Erlang syntax for the unit test. To make life easy, and to make the unit test generator portable I am doing it inside a web page so that by appending some lines to a javascript file and then view the page you get the new set of unit tests inside a <textarea /> which you then copy down into the module to run EUnit.
The problem is that I can't get the line breaks to convert to \n in the string so I end up with:
"?_assert(conv(\"3 > 4
a\") == \"<p>3 > 4
a</p>\"),",
I've tried converting the linefeeds to their escaped versions using code like:
text.replace("\\", "\\\\");
text.replace("\n", "\\n");
but no joy...
Tom McNulty helped me out and pointed out that my regex's were super-pants, in particular I wasn't using the global flag :(
The working code is:
var converter;
var text = "";
var item;
var input;
var output;
var head;
var tail;
converter = new Attacklab.showdown.converter();
item = document.getElementById("tests");
for (var test in tests) {
input = tests[test].replace(/[\n\r]+/gi,"\\n" );
input = input.replace(/[\"]+/gi, "\\\"");
output = converter.makeHtml(tests[test]).replace(/[\n\r]+/gi, "\\n");
output = output.replace(/[\"]+/gi, "\\\"");
text += " ?_assert(conv(\"" + input + "\") == \"" + output + "\"),\n";
};
head = "unit_test_() -> \n [\n";
tail = "\n ].";
text = text.slice(0, text.length - 2);
item.value = head + text + tail;

Categories

Resources