I want to do something like this:
Python Code:
nums = [1,2,3]
Java Code:
nums_Java[] = nums //from python
System.out.println(nums_Java[0])
Output:
1
I have been looking over jython but I just can't seem to find the answer. It seems like it should be very simple but I'm lost. Thanks!
If I understand the question correctly, you'd like to run some embedded python code from a java program, and get the value of a python variable.
Based on http://www.jython.org/archive/21/docs/embedding.html , I wrote a small program that might help:
import org.python.util.PythonInterpreter;
import org.python.core.*;
public class SimpleEmbedded {
public static void main(String[] args) throws PyException {
PythonInterpreter interp = new PythonInterpreter();
interp.exec("nums = [1,2,3]");
PyObject nums = interp.get("nums");
System.out.println("nums: " + nums);
System.out.println("nums is of type: " + nums.getClass());
}
}
Unfortunately, I don't have jython installed at the moment, so the above code is untested. Also I'm not sure what type you will get back from the interpreter, and how to convert it to a java array or access its items. But the program should get you started and give you some more information.
Related
Hello I am new into using MOA and WEKA,
I need to test paired learners concept using this code and I have been able to locate the code but I cannot find any example online and
I am having a hard time figuring how to pas my data into the code and run a test and see my results.
Pls can anyone point my in a right direction or give me a few pointers that I could follow to implement this.
moa/moa/src/main/java/moa/classifiers/meta/PairedLearners.java
Trying to use a similar code like this:
https://groups.google.com/forum/#!topic/moa-development/3IKcguR2kOk
Best Regards.
//Sample code below
import moa.classifiers.meta.pairedLearner;
Public class SamplePairedlearner{
public static void main(String[] args) {
FileStream fStream = new FileStream();
fStream.arffFileOption.setValue("test.arff");// set the ARFF file name
fStream.normalizeOption.setValue(false);// set normalized to be true or false
fStream.prepareForUse();
int numLines = 0;
PairedLearner learners = PairedLearners();
learners.resetLearning();
learners.resetLearningImpl(); //this is where i get an error message
ClusteringStream stream = fStream;
while (stream.hasMoreInstances()) {
Instance curr = stream.nextInstance().getData();
learners.trainOnInstanceImpl(curr)//this line also generates an error
numLines++;
}
Clustering resDstream = dstream.getClusteringResult();
dstream.getMicroClusteringResult();
System.out.println("Size of result from Dstream: " + resDstream.size());
System.out.println(numLines + " lines have been read");
}
}
I could fix the code that you have there, but it wouldn't do you much good. MOA has it's own selection of tasks and evaluators for running these experiments at a much higher level. This is how to run evaluations properly and not dive too deeply into the code. I'll assume a few things:
We use PairedLearners as our classifier.
We evaluate stream classification performance.
We evaluate in predictive sequential (prequential) fashion, i.e. train, then test on each example in the sequence.
Therefore, we can define our task quite simply, as follows.
public class PairedLearnersExample {
public static void main(String[] args) {
ArffFileStream fs = new ArffFileStream(PairedLearnersExample.class.getResource("abalone.arff").getFile(), -1);
fs.prepareForUse();
PairedLearners learners = new PairedLearners();
BasicClassificationPerformanceEvaluator evaluator = new BasicClassificationPerformanceEvaluator();
EvaluatePrequential task = new EvaluatePrequential();
task.learnerOption.setCurrentObject(learners);
task.streamOption.setCurrentObject(fs);
task.evaluatorOption.setCurrentObject(evaluator);
task.prepareForUse();
LearningCurve le = (LearningCurve) task.doTask();
System.out.println(le);
}
}
If you want to do other tasks, you can quite happily swap out the evaluator, stream and learner to achieve whatever it is you want to do.
If you refer to the MOA Manual you'll see that all I'm doing is imitating the command line commands - you could equally perform this evaluation at the command line if you wished.
For example,
java -cp .:moa.jar:weka.jar -javaagent:sizeofag.jar moa.DoTask \
"EvaluatePrequential -l PairedLearners \
-e BasicClassificationPerformanceEvaluator \
-s (ArffFileStream -f abalone.arff) \
-i 100000000 -f 1000000" > plresult_abalone.csv
I have an odd problem. So I am writing a program that uses Python for a simple user scripting interface. But to keep my question simple...I am trying to use PythonInterpreter.set to set a variable in the Python interpreter to a String value. But when I set it I get this exception:
LookupError: no codec search functions registered: can't find encoding
The following is my code:
package demo;
import org.python.util.PythonInterpreter;
public class Application {
public static void main(String[] args) {
PythonInterpreter pi = new PythonInterpreter();
String greeting = "Jesus Christ";
Integer times = 6;
pi.exec("actor = 'Lucy'");
pi.set("greeting", greeting);
pi.set("times", times);
pi.exec("print '%s %s' % (greeting, actor)");
pi.exec("print \"%s %s \\n\" % (greeting, actor) * times");
System.out.println("RESULT: " + pi.eval("actor == 'Lucy'"));
System.out.println("ACTOR: " + pi.get("actor"));
}
}
If you need to see the pom file for my project, I can include it, but really I just have the Jython 2.5.0 library installed. I am wondering if I needed to install something else on my system other than having maven install this library for me. I do have Python installed on this computer, and PYTHON_HOME setup in the environment variables. What am I doing wrong?
EDIT: The line:
pi.set("times", times);
...works just fine.
But...
pi.set("greeting", greeting);
does not. I imagine it has something to with times being a primitive data type and greeting being a String.
I'm trying to create a program to compare the amount of time it takes various haskell scripts to run, which will later be used to create graphs and displayed in a GUI. I've tried to create said GUI using Haskell libraries but I haven't had much luck, especially since I'm having trouble finding up to date GUI libraries for Windows. I've tried to use Java to get these results but either get errors returned or simply no result.
I've constructed a minimal example to show roughly what I'm doing at the moment:
import java.io.*;
public class TestExec {
public static void main(String[] args) {
try {
Process p = Runtime.getRuntime().exec("ghc test.hs 2 2");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
And here is the Haskell script this is calling, in this case a simple addition:
test x y = x + y
Currently there simply isn't any result stored or printed. Anyone have any ideas?
Since you're attempting to run this as an executable, you need to provide a main. In you're case it should look something like
import System.Environment
test :: Integer -> Integer -> Integer
test = (+)
main = do
[x, y] <- map read `fmap` getArgs
print $ x `test` y
This just reads the command line arguments, adds them, then prints them. Though I did something like a while ago, it's much easier to do the benchmarking/testing in Haskell, and dump the output data to a text file in a more structured format, then parse/display it in Java or whatever language you like.
This is mostly a Java question. Search for Runtime.getRuntime().exec().
On the Haskell side, you need to write a stand-alone Haskell script. The one by #jozefg is OK. You should be able to run it as
runghc /path/to/script.hs 1 2
from the command line.
Calling it from Java is no different than running any other external process in Java. In Clojure (a JVM language, I use it for brevity) I do:
user=> (def p (-> (Runtime/getRuntime) (.exec "/usr/bin/runghc /tmp/test.hs 1 2")))
#'user/p
user=> (-> p .getInputStream input-stream reader line-seq)
("3")
Please note that I use runghc to run a script (not ghc). Full paths are not necessary, but could be helpful. Your Java program can be modified this way:
--- TestExec.question.java
+++ TestExec.java
## -2,7 +2,7 ##
public class TestExec {
public static void main(String[] args) {
try {
- Process p = Runtime.getRuntime().exec("ghc test.hs 2 2");
+ Process p = Runtime.getRuntime().exec("/usr/bin/runghc /tmp/test.hs 2 2");
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()));
String line = null;
The modified version runs the Haskell script just fine. You may have to change paths to you runghc and test.hs locations.
At first to read from output you need to use OutputStreamReader(p.getOutputStream()) instead of InputStreamReader
As I said in comment such a benchmark is simply incorrect. While benchmarking one should eliminate as many side coasts as possible. The best solution is to use the criterion package. It produces nice graphical output as you desire.
Small example:
import Criterion
import Criterion.Main
import Criterion.Config
fac 1 = 1
fac n = n * (fac $ n-1)
myConfig = defaultConfig {
cfgReport = ljust "report.html"
}
main = defaultMainWith myConfig (return ()) [
bench "fac 30" $ whnf fac 30
]
After execution it produces a file "report.html" with neat interactive plots.
I just started taking the Stanford CS106a course on iTunes, but I'm running in to problems with Eclipse. Here's my code:
/*
* File: Add2Integers.java
* -----------------------
* A simple ConsoleProgram to add two integers
* and display their total.
*/
import acm.program.*;
public class Add2Integers extends ConsoleProgram {
public void run() {
/* So all y'all in the back can see! */
setFont("DejaVuSerif-BOLD-24");
println("This program adds two numbers.");
int n1 = readInt("Enter n1: ");
int n2 = readInt("Enter n2: ");
int total = n1 + n2;
println("The total is " + total + ".");
}
}
When I try to run it, I get the message that the section does not contain an applet. I think it has to do with import acm.program.
I downloaded the acm toolkit and tried adding the program.java file to my root folder, building the path, doing the same for the entire acm folder, nothing works.
I just need help getting this simple program up and running so that I can start learning.
I'm running OSX 10.8.
To run a Java application, you need a main method:
public static void main(String[] args) {
Add2Integers add2Integers = new Add2Integers();
add2Integers.run();
}
You need to start your ConsoleProgram from a main method:
public static void main(String[] args) {
new Add2Integers().start(args);
}
See: Introduction to the JTF Packages
When I try to run, I get the message that the section does not contain an applet.
That's because it isn't an applet. It's an ordinary Java application.
The examples which do graphics, are applets. But this is text-only - it extends ConsoleProgram - so it is not an applet.
I know its too late, but you dont need the main(String[] args), all you need is press the right click in your project, go to propieties, then java build path, libraries, add external Jars, and search the acm.jar file in your pc.
I am trying to get coordinates for turtles in NetLogo by using the Java API. I have managed to get the workspace loaded and have been using the following code that I made:
public static int getX(HeadlessWorkspace workspace, String playerName, int agentNum)
{
Double doubleX = null;
int xVal = 0;
try
{
xVal = doubleX.valueOf((workspace.report("[xcor] of "+playerName+" "+agentNum).toString()).trim()).intValue();
}
catch(Exception ex)
{
ex.printStackTrace();
}
return xVal;
}
However, there is one small problem. It is extremely slow when there are more than 5 turtles. When I run the Flocking code with 200 turtles, without getting the coordinates, then I get about 300 ticks in 10 seconds. When I run the code with the coordinates, then each tick takes about 3 seconds. Is there a more efficient way of achieving this?
Thanks,
Nadim
I managed to find out what the proper way should be. This is the code in the NetLogo mailing list as given by Seth Tisue.
import org.nlogo.headless.*;
import org.nlogo.api.*;
class J {
public static void main(String[] args) {
try {
HeadlessWorkspace ws = HeadlessWorkspace.newInstance();
ws.openString(org.nlogo.util.Utils.url2String("/system/empty.nlogo"));
ws.command("cro 8 [ fd 5 ]");
org.nlogo.api.Turtle turtle =(org.nlogo.api.Turtle) ws.world().turtles().agent(3);
System.out.println("[xcor] of turtle 3 = " + turtle.xcor());
ws.dispose();
}
catch(Exception ex) {
ex.printStackTrace();
}
}
}
I have reproduced the code here so it may benefit others. To see a list of what information you can get from Turtle, look at the NetLogo API documentation.
Nadim
So, you are using the Java API just so you can get the
[xcor] of "bob" 10
I am very confused.
I can tell you that your workspace.report() call above is very expensive as you are asking netlogo to parse then evaluate the expression you create, then you parse it into an integer to pass back to netlogo.
It seems it would be much easier to just store all the players in a list or map and refer to them by their index in the list. That is, I don't think you need to use the API to do what you seem to be doing.