Quicker searching in JScript using the Bash - javascript

I am using the following JScript code to search for a string inside a file:
var myFile = aqFile.OpenTextFile(fileToSearchIn, aqFile.faRead, aqFile.ctANSI);
while(!myFile.IsEndOfFile())
{
s = myFile.ReadLine();
if (aqString.Find(s, searchString) != -1)
Log.Checkpoint(searchString + " found.", s);
}
myFile.Close();
This is rather slow. I was thinking about using bash commands in order to speed up the search in file process:
var WshShell = new ActiveXObject("WScript.Shell");
var oExec = WshShell.Exec("C:\\cygwin\\bin\\bash.exe -c 'cat \"" + folderName + "/" + fileName + "\"'");
while (!oExec.StdOut.AtEndOfStream)
Log.Checkpoint(oExec.StdOut.ReadLine());
while (!oExec.StdErr.AtEndOfStream)
Log.Error(oExec.StdErr.ReadLine());
Since every time bash.exe is started a new window opens the searching is not faster than before. Is there a possibility to have the bash run in the background using another switch?

Every invocation of WshShell.Exec will start a new process which is costly. If your textfile is not too big this will prevent spawning a new process:
var myFile = aqFile.OpenTextFile(fileToSearchIn, aqFile.faRead, aqFile.ctANSI);
var myFileData = myFile.Read(myFile.Size);
var index = myFileData.indexOf(searchString);
if(index>0)
{
Log.Checkpoint(searchString + " found.", index);
}
myFile.Close();
This will not print the whole line but the index of the found location. If you want the whole line, search for line endings from there.

Related

fix doScript function error in InDesign script

I wrote a script for InDesign and used doScript to run a bat file. This script works on some systems and not on others.
The error is in the image.
I run as admin InDesign. But it gives another error.
How can I fix the error?
function batFile(str) {
var path = "~\\AppData\\Roaming\\test\\";
var filename = 'b1.bat';
var file1 = new File(path + filename);
file1.encoding = 'UTF-8';
file1.open('w');
var txt = "systeminfo | findstr /B /C:\"OS Name\" /C:\"OS Version\">%appdata%\\test\\t1.txt"
file1.write(txt);
file1.close();
var cmdcode = "CreateObject(\"WScript.Shell\").Run \"%appdata%\\test\\b1.bat\", 0, True";
app.doScript(cmdcode, ScriptLanguage.visualBasic, undefined, UndoModes.FAST_ENTIRE_SCRIPT);
var result = path + "t1.txt";
var arry = openFile2(result);
if (arry.length != 0) {
return arry;
} else {
return "null";
}
}
**
Update
I find the problem.
When a user name is composed of two parts, such as "your name" causes this problem. To address this issue, we need to put the address in two double quotations.
var txt = "systeminfo | findstr /B /C:\"OS Name\" /C:\"OS Version\">\"%appdata%\\test\\t1.txt"\"
**
Update 2
In Windows, when the user uses OneDrive, the AppData path also changes, which causes doScript not to run. for example:
c: \ users \ username \ appdata
Changes to:
c: \ users \ username \ onedrive \ appdata
This is a known bug reported in the UserVoice: https://indesign.uservoice.com/forums/601180-adobe-indesign-bugs/suggestions/41072476-type-library-is-not-automatically-created-by-cc202. A common trick to solve this is, run InDesign at least once as administrator on the client machine. This activates VBS support.
I can't tell what the problem with your script. But just in case, you can run bat file this way:
var bat_file = File("your_file.bat");
bat_file.execute();
Update
Based on your code I can offer the workaround: add & echo ok > %appdata%\\test\\ok.txt in your bat file and check if the file ok.txt exists before going further.
function batFile(str) {
var path = "~\\AppData\\Roaming\\test\\";
var filename = 'b1.bat';
var file1 = new File(path + filename);
file1.encoding = 'UTF-8';
file1.open('w');
var txt = "systeminfo | findstr /B /C:\"OS Name\" /C:\"OS Version\">%appdata%\\test\\t1.txt";
// add the file 'ok.txt' after the previous command is finished
txt += " & echo ok > %appdata%\\test\\ok.txt";
file1.write(txt);
file1.close();
// run the bat file
file1.execute();
// check if the file 'ok.txt' exists before going further
var ok = File(path + "ok.txt");
while (!ok.exists) $.sleep(100);
ok.remove();
// do stuff
var result = path + "t1.txt";
var arry = openFile2(result);
if (arry.length != 0) {
return arry;
} else {
return "null";
}
}

