How to create a Mathematica Notebook in Java? - wolfram-mathematica

I am looking for the prototypical 'Hello World' program that creates a Mathematica Notebook file.
I have this working program.
package graphica;
import com.wolfram.jlink.*;
/**
*
* #author Nilo
*/
public class MathematicaTester {
public static void main(String[] args) {
KernelLink ml = null;
String jLinkDir = "C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\\SystemFiles\\Links\\JLink";
System.setProperty("com.wolfram.jlink.libdir", jLinkDir);
try {
ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname 'C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\\MathKernel.exe'");
ml.discardAnswer();
String expr = "Sum[k^2,{k,1,11}]";
ml.evaluate(expr);
ml.waitForAnswer();
String x = ml.getString();
System.out.println("Result = " + x);
} catch (MathLinkException e) {
System.out.println("Fatal error opening link: " +
e.getMessage());
return;
}
}
}
When I run this I get the following -expected- output.
run:
Result = 506
BUILD SUCCESSFUL (total time: 2 seconds)
QUESTION:
I want to change this program so that a Mathematica Notebook is created. The program will ( eventually ) add line after line of mma command strings. It would be nice if a Mathematica frontend is started at the same time and that the mma code is evaluated by request from the Java program. Essential is the creation of a Notebook that can be opened later by the mma front-end.

A method for creating a formatted notebook file is shown here:
How to create a notebook with a properly formatted expression
You can box format your Mathematica code (mathCommand) using a kernel call, e.g.
String mathCommand = "Plot[Sin[x], {x, 0, 6}]";
mathCommand = "FullForm[ToBoxes[Defer[" + mathCommand + "]]]";
MathKernel kernel = new MathKernel();
kernel.Compute(mathCommand);
mathCommand = kernel.Result.ToString();
Then encapsulate it like so, and save it with .nb extension.
Notebook[{Cell[BoxData[
... ( inserted box-formatted output ) ...
], "Input"]
},
WindowSize->{615, 750},
WindowMargins->{{328, Automatic}, {Automatic, 76}},
StyleDefinitions->"Default.nb"
]

Mathematica notebooks are plaintext files with structures like
Notebook[{Cell[],Cell[]}]
You can work out the required structure by viewing them with a text editor. Assuming you can get Java to create a text file, save it with a .nb file name ending, and invoke the command-line version of Mathematica, then what you want should be doable. You will probably want to set the input cells to initialization type.

It took some research but I managed to answer the question myself.
package graphica;
import com.wolfram.jlink.*;
/**
*
* #author Nilo
*/
public class MathematicaTester {
public static void main(String[] args) {
KernelLink ml = null;
String jLinkDir = "C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\ \SystemFiles\\Links\\JLink";
System.setProperty("com.wolfram.jlink.libdir", jLinkDir);
try {
ml = MathLinkFactory.createKernelLink("-linkmode launch -linkname 'C:\\Program Files\\Wolfram Research\\Mathematica\\8.0\\MathKernel.exe'");
//test-1
ml.discardAnswer();
String expr = "Sum[k,{k,1,11}]";
ml.evaluate(expr);
ml.waitForAnswer();
String x = ml.getString();
System.out.println("Result = " + x);
//test-2
expr = "UsingFrontEnd[nb=NotebookPut[Notebook[{Cell[\"Graphics3D[Cuboid[]]\", \"Input\"]}]]]";
System.out.println("Result = " + ml.evaluateToOutputForm(expr, 40) );
expr = "UsingFrontEnd[NotebookSave[nb,\"TERRANOVA1\"]]";
System.out.println("Result = " + ml.evaluateToOutputForm(expr, 40) );
} catch (MathLinkException e) {
System.out.println("Fatal error opening link: " +
e.getMessage());
return;
}
}
}

Related

While using FileReader class in java why is it compulsory to store the value of r.read in i first and then type caste it? why can't we typecast r.read

