-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVWorksExtLib.js
More file actions
1742 lines (1492 loc) · 66.6 KB
/
VWorksExtLib.js
File metadata and controls
1742 lines (1492 loc) · 66.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
///<?xml version='1.0' encoding='ASCII' ?>
///<Velocity11 file='MetaData' md5sum='00000000000000000000000000000000' version='1.1.0'>
///<Command Compiler='1' Description='VWorks Extension Library' Editor='-1' Name='VWorksExtLib'>
/// <Parameters>
/// </Parameters>
///</Command>
///</Velocity11>
function VWorksExtLib() {
print("This is the VWorks Extension Library (JS Wrapper version)");
}
function getVWorksExtLibVersion() {
// Update this when releasing new versions!
return "1.1.0";
}
// VWorksExtLib - VWorks Extension Library
// Author: Mauro A. Cremonini
//
// **************************** DISCLAIMER ***********************************//
// This project is developed and maintained in a personal capacity. //
// It is not affiliated with, endorsed by, or representative of my employer, //
// Agilent Technologies. All code, opinions, and documentation are my own and //
// my employer bears no responsibility for any aspect of this work. //
// Use the code at your own risk. Credits where credit is due. //
// ***************************************************************************//
//
// ======================== GENERAL PURPOSE FUNCTIONS ===============================
// This function returns the root folder for VWorksExtLib.
// If getVWorksExtLibRoot() is defined in the relevant context before open()ing
// VWorksExtLib.js, no redefinition will take plate.
// Note that if getVWorksExtLibRoot exists it must return "something"
// starting with "C:/VWorks Workspace/" (any casing).
var getVWorksExtLibRoot = (getVWorksExtLibRoot && typeof getVWorksExtLibRoot === "function" &&
getVWorksExtLibRoot().toLowerCase().replace(/\\/g,"/").indexOf("c:/vworks workspace/")===0) ?
getVWorksExtLibRoot :
function () {return "C:/VWorks Workspace/VWorksExtLib/"}
// ------------------------------------------------------------------------------
// This function returns true if run on VWorks 14.x and false otherwise.
function isVWorks14() {
return (typeof IsCompliantMode === "function");
}
// ------------------------------------------------------------------------------
// isArray returns true or false if the passed argument is an array.
Array.isArray = function (a) {
return Object.prototype.toString.call(a) === "[object Array]";
}
isArray = Array.isArray; // shorter to write :-)
// ------------------------------------------------------------------------------
// isWSArray returns true if the passed argument is an array
// of 2-element arrays that can be used for task.Wellselection.
function isWSArray(a) {
if (!isArray(a)) return false;
var cbk = function (el) {return (isArray(el) && el.length===2 && typeof el[0] === "number" && typeof el[1] === "number")};
return a.every(cbk);
}
// ------------------------------------------------------------------------------
// This function uses "mkdir" to create a folder if not existent.
function ensureFolderExists (folder) {
var folder = folder.toBackSlashes();
var f = new File();
var cmd = "cmd /c mkdir \"" + folder + "\"";
if (!f.Exists(folder)) {
print("Creating " + folder);
run(cmd, true);
}
return;
}
// ------------------------------------------------------------------------------
// helper function for throwing TypeErrors if callback is not a function
function checkIfCallback (cb) {
if (typeof cb === "function") return;
var msg = "Warning: " + cb + " is not a function.";
print(msg);
throw new TypeError(msg);
}
// ------------------------------------------------------------------------------
// Pause for secs seconds
function sleep(secs) {
run("cmd /c timeout /nobreak /t " + secs, true);
return true
}
// ------------------------------------------------------------------------------
// WSArray2String returns a "task.wellselection-like" string,
// useful when checking AoA's for multiAsp or multiDisp.
function WSArrayToString(a) {
if (!isWSArray(a)) {return "Not WS Array"};
var cbk = function (acc, el, ind, arr) {acc.push("["+el.toString()+"]"); return acc;};
var acc = a.reduce(cbk, []);
return "[" + acc.join(",") + "]"
}
// ------------------------------------------------------------------------------
// This function uses powershell to make VWorks speak a text.
// text: a string with the text to be read aloud.
// voiceNum: an integer, 0 for "MS David" voice and 1 for "MS Zira".
// volume: an integer in the range 0-100.
// waitUntilCompletion: a boolean. If false the function will immediately return.
// Omit this parameter for normal use.
function speak (text, voiceNum, volume, waitUntilCompletion) {
voiceNum = String(voiceNum) || "1";
volume = volume || 100;
var a = "$s=New-Object -ComObject Sapi.SpVoice";
var b = "$s.Voice=$s.GetVoices().Item("+voiceNum+")";
var c = "$s.Volume="+volume; // 0 - 100
var d = "$s.Speak(\\\"" + text + "\\\")";
cmd = "cmd /c powershell \"" + [a,b,c,d].join(";") + "\"" ;
print("Running: " + cmd);
run(cmd, waitUntilCompletion);
}
// ------------------------------------------------------------------------------
// This function uses powershell to generate beeps.
// Tone is in Hz, duration is in ms. For a nice beep use beep(2500,300).
// waitUntilCompletion: a boolean. If false the function will immediately return.
// Omit this parameter for normal use.
function beep(freqHz, durMs, waitUntilCompletion) {
var cmd = "cmd /c powershell \"[Console]::Beep("+freqHz+","+durMs+")\"";
run(cmd, waitUntilCompletion);
}
// ------------------------------------------------------------------------------
function alert() {
beep(2500,300);
}
// ------------------------------------------------------------------------------
function msgBox (msg, title, buttons, type) {
// see https://ss64.com/ps/messagebox.html
// ButtonType Value Image Value
// OK 0 None 0
// OKCancel 1 Error 16
// YesNoCancel 3 Question 32
// YesNo 4 Warning 48
// Information 64
var msgBoxFile = (getVWorksExtLibRoot() + "MsgBox/response.txt").toBackSlashes();
ensureFolderExists(msgBoxFile.dirname());
var sQuote = function (s) {return "'" + s + "'"};
var escDQuote = function (s) {return "\\\"" + s + "\\\""};
var pre = "cmd /c powershell \"Add-Type -AssemblyName PresentationFramework; [System.Windows.MessageBox]::Show(";
var mb = [pre + escDQuote(msg)];
mb.push(sQuote(title || ""));
mb.push(sQuote(buttons || "OK"));
mb.push(sQuote(type || "None")+")");
var cmd = mb.join(",") + " | Out-File -Filepath '" + msgBoxFile + "' -Encoding ascii \"";
run(cmd, true);
var f = new File();
f.filename = msgBoxFile;
return f.readFile().stripEmptyLines().trim();
}
// ------------------------------------------------------------------------------
// This function returns a time stamp in the default format "YYYY-MM-DD_hh-mm-ss".
// If a different form is needed, provide a new format using the following tokens:
// YYYY: full year
// YY: last two digits of year
// MM: month (01-12)
// DD: day (01-31)
// HH: hours (00-23)
// hh: hours (00-12)
// a: am/pm
// A: AM/PM
// mm: minutes (00-59)
// ss: seconds (00-59)
// If dateObj is provided, it is used instead of the current date/time.
// Examples:
// getTimeStamp("DD/MM/YYYY-HH_mm_ss") --> "13/03/1970-13_23_00"
// getTimeStamp("YYYY-MM-DD hh:mm:ss A", new Date(1965,0,4,13,30,45)) --> "1965-01-04 01:30:45 PM"
// Note: non-token characters are preserved as-is. If multiple tokens are used, they are all replaced.
function getTimeStamp (format, dateObj) {
if (!format) format = "YYYY-MM-DD_HH-mm-ss";
var format = String(format);
var myDate = (dateObj && dateObj.constructor.name === "Date") ? dateObj : (new Date());
var YYYY = String(myDate.getFullYear());
var YY = YYYY.slice(-2);
var MM = String(myDate.getMonth() + 1).zeropad(2);
var DD = String(myDate.getDate()).zeropad(2);
var HH = String(myDate.getHours()).zeropad(2);
var hh = String((myDate.getHours()%12) || 12).zeropad(2);
var mm = String(myDate.getMinutes()).zeropad(2);
var ss = String(myDate.getSeconds()).zeropad(2);
var a = (myDate.getHours() < 12) ? "am" : "pm";
var A = a.toUpperCase();
format = format
.replace(/YYYY/g,YYYY)
.replace(/YY/g,YY)
.replace(/MM/g,MM)
.replace(/DD/g,DD)
.replace(/HH/g,HH)
.replace(/hh/g,hh)
.replace(/mm/g,mm)
.replace(/ss/g,ss)
.replace(/a/g,a)
.replace(/A/g,A);
return format;
}
// ======================== POLYFILLS FOR OBJECTS ===============================
// Polyfil for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
Object.keys = function (obj) {
var arr = [];
if (typeof obj !== "object") return arr;
for (var p in obj) if (obj.hasOwnProperty(p)) arr.push(p);
return arr;
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values
Object.values = function (obj) {
var arr = [];
if (typeof obj !== "object") return arr;
for (var p in obj) if (obj.hasOwnProperty(p)) arr.push(obj[p]);
return arr;
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries
Object.entries = function (obj) {
var arr = [];
if (typeof obj !== "object") return arr;
for (var p in obj) if (obj.hasOwnProperty(p)) arr.push([p,obj[p]]);
return arr;
}
// ======================== POLYFILLS FOR ARRAYS ===============================
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf
Array.prototype.indexOf = function (x, fromIndex) {
// Return value:
// The first index of x in the array; -1 if not found.
var len = this.length;
var fromIndex = parseInt(fromIndex);
if (fromIndex >= len) return -1;
if (!fromIndex || fromIndex < -len) fromIndex = 0;
for (var i = fromIndex + (fromIndex < 0)*len; i < len; i++) {
if (this[i] === x) return i;
};
return -1;
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf
Array.prototype.lastIndexOf = function (x, fromIndex) {
// Return value:
// The last index of x in the array; -1 if not found.
var len = this.length;
var fromIndex = parseInt(fromIndex);
if (fromIndex < -len) return -1;
if (!fromIndex || fromIndex >= len) fromIndex = len-1;
for (var i = fromIndex + (fromIndex < 0)*len; i >= 0; i--) {
if (this[i] === x) return i
}
return -1
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex
Array.prototype.findIndex = function (callback, thisArg) {
// Return value:
//The index of the first element in the array that passes the test. Otherwise, -1.
checkIfCallback(callback);
for (var i = 0; i < this.length; i++) {
if (callback.apply(thisArg, [this[i], i, this])) return i
}
return -1
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findLastIndex
Array.prototype.findLastIndex = function (callback, thisArg) {
// Return value:
//The index of the last element in the array that passes the test. Otherwise, -1.
checkIfCallback(callback);
for (var i = this.length-1; i >=0; i--) {
if (callback.apply(thisArg, [this[i], i, this])) return i
}
return -1
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
Array.prototype.map = function(callback, thisArg) {
// Return value:
// A new array with each element being the result of the callback function.
// Sparse arrays will still be sparse and callback will not be invoked on them.
checkIfCallback(callback);
var arr = [];
for(var i=0; i<this.length; i++) {
if (!(i in this)) continue;
arr[i] = callback.apply(thisArg, [this[i], i, this]);
}
return arr;
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
Array.prototype.forEach = function(callback, thisArg) {
// Return value: none.
// Sparse arrays will still be sparse and callback will not be invoked on them.
checkIfCallback(callback);
for(var i=0; i<this.length; i++){
if (!(i in this)) continue;
callback.apply(thisArg, [this[i], i, this]);
}
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Array.prototype.filter = function(callback, thisArg) {
// Return value:
// A shallow copy of the given array containing just the elements that pass the test.
// If no elements pass the test, an empty array is returned.
checkIfCallback(callback);
var arr = [];
for(var i=0; i<this.length; i++) {
if (!(i in this)) continue;
if (callback.apply(thisArg, [this[i], i, this])) arr.push(this[i]);
}
return arr;
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
Array.prototype.find = function(callback, thisArg) {
// Return value:
// The first element in the array that satisfies the provided testing function.
// Otherwise, undefined is returned.
checkIfCallback(callback);
for(var i=0; i<this.length; i++){
if (callback.apply(thisArg, [this[i], i, this])) return this[i];
}
return undefined;
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every
Array.prototype.every = function(callback, thisArg){
// Return value:
// true unless callback returns a falsy value for an array element,
// in which case false is immediately returned.
checkIfCallback(callback);
for(var i=0; i<this.length; i++){
if (!(i in this)) continue;
if (!callback.apply(thisArg, [this[i], i, this])) return false;
}
return true;
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
Array.prototype.some = function(callback, thisArg){
// Return value:
// false unless callback returns a truthy value for an array element,
// in which case true is immediately returned.
checkIfCallback(callback);
for(var i=0; i<this.length; i++){
if (!(i in this)) continue;
if (callback.apply(thisArg, [this[i], i, this])) return true;
}
return false;
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Array.prototype.reduce = function(callback, initialValue) {
checkIfCallback(callback);
if (this.length === 0 && !initialValue) {print("Error in reduce"); throw new TypeError("Reduce failed");}
// edge case #1
if (this.length === 0 && initialValue) return initialValue;
// edge case #2 - check for one only element somewhere
var filteredThis = this.filter(function (el) {return !!el});
if (initialValue === undefined && filteredThis.length === 1) return filteredThis[0];
// remaining two cases
var accumulator, startElement;
if (initialValue === undefined) {
accumulator = this[0];
startElement = 1;
} else {
accumulator = initialValue;
startElement = 0;
};
for(var i=startElement; i<this.length; i++){
if (!(i in this)) continue;
accumulator = callback(accumulator, this[i], i ,this);
}
return accumulator;
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill
Array.prototype.fill = function (value, start, end) {
var len = this.length;
if (len === 0) return this;
var start = parseInt(start) || 0;
var end = (end===undefined && len) || (parseInt(end) || 0);
start = start < 0 ? start = len + start : start;
end = end < 0 ? end = len + end : end;
if (start < 0) start = 0;
if (end < 0) end = 0;
if (end > len) end = len;
if (start >= len) return this;
if (end <= start) return this;
for (var i = start; i < end; i++) this[i] = value;
return this
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/at
Array.prototype.at = function (index) {
var len = this.length;
var index = parseInt(index);
if (index < -len || index >= len ) return undefined;
return index<0 ? this[index+len] : this[index];
}
// ------------------------------------------------------------------------------
// This Array method returns the unique elements in an array.
// callback: equality checker to be used for the some() method.
Array.prototype.unique = function (callback) {
checkIfCallback(callback);
var reduceCallback = function (acc, el) {
if (!acc.some(callback,el)) acc.push(el);
return acc;
}
return this.reduce(reduceCallback,[]);
}
// ------------------------------------------------------------------------------
// This Array methods scrambles the elements of an array using the Fisher-Yates Shuffle Algorithm.
// Vanilla version (kept for reference).
Array.prototype.shuffleVanilla = function () {
var arr = this.slice(); //shallow copy
var len = arr.length;
var i, r, tmp;
for (i = len-1; i > 0 ; i--) {
r = Math.floor(Math.random() * (i+1));
tmp = arr[i];
arr[i] = arr[r];
arr[r] = tmp;
}
return arr;
}
// ------------------------------------------------------------------------------
// This Array methods scrambles the elements of an array using the Fisher-Yates Shuffle Algorithm.
Array.prototype.shuffle = function () {
var arrCpy = this.slice();
var cbk = function (el, ind, arr) {
if (ind === arr.length-1) return;
var rnd = ind + Math.floor((arr.length - ind) * Math.random());
if (rnd === ind) return;
arr[ind] = arr[rnd];
arr[rnd] = el;
}
arrCpy.forEach(cbk);
return arrCpy;
}
// ======================== POLYFILLS FOR STRINGS ===============================
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/trim
String.prototype.trim = function () {
return this.replace(/^\s+|\s+$/g,"");
}
// ------------------------------------------------------------------------------
// Zero-padding a string to "digits". Shorter than padStart().
String.prototype.zeropad = function (digits) {
var digits = parseInt(digits);
if (digits < 1 || isNaN(digits)) return this;
return this.padStart(digits,"0");
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart
String.prototype.padStart = function (toLen, str) {
var len = this.length;
if (toLen <= len) return this;
var delta = toLen-len;
var pad = str.repeat(Math.ceil(delta/str.length)).slice(0,delta);
return pad+this;
}
// ------------------------------------------------------------------------------
//Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd
String.prototype.padEnd = function (toLen, str) {
var len = this.length;
if (toLen <= len) return this;
var delta = toLen-len;
var pad = str.repeat(Math.ceil(delta/str.length)).slice(0,delta);
return this+pad;
}
// ------------------------------------------------------------------------------
// Polyfill for https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
String.prototype.repeat = function (count) {
var count = parseInt(count) || 0;
if (!count || count < 0 ) return this;
var outStr = "";
for (var i=0; i<count; i++) outStr += this;
return outStr;
}
// ------------------------------------------------------------------------------
// getWellselection() as String method. See below for getWellselection as function.
String.prototype.getWellselection = function (plateType) {
return getWellselection(this, plateType);
}
// ------------------------------------------------------------------------------
// remove trailing slash or backslash
String.prototype.stripTrailingSlash = function () {
return this.replace(/[\/\\]$/,"");
}
// ------------------------------------------------------------------------------
// return filename without path. If ext is provided and matches the file extension, it is removed as well.
String.prototype.basename = function (ext) {
var ext = (ext && "." + ext.replace(/^\./,"")) || ""; // ensure ext starts with "." if provided
return (this.stripTrailingSlash().split(/[\/\\]/)).at(-1).replace(new RegExp(ext+"$"),"");
}
// ------------------------------------------------------------------------------
// return folder name
String.prototype.dirname = function () {
return (this.stripTrailingSlash().split(/[\/\\]/)).slice(0,-1).join("/");
}
// ------------------------------------------------------------------------------
// return file extension
String.prototype.extname = function () {
return (this.stripTrailingSlash().split(".")).at(-1);
}
// ------------------------------------------------------------------------------
// turn all backslashes into forward slashes
String.prototype.toBackSlashes = function () {
return this.replace(/\//g, "\\");
}
// ------------------------------------------------------------------------------
// turn all backslashes into forward slashes
String.prototype.toForwardSlashes = function () {
return this.replace(/\\/g, "/");
}
// ------------------------------------------------------------------------------
// remove all \r, \n at the beginning of a lines and (\r)\n at end of content
String.prototype.stripEmptyLines = function () {
return this.replace(/\r/g,"").replace(/^\n/gm,"").replace(/[^\S\n\r]*\r?\n$/, "");
}
// ======================= NEW METHODS FOR THE MATH OBJECT ==================
// This methods rounds to d decimal digits
Math.roundTo = function (x, d) {
var x = parseFloat(x);
var d = Math.abs(parseInt(d));
if (isNaN(x)) return NaN;
if (isNaN(d)) return x;
var factor = this.pow(10,d);
return this.round(x*factor)/factor;
}
// ======================= NEW METHODS FOR THE FILE() CONSTRUCTOR ==================
// fn: filepath, forwardSlashes: changes backslashes to forward slashes (useful for VWorks 14.x).
// The filename is set in the "filename" property.
File.prototype.setFilename = function (fn, forwardSlashes) {
if (!fn) {print("setFilename: no filename provided."); return false};
this.filename = forwardSlashes ? fn.toForwardSlashes() : fn;
}
// ------------------------------------------------------------------------------
// This method reads the content of the file and stores it in the "content" property
File.prototype.readFile = function () {
if (!this.filename) {print("readFileContent: set the filename property first."); return false};
if (!this.Exists(this.filename)) {alert(); print("readFileContent: file not found."); return false};
this.Open(this.filename);
this.content = this.Read();
this.Close();
return this.content;
}
// ------------------------------------------------------------------------------
// This method checks if the file set in the property filename exists. Returns true or false.
File.prototype.existsFile = function () {
if (!this.filename) {print("existsFile: set the filename property first."); return false};
return this.Exists(this.filename);
}
// ------------------------------------------------------------------------------
// This method saves "content" to this.filename (overwriting the file!).
// If content is an array then the separator "sep" is used to separate the elements of the array
// and "\n" is added at the end.
// "suppressCRLF" is passed to Open() as third argument.
File.prototype.writeFile = function (content, sep, suppressCRLF) {
if (!this.filename) {alert(); print("writeToFile: set the filename first."); return false};
var txt = isArray(content) ? content.join(sep) + "\n" : content;
this.Open(this.filename, true, suppressCRLF);
this.Write(txt);
this.Close();
this.readFile();
return true;
}
// ------------------------------------------------------------------------------
// This method appends "content" to this.filename.
// See "writeFile" for the meaning of the parameters.
File.prototype.appendFile = function (content, sep, suppressCRLF) {
if (!this.filename) {alert(); print("writeToFile: set the filename first."); return false};
var txt = isArray(content) ? content.join(sep) + "\n" : content;
this.Open(this.filename, false, suppressCRLF);
this.Write(txt);
this.Close();
this.readFile();
return true;
}
// ------------------------------------------------------------------------------
// This method first reads the content of this.filename and then stores it in the
// filepath "fn2". If fn2 exists and overwrite is false, no copy will happen.
File.prototype.copyFile = function (fn2, overwrite) {
if (!this.filename) {alert(); print("copyFile: set the filename first."); return false};
if (!overwrite && this.Exists(fn2)) {alert(); print("copyFile: target file exists. Can't copy."); return false};
var cmd = "cmd /c copy /Y \"" + this.filename.toBackSlashes() + "\" \"" + fn2.toBackSlashes() + "\"";
run(cmd, true)
return true;
}
// ------------------------------------------------------------------------------
// Delete file (added for naming consistency)
File.prototype.deleteFile = function (fn) {
if (!this.Exists(fn)) {alert(); print("deleteFile: file not found."); return false};
this.Delete(fn);
return true;
};
// ------------------------------------------------------------------------------
// This method lists the files in a folder using:
// "cd <folder> & dir /b <folder> <pattern> > <outFile>"
// folder: the required folder
// patter: like "*.*" or "*.txt"
// outFile: (generally not required) a temporary file in <folder>
File.prototype.readFolder = function (folder, pattern, outFile) {
if (!folder) {alert(); print("readFolder: no folder provided."); return false};
var pattern = pattern || "*.*";
var outFile = outFile || "__readFolder";
var dosFolder = folder.toBackSlashes();
if (!this.Exists(dosFolder)) {alert(); print("readFolder: folder not found."); return false};
var command = "cd " + dosFolder + " & dir /b " + pattern + " > " + outFile;
run("cmd /c " + command, true);
this.Open([folder,outFile].join("/"));
var folderContent = (this.Read()).stripEmptyLines();
this.Close();
this.Delete([folder,outFile].join("/"));
return folderContent.split("\n").filter(function (el) {return !!el});
}
// ======================= BASE64 ENCODING/DECODING FUNCTIONS ==================
// see https://base64.guru/learn/base64-algorithm/encode and wikipedia
function btoa (inStr) {
var inStr = String(inStr)
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
var lastPos = inStr.length - 1
var i = -1, tmp, encoded = ""
while (i < lastPos) {
tmp = inStr.charCodeAt(++i) << 16 | inStr.charCodeAt(++i) << 8 | inStr.charCodeAt(++i)
encoded += alphabet[(tmp >>> 18) & 0x3F] + alphabet[(tmp >>> 12) & 0x3F] + alphabet[(tmp >>> 6) & 0x3F] + alphabet[tmp & 0x3F]
}
var remChars = inStr.length % 3
return remChars ? encoded.slice(0,remChars-3) : encoded
}
// ------------------------------------------------------------------------------
function atob (inStr) {
var inStr = String(inStr)
var lastPos = inStr.length - 1
var i = -1, tmp, decoded = ""
var index = function (c) {
var alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
return alphabet.indexOf(c) < 0 ? 0 : alphabet.indexOf(c)
}
while (i < lastPos) {
tmp = index(inStr[++i]) << 18 | index(inStr[++i]) << 12 | index(inStr[++i]) << 6 | index(inStr[++i])
decoded += String.fromCharCode( (tmp >>> 16) & 0xFF, (tmp >>> 8) & 0xFF, tmp & 0xFF)
}
var ind0 = decoded.indexOf(String.fromCharCode(0))
return ind0 < 0 ? decoded : decoded.slice(0,ind0)
}
// ======================= OTHER FUNCTIONS ======================================
// *** DEPRECATED function *** - use distributeUnitsEvenly() directly instead.
// Kept for backward compatibility.
//
// This function solves the problem of processing "nUnits" of something when the available maximum capacity is "maxCapacity"
// and each unit needs to use "someCapacity". The function will return the "best" number of cycles needed to complete the action
// and the number of units that will be processed in each cycle. "Best" here is intented as the one that makes the resulting
// processed units per cycles as similar as possible.
// Possible uses:
// 1. filling "nUnits" columns (with multidispense), each with "someCapacity" uL using tips having a max volume of "maxCapacity" uL.
// 2. processing "nUnits" plates stored in a stacker when the available space on the Bravo amounts to "maxCapacity" locations
// and one needs to know how many plates to use in each cycle. In case one has 3 locations available maxCapacity=3 and someCapacity=1.
// The function returns an object whose propertes are "nCycles" (integer) and "unitsPerCycle" (array of integers of length nCycles).
// Test #1: get 16 plates in groups of 3 on the Bravo:
// print("=== Test with number of plates")
// pTest = {nUnits: 16,maxCapacity: 3,someCapacity: 1}
// pRes = doActionInCycles(pTest)
// print("nUnits = " + pTest.nUnits + " nCycles = " + pRes.nCycles + " unitsPerCycle = " + pRes.unitsPerCycle)
// --> nUnits = 16 nCycles = 6 unitsPerCycle = 3,3,3,3,2,2 (note that it is *not* 3,3,3,3,3,1)
// Test #2: calculate how to multidispense 30 uL to 9 columns using filtered tips whose max volume is 180 uL:
// print("=== Test with multidispense")
// vTest = {nUnits: 9,maxCapacity: 180,someCapacity: 30}
// vRes = doActionInCycles(vTest)
// print("nUnits = " + vTest.nUnits + " nCycles = " + vRes.nCycles + " unitsPerCycle = " + vRes.unitsPerCycle)
// --> nUnits = 9 nCycles = 2 unitsPerCycle = 5,4 (*not* 6,3)
function doActionInCycles (o) {
var props = ["someCapacity","nUnits","maxCapacity"];
if (typeof(o) !== "object") {
print("Argument is not an object!");
return false;
}
for (var i = 0; i < props.length; i++) {
if (!o.hasOwnProperty(props[i]) || typeof o[props[i]] !== "number") {
print("Problem with property " + props[i]) ;
return false;
}
}
var someCapacity = o.someCapacity, nUnits = o.nUnits, maxCapacity = o.maxCapacity;
return distributeUnitsEvenly(nUnits, someCapacity, maxCapacity);
}
// ------------------------------------------------------------------------------
// This function distributes nUnits into cycles so that:
// 1. each cycle processes an integer number of units
// 2. no cycle exceeds cycleCapacity when processing its units
// 3. the number of units processed in each cycle is as similar as possible
// Returns an object with properties:
// nCycles: integer, number of cycles needed
// unitsPerCycle: array of integers, number of units processed in each cycle
// If input arguments are invalid, it returns false.
function distributeUnitsEvenly (nUnits, unitCapacity, cycleCapacity) {
var nUnits = parseInt(nUnits);
var unitCapacity = parseFloat(unitCapacity);
var cycleCapacity = parseFloat(cycleCapacity);
if (isNaN(nUnits) || isNaN(unitCapacity) || isNaN(cycleCapacity) || nUnits < 2 || unitCapacity <= 0 || cycleCapacity <= 0) {
print("distributeUnitsEvenly: bad input argument(s)");
return false;
}
var maxUnitsPerCycle = Math.floor(cycleCapacity / unitCapacity);
if (maxUnitsPerCycle < 1) {
print("distributeUnitsEvenly: unitCapacity exceeds cycleCapacity");
return false;
}
var nCycles = Math.ceil(nUnits / maxUnitsPerCycle);
var baseUnitsPerCycle = Math.floor(nUnits / nCycles);
var cyclesWithExtraUnit = nUnits % nCycles;
var unitsPerCycle = [].concat(
Array(cyclesWithExtraUnit).fill(baseUnitsPerCycle + 1),
Array(nCycles - cyclesWithExtraUnit).fill(baseUnitsPerCycle)
);
return {nCycles: nCycles, unitsPerCycle: unitsPerCycle};
}
// ------------------------------------------------------------------------------
// This function calculates how to distribute some capacity evenly over nUnits
// when each unit needs unitCapacity and the maximum capacity per cycle is cycleCapacity.
// decDigits: number of decimal digits for capacityPerCycle (default: 1).
// It returns an object with properties:
// nCycles: integer, number of cycles needed
// capacityPerCycle: float, capacity to be used for each unit in each cycle
// If input arguments are invalid, it returns false.
function distributeCapacityEvenly (nUnits, unitCapacity, cycleCapacity, decDigits) {
var decDigits = (decDigits === undefined) ? 1 : Math.abs(parseInt(decDigits));
var nUnits = parseInt(nUnits);
var unitCapacity = parseFloat(unitCapacity);
var cycleCapacity = parseFloat(cycleCapacity);
if (isNaN(nUnits) || isNaN(unitCapacity) || isNaN(cycleCapacity) || nUnits < 2 || unitCapacity <= 0 || cycleCapacity <= 0) {
print("distributeCapacityEvenly: bad input argument(s)");
return false;
}
var nCycles = Math.ceil((nUnits * unitCapacity) / cycleCapacity);
var capacityPerCycle = Math.roundTo(unitCapacity / nCycles, decDigits);
return {nCycles: nCycles, capacityPerCycle: capacityPerCycle};
}
// ------------------------------------------------------------------------------
// This function returns the wellselection array corresponding to a certain well address.
// If a well address does not belong to the chosen format ("platetype"), it returns false.
function getWellselection (well,plateType) {
var filterSpaces = /[^A-Z0-9]/g;
var filterType = /^(6|12|24|48|54|96|384|1536)$/;
var filter2Letters = /^[A-Z]{2}/;
var filter12Numbers = /[0-9]{1,2}$/;
var checkWell = {6: /^[A-B]0?[1-3]$/,
12: /^[A-C]0?[1-4]$/,
24: /^[A-D]0?[1-6]$/,
48: /^[A-F]0?[1-8]$/,
54: /^[A-F]0?[1-9]$/,
96: /^[A-H](0?[1-9]|1[012])$/,
384: /^[A-P](0?[1-9]|1[0-9]|2[0-4])$/,
1536: /^([A-Z]|A[A-F]|([A-F])\2)(0?[1-9]|[123][0-9]|4[0-8])$/};
if (plateType === undefined) {print("getWellselection: no plate type provided - defaulting to 96 well-format"); var plateType = 96};
var plateType = plateType.toString().replace(filterSpaces,"");
if (!filterType.test(plateType)) {print("getWellselection: bad plate type \"" + plateType +"\""); return false};
var well = well.toString().toUpperCase().replace(filterSpaces,"");
if(!checkWell[plateType].test(well)) {print("getWellselection: bad well address \"" + well + "\" for selected plate type \"" + plateType +"\""); return false};
var row = filter2Letters.test(well) ? 26 + well.charCodeAt(1) - 64 : well.charCodeAt(0) - 64;
var col = filter12Numbers.exec(well)[0];
return [parseInt(row),parseInt(col)];
}
// ------------------------------------------------------------------------------
// This function pulls labware information from the registry (VWorks 13)
// or the roiZip record (VWorks 14) and returns an object with labware's parameters.
// Updated for VWorks 14 (Jan 2023)
// Improved VWorks 13 part: now it makes sure that labware exists before calling reg.Read() (Apr 2025).
function plateInfo (plateName) {
if (typeof plateName !== "string") {print("plateInfo: bad input argument"); return}
var baseC = ["","Microplate","Filter plate","Reservoir","Tip Wash Station","Pin tool","Tip box","Lid","Tip trash bin","AM cartridge rack"];
var wellG = ["","Round","Square"];
var wellB = ["","Rounded","Flat","V-Shaped"];
var labwrP = { name: "NAME",
wells: "NUMBER_OF_WELLS",
maxVolume: "WELL_TIP_VOLUME",
labwareType: "BASE_CLASS",
wellDepth: "WELL_DEPTH",
wellDiameter: "WELL_DIAMETER",
wellGeometry: "WELL_GEOMETRY",
wellBottom: "WELL_BOTTOM_SHAPE",
tipCapacity: "TIP_CAPACITY"};
print("Retrieving parameters for labware entry \"" + plateName + "\"");
// Create PlateInfo work folder.
// *** C:/VWorks Workspace must be user writable (usually, it is).
var outPath = "C:/VWorks Workspace/Temp/PlateInfo/";
ensureFolderExists(outPath);
var f = new File();
if (isVWorks14()) {
var getQuery = function (q) {
var queryTemplate = "//value[@name=\"##@@##\"]/@value";
return queryTemplate.replace("##@@##",q);
}
var labwPath = "VWorks Projects/VWorks/Labware/Entries/"; //relative to [olssvr]
// download a labware entry to outPath
if (!f.Exists("[olssvr]:"+labwPath+plateName+".xml.roiZip")) {
print("plateInfo: labware " + plateName + " not found");
return;
}
DownloadFromStorage(labwPath+plateName+".xml",outPath);
// Start XPath
var xmlDoc = new ActiveX("Msxml2.DOMDocument.6.0");
xmlDoc.setProperty("SelectionLanguage","XPath");
xmlDoc.async = false;
f.Open(outPath+plateName+".xml");
var isXMLReadOK = xmlDoc.loadXML(f.Read());
f.Close();
if (!isXMLReadOK) {print("plateInfo: XML read failed"); return};
var resObj = {};
for (var p in labwrP) {
if (labwrP.hasOwnProperty(p)) resObj[p] = xmlDoc.selectSingleNode(getQuery(labwrP[p])).value;
}
}
else {
var myKey, reg
var vworksPath = "C:\\Program Files (x86)\\Agilent Technologies\\VWorks\\VWorks.exe";
var f = new File();
myKey = f.Exists(vworksPath) ?
"SOFTWARE\\Wow6432Node\\Velocity11\\Shared\\Labware\\Labware_Entries\\" + plateName : // 64-bit Windows
"SOFTWARE\\Velocity11\\Shared\\Labware\\Labware_Entries\\" + plateName; // 32-bit Windows
// Make sure that the labware exists in the registry
// otherwise reg.Read() fails and VWorks stops executing the present JS code.
var myKey2 = "HKLM\\" + myKey;
var regFileName = outPath + "regTest.txt";
var regCmd = "cmd /c reg query \"" + myKey2 +"\" /v NAME 2> \"" + regFileName + "\"";
run(regCmd,true);
f.Open(regFileName);
var content = f.Read();
f.Close();
if (content.indexOf("ERROR:") > -1) {
print("plateInfo: labware " + plateName + " not found");
return;
}
// create registry object
var reg = new Registry();
// now create an object with all the required info
var resObj = {};
for (var p in labwrP) {
if (labwrP.hasOwnProperty(p)) resObj[p] = reg.Read(myKey,labwrP[p]);
}
}
// manipulate properties for some entries
resObj.labwareType = baseC[resObj.labwareType];
resObj.wellGeometry = wellG[resObj.wellGeometry];
resObj.wellBottom = wellB[resObj.wellBottom];
if (resObj.labwareType !== "Tip box") resObj.tipCapacity = "NA";
return resObj;
}
// ------------------------------------------------------------------------------
// This constructor simulates WaitFor/Signal pairs.
// It is useful when preventing a subprocess from starting while waiting
// from "something" to happen.
// dontReset: generally not provided. If provided, the WaitFor will not block
// after the first signal is received.
function Signal (dontReset) {
if (!(task && task.getProtocolName())) {
print("Warning: Signal() must only be instantiated in a protocol.");
return false;
}
var signaled = false;
this.waitForSignal =function (delay, message) {
signaled ? (signaled=!!dontReset, task.skip()) : task.repeatDelay(delay);
message && print(message);
}
this.sendSignal = function (message) {
signaled = true;
message && print(message);
}
}
// ------------------------------------------------------------------------------
// This is a contructor that returns an object with a method "log"
// that adds a line to a custom log file, creating the path if not existent.
// If fileOrTask is the "task" object then the output file is automatically set to
// C:\VWorks Workspace\CustomLogs\<protocol name>_out.txt.
// In the log method, if txtLine is an array its elements are automatically join()'ed with the selected separator.
function CustomLog (fileOrTask, sep) {
var sep = sep || "\t";
var fileName = "", f = new File();
if (typeof fileOrTask === "object") {
if (typeof fileOrTask.getProtocolName === "function") {
var tmp = fileOrTask.getProtocolName().replace(/\\/g,"/").split("/").pop();