Include variable string inside JS function (HTA app)

I am trying to include variable inside cmd /c runas command, I use JS function and it gives me an error that specified file was not found.
I guess I am using the wrong variable calling or something.
Here is my function:
function runasSRVhta(){
var WShell = new ActiveXObject('WScript.Shell');
// var srvDude = document.getElementById("SRVinput").value;
var SRVguy = "someadmin.srv";
WShell.Run('cmd /c runas /u:sa.local\\SRVguy "c:\\windows\\system32\\mshta.exe """\\\\fs\\FIle Share\\SA Support\\ZverTools\\giveMeIPsPLZ.hta""""', 1, true);
}
Instead of running following command as someadmin.srv it runs its variable name, without taking value.
Problem is here - cmd /c runas /u:sa.local\\SRVguy, SRVguy should be variable taken from var SRVguy = "someadmin.srv";
Update
I tried following function as well, it detects variable value, but my HTA gives me another error saying that it can't find the file specified.
function testsrv() {
var shell = new ActiveXObject("WScript.Shell");
var SRVguy = "someadmin.srv";
var SRVguyaftertext = 'c:\\windows\\system32\\mshta.exe """\\\\fs\\FIle Share\\SA Support\\ZverTools\\giveMeIPsPLZ.hta"""';
var satavesrv = 'cmd /c runas /u:sa.local\\';
var theend = "'" + satavesrv + SRVguy + ' "' + SRVguyaftertext + '"' + "'";
document.write(theend);
var path = theend;
shell.run(theend,1,false);
}
Oh, and I used document.write to check output if it is correct, here is the output:
'cmd /c runas /u:sa.local\someadmin.srv "c:\windows\system32\mshta.exe """\\fs\FIle Share\SA Support\ZverTools\giveMeIPsPLZ.hta""""'
Everything seems correct with second function, but HTA pops up an error message saying that it cannot find the file specified...
try using template strings to include the variable in the string like this
WShell.Run(`cmd /c runas /u:sa.local\\${SRVguy} "c:\\windows\\system32\\mshta.exe """\\\\fs\\FIle Share\\SA Support\\ZverTools\\giveMeIPsPLZ.hta""""`, 1, true);
- Update
WShell.Run('cmd /c runas /u:sa.local\\' +SRVguy + ' "c:\\windows\\system32\\mshta.exe """\\\\fs\\FIle Share\\SA Support\\ZverTools\\giveMeIPsPLZ.hta"""', 1, true);

alfresco javascript inheritance and paths

I am writing a simple script on javascript for Alfresco Community. I have the script runnign everytime a new file is uploaded.
I need to check wether an specific filename (label.txt) exists in the folder. If it exists, I will use the information contained in the file for later treatment.
If I set the filename alone it works as long as the folder itself is the one with the script asigned, it works perfecly.
var labelFile = space.childByNamePath("label.txt");
if (labelFile != null)
{
...
}
When i set the inheritance of the script to lower level folders the script runs but still tries to find the label.txt file in the root folder. I am trying to locate the actual path of the uploaded document:
var dpath = document.displayPath + "/label.txt";
var labelFile = space.childByNamePath(dpath);
logFile.content += "labelFile: " + labelFile.displayPath + "\r\n";
if (labelFile != null)
{
...
}
I am getting a supposedly correct path in the dpath var, but I get a NULL result on the file object so I cannot read the file and its content.
What I am doing wrong?
What is "space" there? Try using "companyhome", see this for further ideas. http://docs.alfresco.com/4.0/references/API-JS-rootscoped.html
The current space ScriptNode (if any). For a script executing from a
rule, the space object is the space in which the rule resides. If the rule is inherited, this may not be the expected space.
The problem was not about inheritance, but space.childByNamePath just accepting relative paths, not absolute, so I ahd to calculate it from the space root:
var dpath = document.displayPath;
var dpatharray = dpath.split("/");
var dpathlength = dpatharray.length;
var spath = space.displayPath;
var spatharray = spath.split("/");
var spathlength = spatharray.length;
var labelpath = "";
for (var i=spathlength + 1; i<dpathlength; i++)
{
labelpath += dpatharray[i] + "/";
}
var labelFile = space.childByNamePath(labelpath + "label.txt");