[it is giving wrong output when I use f1.read directly .. why is it compulsory to use (i=f1.read) and then type caste i into the file .. why can't we use f1.read directly..] 1
//why this code is giving wrong output
// why is it compulsory to first store the value of f1.read in i
import static java.lang.System.out;
import java.io.*;
import java.util.*;
public class third{
public static void main(String [] args) {
try{
FileReader f1 = new FileReader("C:\\Users\\Akshita Agarwal\\Desktop\\a.txt");
FileWriter f2 = new FileWriter("C:\\Users\\Akshita Agarwal\\Desktop\\b.txt");
try{
while(f1.read() !=-1){
f2.write((char)f1.read());
}
}
finally {
f2.close();
}
}
catch(IOException e){
out.println(e);
}
}
}
char is two bytes unsigned. int -1 is outside this range.
Your code does not close f1 and it writes half of the file, every second char.
It could be written as:
for (;;) {
int c = f1.read();
if (c == -1) {
break;
}
f2.write((char)c);
}
You suggestion
for (;;) {
char c = (char) f1.read();
if (c == (char)-1) {
break;
}
f2.write(c);
}
has one drawback.
You could embed a ((char) -1) or '\uFFFF' in the middle of your file, and only
half of the file would be read.
The shortest code is:
for (int c; (c = f1.read()) != -1;) {
f2.write((char)c);
}
However it:
reads and writes per character
there is a conversion reading from binary data using the platform encoding to (Unicode) text
there is a conversion writing from (Unicode) text to binary data using the platform encoding.
Here you could do:
Path path1 = Paths.get("C:\\Users\\Akshita Agarwal\\Desktop\\a.txt");
Path path2 = Paths.get(System.getProperty("user.home"), "Desktop\\b.txt");
Files.copy(path1, path2);
or read by lines:
Charset charset = Charset.defaultCharset();
try (BufferedWriter writer = Files.newBufferedWriter(path2, charset));
Stream<String> reader = Files.lines(path1, charset)) {
reader.forEach(line -> bw.write(line + "\r\n"));
} // Automatically closes reader and writer.
The charset is needed to use the platform encoding. Per default it uses UTF-8, Unicode for the full range of possible characters for all languages.
Try-with-resources is a weird syntax try (<DECLARATIONS>) { ... } that ensures closing of the (auto-)closeable variables in the declarations. Even on return, break or exception.
The lines read are stripped from line endings CR-LF = "\r\n" (Windows), LF (Unix), CR, NEL (AS/400 e.a.).

Looking to Parse the following code (Apache CLI 1.4), but it doesn't get into the if loop

I have the following code in JDeveloper and I am trying to parse the output but can't seem to figure it out.
package project1;
import org.apache.commons.cli.*;
public class cmdParser
{
public static void main(String[] args)
{
try
{
Options options = new Options();
options.addOption("t", false, "display current time");
CommandLineParser parser = new DefaultParser();
CommandLine cmd = parser.parse( options, args);
if(cmd.hasOption("t"))
{
String optionT=cmd.getOptionValue("t");
System.out.println("Option t" + optionT);
}
else
{
System.out.println("Can't get the option");
}
}
catch(ParseException exp)
{
System.out.println("Error:" + exp.getMessage());
}
}
}
Output:
Click to enlarge the image
How do you get the option if you don't pass such an option...
Not sure how it is done in JDeveloper but from command line:
java cmdParser -t "my test option"
further more, you should use options.addOption("t", true, "display current time"); if you want to pass a value to the option. If the 2nd parameter is false, this option would just be a flag.

Intellij IDEA Plugin Gradle development - generating code to an existing class

