I am trying to experiment with the Script defined in Get timestamp difference using ANT SO question.
When I use the Date.parse as given in the example, I get a NullPointerException on the line for Javascript i.e. on this line
<script language="javascript" >
It seems to be somehow related to the Date.parse call, but I don't seem to be able to figure it out.
<script language="javascript" >
<![CDATA[
println("calc js");
project.setProperty("task.diff",
Math.abs(
(Date.parse(project.getProperty("task.stop")) +
+project.getProperty("task.stop.millis")) -
(Date.parse(project.getProperty("task.start")) +
+project.getProperty("task.start.millis"))))
]]>
When I used the same concept in another script, making some changes to the original script, I get a different error -
javax.script.ScriptException: sun.org.mozilla.javascript.internal.EvaluatorException: missing ) after argument list (#7) in at line number 7
Here I am sending startTime and endTime as attributes to a macrodef and defining the script inside it.
project.setProperty("task.diff",
Math.abs(
Date.parse(#{startTime}) -
Date.parse(#{endtime})
)
);
How can I go about debugging this issue?
sun.org.mozilla refers to the Rhino JavaScript engine. Date.parse() is not supported by Rhino, unless you have a recent version:
New in Rhino 1.7R3
Use the Rhino console to check the version:
java -jar $RHINOPATH/js.jar #Rhino, `$RHINOPATH` is environment specific
jrunscript -q #Rhino via Mustang
References
Command Line Shell Scripting in Mustang
Java 6 Scripting is no js.jar
e4X is not Mustang
JavaScript Debugging Tips for Mustang
More JavaScript Debugging Tips for Mustang
Related
I am not so into JavaScript. I am using JavaScript to develop a litle script working on a JSON document. This JavaScript script is not executed into the browser but ino another product that allow to use JavaScript to script some tasks (the prodcut is WSO2 ESB but it is not important at this time).
This product (WSO2 ESB) uses Rhino as JavaScript engine, used to implement JavaScript scripts into Java application.
I have some problem trying to create a simple JSON object in this kind of environment.
I have done something like this (into my WSO2 ESB code):
<script language="js">
<![CDATA[
var response = JSON.parse(`
{
"forecast": []
}
`);
]]>
</script>
Using the same code into a classic JavaScript file performed into the broswer it works fine but it seems that it can't work using Rhino. I obtain error relating an illegal character (I also tryied to replace the ` and ` with " and " and with ' and ' but I still obtain error).
Something like this in the Java Stacktrace:
Caused by: javax.script.ScriptException: org.mozilla.javascript.EvaluatorException: illegal character (<Unknown Source>#9)
at com.sun.phobos.script.javascript.RhinoScriptEngine.compile(RhinoScriptEngine.java:341)
at com.sun.phobos.script.javascript.RhinoScriptEngine.compile(RhinoScriptEngine.java:323)
at org.apache.synapse.mediators.bsf.ScriptMediator.initInlineScript(ScriptMediator.java:399)
... 32 more
What could be the problem with Rhino? I think that the problem could be related to the `` character that maybe have to be escaped in some way. Some idea?
Or another something more pure JavaScript workaround solution could be: is it possible declare a JSON object like this:
{
"forecast": []
}
in a different way? I mean in a programmatically way without explicitly declare it.
This works in modern browsers that support ES6 with template literals:
var response = JSON.parse(`{"forecast": []}`);
Why, because JavaScript solves the back ticks first as a template and fills them with the content of the variables before the JSON string is parsed:
var test = "Cloudy";
var string = `{\"forecast": ["${test}"]}`;
var response = JSON.parse(string);
console.log(response);
But maybe your Rhino build has no ES6 support, so that won't work. Also the multiline is causing problems:
var response = JSON.parse(''+
'{'+
' "forecast": []'+
'}'
);
console.log(response);
I've been playing with snippets for Atom editor,
and see that I've learned I can include
JavaScript inside of a snippet, as my example shows.
(It inserts a TODO Comment with date)
TODO: (RAM) Fix this - 2014-11-23 20:55
HELLO
How can I include MORE JavaScript.?
For example
inside the snippet to set
var= to something
or
call a JS library
or
ask for input from user i.e. confirm();
and proceed on basis of confirm() function.
Any help would be appreciated, I looked for a long time,
but not much documentation on this. Submlime Text's snippets allowed lots of code to be inserted via Python.
Thanks
~Rob
Inside file snippets.cson
'.source.js':
'Date TODO: insert':
'prefix': 'datetd'
'body': """
TODO: (RAM) $1 - #{datetime = new Date(); datetime.getFullYear()}-#{(datetime.getMonth()+1)}-#{datetime.getDate()} #{datetime.getHours()}:#{datetime.getMinutes()}
#{"hello".toUpperCase(); }
$2
"""
Update: With the merge of atom/atom#4791, the capability of putting CoffeeScript code in CSON configuration files has been removed from Atom. The rest of the answer has been left intact for historic reference.
Actually, the syntax of the file is CoffeeScript (hence .cson as in CoffeeScript Object Notation), not JavaScript. It just so happens that you typed in JavaScript that is allowed as CoffeeScript. CoffeeScript doesn't use the var keyword, so you can assign variables like you did in your example:
datetime = new Date()
The other items, you'll probably have to get a little creative. I don't believe that the snippets package was intended to be used in this manner, which is why the lack of documentation on the "feature".
For few days I've been trying to include the actual Moment.js library in my dynamic PDF which I've created with Adobe Livecycle Designer.
We've used an older version (1.7.2) without any problems but now I only get a 'Function not exist' error.
Does anyone have any expierience with this?
Thanks in advance.
How to include Moment.js in an Adobe LiveCycle Form:
Download the minified script
In LiveCycle Designer open your form and create a Script Object called MOMENTJSMIN
Copy the minified script into that Script Object
In the Script Editor window of LiveCycle Designer, edit MOMENTJSMIN Script Object in the following manner:
Remove all the script up to but not including the second curly brace { :
!function(a,b){"object"==typeof exports&&"undefined"!=typeof module?module.exports=b():"function"==typeof define&&define.amd?define(b):a.moment=b()}(this,function()
Remove the rounded parenthesis and semicolon from the end of the minified script
Add this line to the beginning of the minified script:
if (xfa.momentjs == undefined) xfa.momentjs = function()
In the MOMENTJSMIN Script Object add this function after the end of the script:
function getMomentJS(){
return xfa.momentjs();
}
Now your MOMENTJSMIN script object is set up to provide Moment.js to scripts throughout your form.
To use Moment.js in any of your script, start your script object or event script with this line:
var moment = MOMENTJSMIN.getMomentJS();
Now you can use moment() anywhere in the script that starts with that line. eg:
var moment = MOMENTJSMIN.getMomentJS();
var jan07 = moment([2007, 0, 29]);
app.alert(moment().format("dddd, MMMM Do YYYY, h:mm:ss a"));
app.alert(jan07.format("dddd, MMMM Do YYYY") + " was " + jan07.fromNow());
app.alert(moment.isDate(new Date()));
What I would check first:
Make sure your script is fully loaded before trying to invoke functions from it. (check the event, where you call the function-calculate, form:readty etc.)
Check the script referencing. Right path? Right name?
Check if the function really exists
Check function parameters.
I recently had to fix a bug that manifested sometimes in Internet Explorer. The bug was that, sometimes, the parser choked on code like
<script type="text/javascript">
<!-- // comments -->
/*...*/
</script>
Which we fixed by correcting the comment.
My question is: is "<!--" valid javascript code, or not? I tried testing it with firebug, and it only says" Undefined". JSFiddle didn't faze. IE only choked on it some of the times (reloading the page in question would show up the result of the script involved).
While knowing that, for historical reasons, an HTML comment inside js could be valid depending on its exact position and the phase of the moon is indeed useful, I was more interested in answers like "var <!-- foo is valid js code, but <!-- on its own is not. Here's why:..."
I did some analysis in firebug:
var x = 2;
var y = 3;
var z = 0;
console.log(x);
console.log(y);
y<!--x;
console.log(x);
console.log(y);
z = y<! --x;
console.log(x);
console.log(y);
console.log(z);
resulting in the following:
2
3
2
3
1
3
false
The difference between the first and second tries is interesting.
I then tried
z = (y <!--x);
console.log(z);
Which failed with
SyntaxError: missing ) in parenthetical
First to answer your question on Is <!-- valid JavaScript: No, it is not, in none of the forms you gave in your question. This is because it is not valid according to the JavaScript BNF grammar which you can find here: http://tomcopeland.blogs.com/EcmaScript.html
If you are interested, here's why you do see it inside script blocks: It is the HTML comment character. You do see it very often within script tags like this:
<script>
<!--
.. JavaScript code...
// -->
</script>
The reason is that old browsers (and with "old" I mean "stone age" like Netscape 1.0) that do not even support JavaScript and would otherwise just show the code on the screen. By doing it this way those older browsers treat the JavaScript as HTML comments and do not show it. Newer browsers ignore this and just run the JavaScript.
This is how it actually works (from http://www.w3.org/TR/html401/interact/scripts.html#h-18.3.2): The JavaScript engine allows the string <!-- to occur at the start of a SCRIPT element, and ignores further characters until the end of the line. JavaScript interprets // as starting a comment extending to the end of the current line. This is needed to hide the string --> from the JavaScript parser.
Because all browsers nowadays support JavaScript (even if it is turned off) you do not need to do this anymore. It is actually bad practice to do so because of these reasons (from http://www.javascripttoolbox.com/bestpractices/#comments):
Within XHTML documents, the source will actually be hidden from all browsers and rendered useless
-- is not allowed within HTML comments, so any decrement operations in script are invalid
An even deeper explanation and all the cons and pro's can be found here: http://lachy.id.au/log/2005/05/script-comments
In older browsers, it was required to have these comments inserted because the browsers couldn't parse the javascript properly. it would try to literally parse the javascript as html which caused script execution failures.
Today, browsers don't need this.
It's not.
If you go to the standard, you'll see that a < can only exist in a RelationalExpression, which <!-- is not as it hasn't got anything on the left-hand side.
Comments in Javascript are like other C-type languages (// for single line, /* */ for blocks.
I'm trying to help a friend to figure out if it's possible to implement DSP algorithms in Max/MSP javascript. He was told so in class, and he asked for my help but I can't find any way to process actual samples.
TL;DR
Is it possible to get samples in and return them out in Max/MSP using javascript?
Thanks
No, it's not, as it's made only for processing messages and not signal vectors. Probably you mixed JavaScript with Java — there is a mxj~ object which allows you to use Java 6 (not higher!) for developing signal processing algorithms. Check out the tutorial, which everyone starts to learn how to use Java with: http://pcm.peabody.jhu.edu/~gwright/stdmp/docs/WritingMaxExternalsInJava.pdf
You can write DSP algorithms using Max’s gen~ and codebox, the syntax for which resembles JavaScript or C.
DSP in Max runs at high priority to avoid audio dropouts, which the js object does not, but it is possible to generate code using JavaScript and load that into a gen~ instance. You can find an example of this bundled with Max itself: search for a file called gen~.dynamicexpr.maxpat
They released a node.js API with Max 8. You can now.
Though not using javascript, like delucis said you can now use gen~ to write dsp code.
Here's a distortion gen~ function using tanh for my own project:
tanh_dist(input, amp, offset)
{
pass1 = input + offset;
pass2 = pass1 * amp;
pass3 = tanh(pass2);
return(dcblock(pass3));
}
I also made a sample patch to show you how to use it (in the codebox). Just copy the following text and paste into an empty max patch window:
----------begin_max5_patcher----------
1168.3ocyW8tbiZCD+y3mBF9TROWOHAXG2qsyzGf9Db4FOxfLVWAACH74bYx
8r2U+ALXv13j3zlOPFu+jzt6uc0tZedhky5r8zRG6ey9K1VVOOwxRIRJvx7a
KmTx9vDRoZYNgYooTtvYpFSP2KTxy1rojJdjWCjSDgaY73UEzPgVA3kAybmZ
iWH+hBbk+yyelq8WM6gWkx3ITgRSnCBypD0RcMRYQZst9a+Jx0QJ6kISjel9
F8CRZ94cBWzAmve9rf2EeX9qwE1jjAGbsstIqHknLx4FIfgvRgEHU4rZkBmv
AgnKFrl6K+piUX704m3994xCLaAIkJnEqnbx5DZadQeDhmxoZSwwYpsyZBO1
w9q2ZZJnOMgOPdCvSnkKj4.uy7zh+C3IN86fp6cgH7ovD5OsQv0ryvBttGxV
lGbdV.OHKf5yB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