Recursive processing of a directory not working correctly

I've been combing this forum looking at other examples of code similar to mine but I still have not been able to solve the issue.
I am processing images in Fiji/imageJ using a macro code. The code is meant to recursively search a given directory for image files (in this case .vsi files) and convert them to .tiff using the built in bioformats functions.
I have cobbled the following code together from several examples (I am not a programmer, I have a biology degree), and I am returning an error that the specified file does not exist just as I am about to actually process a file.
All of my images have the following general directory structure:
~/Brain_01/Slice_01/Slice_01_01.vsi
An actual example is as follows for the second image in this set:
~/K259_tlx3cre/K259_1of3_02/K259_1of3_01_02.vsi
I really, really appreciate all the help you guys provide! I am completely stuck right now and am just banging my head against the keyboard at this point. Also, I think I've followed all the rules for posting. If not please just point out the error of my ways.
Finally here is the macro code I have written so far:
Dialog.create("File type");
Dialog.addString("File suffix: ", ".vsi", 5);
Dialog.show();
suffix = Dialog.getString();
inDir = getDirectory("Choose Directory Containing " + suffix + " Files ");
outDir = getDirectory("Choose Directory for TIFF Output ");
setBatchMode(true);
processFiles(inDir, outDir, "");
print("Done!");
function processFiles(inBase, outBase, sub) {
flattenFolders = false; // this flag controls output directory structure
print("Processing folder: " + sub);
list = getFileList(inBase + sub);
if (!flattenFolders) File.makeDirectory(outBase + sub);
for (i=0; i<list.length; i++) {
path = sub + list[i];
//upath = toUpperCase(path);
upath = path; //the previous line cause some problems
if (endsWith(path, "/")) {
processFiles(inBase, outBase, path);
}
else if (endsWith(upath, suffix)) {
print("Importing " + suffix + " = " + list[i]);
run("Bio-Formats Windowless Importer", "open=path color_mode=Default view=Hyperstack stack_order=XYCZT");
print("Blue...");
selectImage(1);
title1 = getTitle();
run("Blue");
print("Green...");
selectImage(2);
title2 = getTitle();
run("Green");
print("Red...");
selectImage(3);
title3 = getTitle();
run("Red");
print("Merging Channels...");
run("Merge Channels...", "red=&title3 green=&title2 blue=&title1 gray=*None* cyan=*None* magenta=*None* yellow=*None* create keep");
print("Converting to RGB");
run("RGB Color");
saveAs("Tiff", path);
run("Close All");
}
}
}
Thanks to some great help from Jan, and the people on the ImageJ mailing list, I was able to get my code working well enough to do what I need to do! The code below is working well enough to batch convert a directory full of .vsi files to .tiff using the functions I need. I haven't tried changing my code to Michael's suggestion to change endsWith(path, "/"... if i get that working in the future I will post it also.
Dialog.create("File type");
Dialog.addString("File suffix: ", ".vsi", 5);
Dialog.show();
suffix = Dialog.getString();
inDir = getDirectory("Choose Directory Containing " + suffix + " Files ");
outDir = getDirectory("Choose Directory for TIFF Output ");
setBatchMode(true);
processFiles(inDir, outDir, "");
print("Done!");
function processFiles(inBase, outBase, sub) {
flattenFolders = true; // this flag controls output directory structure
print("Processing folder: " + sub);
list = getFileList(inBase + sub);
if (!flattenFolders) File.makeDirectory(outBase + sub);
for (i=0; i<list.length; i++) {
path = sub + list[i];
//upath = toUpperCase(path); only need if the file extension is case sensitive
upath = path; //avoids the previous line
if (endsWith(path, "/")) {
processFiles(inBase, outBase, path);
}
else if (endsWith(upath, suffix)) {
print("Importing " + suffix + " = " + list[i]);
run("Bio-Formats Windowless Importer", "open=["+inBase + path+"] color_mode=Default view=Hyperstack stack_order=XYCZT");
print("Stack to Images...");
run("Stack to Images");
print("Blue...");
selectImage(1);
title1 = getTitle();
run("Blue");
print("Green...");
selectImage(2);
title2 = getTitle();
run("Green");
print("Red...");
selectImage(3);
title3 = getTitle();
run("Red");
print("Merging Channels...");
run("Merge Channels...", "red=&title3 green=&title2 blue=&title1 gray=*None* cyan=*None* magenta=*None* yellow=*None* create keep");
print("Converting to RGB");
run("RGB Color");
saveAs("Tiff", outBase + path);
run("Close All");
}
}
}
By looking at the error message you get, you should be able to spot the issue: while your file sits at e.g. inBase + sub + list[i], your path variable contains just sub + list[i]. So you should use something like:
run("Bio-Formats Windowless Importer", "open=[" + inBase + path + "] color_mode=Default view=Hyperstack stack_order=XYCZT");
for opening the file, and:
saveAs("Tiff", outBase + path);
for saving the output file.
If you also want to use the flattenFolders flag in your code, you should build your output path dependent on the state of flattenFolders, such as:
outputPath = outBase;
if (!flattenFolders) outputPath += sub;
outputPath += list[i];
By the way, there's no need to convert your path to uppercase with toUpperCase(path), unless you want to use a case-insensitive file suffix. In that case, you can write:
if (endsWith(toUpperCase(path), toUpperCase(suffix))) {
// process your file here
}
to allow both .vsi and .VSI as an input.
Note: The script editor of the Fiji distribution of ImageJ offers a macro template to process folders recursively, you can open it via Templates > Macros > Process Folder in the editor.

Photoshop Javascript script: Rename file and saveAs

Im new to using JS with photoshop and have some trouble. What I want to do is to get rid of the word "Online" in the file name of the current document and then save a JPG with new file name in a different folder.
With the help of the adobe reference I came up with the following script:
//Path where the final jpg should be saved
var JPGquality = 12;
var docPath="C:\Users\user\Desktop\test";
var docName='';
docName = activeDocument.name;
//Set new file name by replacing "_Online_" with "_"
var NewName = docName.replace("_Online_", "_");
var saveFile = new File(docPath+'/'+NewName+ '.jpg');
//Save JPG
function SaveJPEG(saveFile, jpegQuality) {
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpgSaveOptions.matte = MatteType.NONE;
jpgSaveOptions.quality = jpegQuality; //1-12
activeDocument.saveAs(saveFile, jpgSaveOptions, true,Extension.LOWERCASE);
}
The Script runs through but therewithout errors but nothing happens. It would be very helpful if someone could tell me what Ive done wrong. Hope someone helps me figuring out how to fix this ;)
I use this:
function saveAsJPG() {
jpgFile = new File(outputFolder + "/" + _CardFileName + ".jpg");
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.embedColorProfile = true;
jpgSaveOptions.formatOptions = FormatOptions.STANDARDBASELINE;
jpgSaveOptions.matte = MatteType.NONE;
jpgSaveOptions.quality = 12;
docRef.saveAs(jpgFile, jpgSaveOptions, true, Extension.LOWERCASE);
}
Try to use forward slashes in your docPath:
var docPath="C:/Users/user/Desktop/test";
\t (tab) and \u (beginning of a Unicode sequence) have special meanings in JS strings.
Or you can escape them, of course:
var docPath="C:\\Users\\user\\Desktop\\test";
The best way to write paths in javascript for photoshop automation is '/c/users/user/' That works on both mac and windows and you don't need to escape the backslashes

Categories