I'm working on my IDEA IntelliJ Plugin with gradle and I am trying to create a button that adds a function to the current class, or a given class.
I saw an example in Eclipse but couldn't find the equivalent libraries.
I've tried to seek for an equivalent library to ICompilationUnit in Eclipse but couldn't find anything
ICompilationUnit unit = compilationUnit(activeEditor());
final String messageName = inputBox("Create New Message",
"Message Name");
if (messageName == null)
return null;
String camel = camelCase(messageName);
final String methodName = "handle" + camel;
IType type = null;
try {
unit.createImport(Global.WHEN_RECEIVED_CLASS_NAME.<String>data(), null, null);
type = unit.getType(drop(unit.getElementName(), 4));
if (!type.getSuperclassName().equals("SimpleAgent")) {
msgbox("cannot create message - unrecognized agent type");
return null;
}
IMethod mtd = method(type, methodName);
if (mtd == null) {
mtd = type
.createMethod(
"#WhenReceived(\""
+ messageName
+ "\")\npublic void "
+ methodName
+ "(){\n\t//TODO: Add Message Handling Code Here.\n\t"
+ "//you can add any parameters to the method in order to receive them within the message.\n}\n",
null, false, null);
}
CompilationUnitEditor editor = activeCompilationUnitEditor();
editor.setSelection(mtd);
My main goal is to add a button that once it's clicked it opens a text box, than it adds a function with the given text to the current class.
Error if nothing has been typed.
Thank you very much in advanced.

How to paste the text copied in clipboard through Selenium and Java on MacOS

I want to paste some text in one of the textbox in MACOS. I am trying below code. But Control + v and Command + v both are not working. I have also seen that this is known issue, but not sure if it is resolved or not.
https://github.com/seleniumhq/selenium-google-code-issue-archive/issues/5919
The code is as below.
public void copyToClipbord(String copyTo)
{
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection str = new StringSelection(copyTo);
clipboard.setContents(str, null );
}
// And paste into required input/testfield/testarea field object
public void pasteText(WebElement element, String value)
{
copyToClipbord(value);
element.click();
//new Actions( driver ).contextClick( element ).sendKeys( "P" ).sendKeys("\n").perform();
element.sendKeys(Keys.CONTROL, "V");
}
I have also tried context click, that also does not work. I have validated that copyToClipboard function is working properly. Please suggest me, if there are any work around to this.
Thanks,
Umang
You have to select paste option in pop up which open after right and then click on paste option.
You can write code like this.
new Actions(driver ).contextClick(element).sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN)
.sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ARROW_DOWN).
sendKeys(Keys.ARROW_DOWN).sendKeys(Keys.ENTER).perform();
For me Paste option is present at 5th position. So I have written sendKeys(Keys.ARROW_DOWN) 5 times. You can write this as per your requirement.
I hope this will work for you.
As you have mentioned copyToClipboard() function is working properly moving forward to send the character sequence through sendKeys() you can use the following solution:
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
copyToClipbord(value);
String data = (String) Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor);
element.sendKeys(data);
public String copyFromClipboard() {
boolean found = false
String data = ''
int count = 0
while (found == false) {
count++
try {
WebDriver driver = DriverFactory.getWebDriver()
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard()
data = ((Toolkit.getDefaultToolkit().getSystemClipboard().getData(DataFlavor.stringFlavor)) as String)
if (!(data.contains('https'))) {
found = false
} else {
println((('Found the data in the ' + count) + ' try: ') + data)
return data
found = true
break
}
}
catch (UnsupportedFlavorException e) {
println(e)
}
catch (IOException e) {
println(e)
}
}
}

How to remove Objects from PDF File using PDFClown

I have a pdf which contains a lot of invisible paths. Since the amount of path produces problems later on, I would like to remove the ones that have white colors.
So far I am trying to do this with a ContentScanner:
public class FilterWhitePathScanner implements Scanner {
private static final Logger LOG = LoggerFactory.getLogger(FilterWhitePathScanner.class);
private int count = 0;
public void scan(ContentScanner level) {
if (level == null)
return;
while (level.moveNext()) {
ContentObject object = level.getCurrent();
if (object instanceof ContainerObject) {
// Scan the inner level!
scan(level.getChildLevel());
} else if (object instanceof org.pdfclown.documents.contents.objects.Path) {
AffineTransform ctm = level.getState().getCtm();
Color<?> strokeColor = level.getState().getStrokeColor();
Color<?> fillColor = level.getState().getFillColor();
if (checkWhite(fillColor) && checkWhite(strokeColor)) {
level.remove();
} else {
LOG.info("Stroke Color " + strokeColor + " - Fill Color " + fillColor);
}
} else {
LOG.info("Object:" + object);
}
}
}
It recognizes the paths correctly, but in the end these are not removed from the PDF. Here the code handling the PDF (it extracts only one page from the source pdf):
Document targetDoc = new File().getDocument();
targetDoc.getPages().add(sourceDoc.getPages().get(pageNum).clone(targetDoc));
Page page = targetDoc.getPages().get(0);
Contents contents = page.getContents();
FilterWhitePathScanner filterWhitePathScanner = new FilterWhitePathScanner();
filterWhitePathScanner.scan(new ContentScanner(contents));
LOG.info("White Paths: " + filterWhitePathScanner.getCount());
targetDoc.getFile().save(tempFilePath.toFile(), SerializationModeEnum.Standard);
The saved PDF file still contains the paths I tried to remove. How can I remove objects from the PDF finally?
Thanks,
Thomas
Finally found the solution in the Java doc:
You have to call contents.flush(); to persist the changes into the pdf file.
So I added this line to the PDF handling code before calling save and it works!

Resources