This is my program code and it give the errors mentioned at the end of the document, when i run the program. FYI, no compilation errors occur.
Program
package javaapplication3;
/**
*
* #author ashish
*/
import org.neuroph.core.*;
import org.neuroph.core.data.DataSet;
import org.neuroph.core.data.DataSetRow;
import org.neuroph.nnet.*;
public class JavaApplication3 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// create new perceptron network
NeuralNetwork neuralNetwork = new Perceptron(2, 1);
// create training set
DataSet trainingSet =
new DataSet(2, 1);
// add training data to training set (logical OR function)
trainingSet. addRow (new DataSetRow (new double[]{0, 0},new double[{0}));
trainingSet. addRow (new DataSetRow (new double[]{0, 1},new double[{1}));
trainingSet. addRow (new DataSetRow (new double[]{1, 0},new double[{1}));
trainingSet. addRow (new DataSetRow (new double[]{1, 1},new double[{1}));
// learn the training set
neuralNetwork.learn(trainingSet);
// save the trained network into file
neuralNetwork.save("or_perceptron.nnet");
/*// load the saved network
NeuralNetwork neuralNetwork =
NeuralNetwork.createFromFile(“or_perceptron.nnet”);
// set network input
neuralNetwork.setInput(1, 1);
// calculate network
neuralNetwork.calculate();
// get network output
double[] networkOutput = neuralNetwork.getOutput();
*/ }
}
Error This is the runtime error which i cannot solve. I tried slf4j folder by adding it to the libraries but that didnt work also. Please help me.
Exception in thread "main" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at org.neuroph.core.learning.LearningRule.<init>(LearningRule.java:65)
at org.neuroph.core.learning.IterativeLearning.<init>(IterativeLearning.java:72)
at org.neuroph.core.learning.SupervisedLearning.<init>(SupervisedLearning.java:82)
at org.neuroph.nnet.learning.LMS.<init>(LMS.java:44)
at org.neuroph.nnet.learning.PerceptronLearning.<init>(PerceptronLearning.java:40)
at org.neuroph.nnet.learning.BinaryDeltaRule.<init>(BinaryDeltaRule.java:48)
at org.neuroph.nnet.Perceptron.createNetwork(Perceptron.java:114)
at org.neuroph.nnet.Perceptron.<init>(Perceptron.java:56)
at javaapplication3.JavaApplication3.main(JavaApplication3.java:24)
Caused by: java.lang.ClassNotFoundException: org.slf4j.LoggerFactory
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 9 more
C:\Users\ashish\AppData\Local\NetBeans\Cache\8.1\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
You should add the path to slf4j jar (or folder that contains .class files) to the classpath.
See here how: http://docs.oracle.com/javase/7/docs/technotes/tools/windows/classpath.html
Related
I am trying to copy the first attribute of my training dataset, and copy the corresponding from Test set for book-keeping purpose. My code compiles successfully. But I am not able to run it.
I get the following errorwhen run java WekaRF
Exception in thread "main" java.lang.NoClassDefFoundError: weka/core/converters/CSVLoader
at WekaRF.main(WekaRF.java:17)
Caused by: java.lang.ClassNotFoundException: weka.core.converters.CSVLoader
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 1 more
If I run, java -cp weka-3-8-1/weka.jar WekaRF, I get
Error: Could not find or load main class WekaRF
My code is given below
import java.io.*;
import java.util.Random;
import weka.classifiers.Evaluation;
import weka.classifiers.trees.RandomForest;
import weka.core.Instances;
import weka.filters.unsupervised.attribute.Remove;
import weka.core.converters.*;
public class WekaRF {
public static void main(String[] args) {
int percent = 60;
Instances data = null;
try {
CSVLoader loader = new CSVLoader();
loader.setSource(new File("../../rf.csv"));
data = loader.getDataSet();
} catch (Exception e) {
e.printStackTrace();
return;
}
int TrainSize = (int) Math.round(data.numInstances() * percent/ 100);
int TestSize = data.numInstances() - TrainSize;
Instances Train = new Instances(data, 0, TrainSize);
Instances Test = new Instances(data, TrainSize, TestSize);
System.out.println(Test.attribute(0).name());
Remove remove = new Remove();
String[] options = new String[2];
options[0] = "-R";
options[1] = "1";
remove.setOptions(options);
remove.setInputFormat(data2);
Test = Filter.useFilter(Test, remove);
Train.setClassIndex(Train.numAttributes() - 1);
}
}
Your classpath does not include current directory so java didn't see your WekaRF class.
Try to use java -cp .;weka-3-8-1/weka.jar WekaRF instead.
Notice dot at the start of -cp argument. It denotes current directory.
Upd: Character used to separate individual class path entries is operation system-depended. Windows uses ; and most other systems use :. The actual path separator can be retrieved by querying java.io.File::pathSeparator field.
I have a small java program that reads a given file with data and converts it to a csv file.
I've been trying to use the arrow symbols: ↑, ↓, → and ← (Alt+24 to 27) but unless the program is run from within Netbeans (Using F6), they will always come out as '?' in the resulting csv file.
I have tried using the unicodes, eg "\u2190" but it makes no difference.
Anyone know why this is happening?
As requested, here is a sample code that gives the same issue. This wont work when run using the .jar file, just creating a csv file containing '?', however running from within Netbeans works.
import java.io.FileNotFoundException;
import java.io.PrintWriter;
public class Sample {
String fileOutName = "testresult.csv";
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException {
Sample test = new Sample();
test.saveTheArrow();
}
public void saveTheArrow() {
try (PrintWriter outputStream = new PrintWriter(fileOutName)) {
outputStream.print("←");
outputStream.close();
}
catch (FileNotFoundException e) {
// Do nothing
}
}
}
new PrintWriter(fileOutName) uses the default charset of the JVM - you may have different defaults in Netbeans and in the console.
Google Sheet uses UTF_8 according to this thread so it would make sense to save your file using that character set:
Files.write(Paths.get("testresult.csv"), "←".getBytes(UTF_8));
Using the "<-" character in your editor is for sure not the desired byte 0x27.
Use
outputStream.print( new String( new byte[] { 0x27}, StandardCharsets.US_ASCII);
I'm trying to install the JWKTL library into a Java project.
JWKTL Getting started
Now I downloaded the dump file as described, and parsed it into a new directory.
My code is:
package main;
import java.io.File;
import java.util.List;
import de.tudarmstadt.ukp.jwktl.JWKTL;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryEdition;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryEntry;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryPage;
import de.tudarmstadt.ukp.jwktl.api.IWiktionaryRelation;
import de.tudarmstadt.ukp.jwktl.api.PartOfSpeech;
import de.tudarmstadt.ukp.jwktl.api.RelationType;
public class Main {
final static String PATH_TO_DUMP_FILE = "/GetWords/enwiktionary-20160601-pages-articles-multistream.xml";
final static String TARGET_DIRECTORY = "/GetWords/";
final static boolean OVERWRITE_EXISTING_FILES = true;
/**
* Simple example which parses an English dump file and prints the entries for the word <i>Wiktionary</i>
* #param args name of the dump file, output directory for parsed data, ISO language code of the Wiktionary entry language (en/de), boolean value that specifies if existing parsed data should be deleted
*/
public static void main(String[] args) throws Exception {
File dumpFile = new File(PATH_TO_DUMP_FILE);
File outputDirectory = new File(TARGET_DIRECTORY);
boolean overwriteExisting = OVERWRITE_EXISTING_FILES;
JWKTL.parseWiktionaryDump(dumpFile, outputDirectory, overwriteExisting);
IWiktionaryEdition wkt = JWKTL.openEdition(TARGET_DIRECTORY);
//TODO: Query the data you need.
// Close the database connection.
wkt.close();
}
}
But the line: IWiktionaryEdition wkt = JWKTL.openEdition(TARGET_DIRECTORY); throws an error: The method openEdition(File) in the type JWKTL is not applicable for the arguments (String), when I try to enter the dump_file as
java.io.File
the program throws the following error:
Exception in thread "main" de.tudarmstadt.ukp.jwktl.api.WiktionaryException: Unable to establish a db connection
at de.tudarmstadt.ukp.jwktl.api.entry.BerkeleyDBWiktionaryEdition.<init>(BerkeleyDBWiktionaryEdition.java:228)
at de.tudarmstadt.ukp.jwktl.api.entry.BerkeleyDBWiktionaryEdition.<init>(BerkeleyDBWiktionaryEdition.java:205)
at de.tudarmstadt.ukp.jwktl.JWKTL.openEdition(JWKTL.java:98)
at de.tudarmstadt.ukp.jwktl.JWKTL.openEdition(JWKTL.java:89)
at main.Main.main(Main.java:31)
Caused by: java.lang.IllegalArgumentException: Malformed \uxxxx encoding.
at java.util.Properties.loadConvert(Unknown Source)
at java.util.Properties.load0(Unknown Source)
at java.util.Properties.load(Unknown Source)
at com.sleepycat.je.dbi.DbConfigManager.applyFileConfig(DbConfigManager.java:388)
at com.sleepycat.je.Environment.setupHandleConfig(Environment.java:323)
at com.sleepycat.je.Environment.<init>(Environment.java:260)
at com.sleepycat.je.Environment.<init>(Environment.java:212)
at de.tudarmstadt.ukp.jwktl.api.entry.BerkeleyDBWiktionaryEdition.connect(BerkeleyDBWiktionaryEdition.java:241)
at de.tudarmstadt.ukp.jwktl.api.entry.BerkeleyDBWiktionaryEdition.<init>(BerkeleyDBWiktionaryEdition.java:224)
... 4 more
Does anybody know how to fix this?
I use Java 8 in Eclipse Mars.
I installed these libs:
jwktl-1.0.1.jar
je-6.4.25.jar
apache-ant-1.8.2.jar
Thank you!
I solved it...
It was too simple:
The sulution is:
File f = new File(TARGET_DIRECTORY);
IWiktionaryEdition wkt = JWKTL.openEdition(f);
Best regards!
I am using Rserve to access an R script through my Java project. The java code asks for a user input to enter the file location and stores in a String variable. This variable is then passes through to the R function which should read the file location perform some processes and then create a new folder and write the processed data in individual files and then print out on the console that all the files have been generated. I initially checked the R connection with a smaller version of the program and it worked. But, when I include the steps to write data to files, it shows the following error:
Enter the file path:
/home/workspace/TestR/test_file
Exception in thread "main" org.rosuda.REngine.Rserve.RserveException: eval failed, request status: error code: 127
at org.rosuda.REngine.Rserve.RConnection.eval(RConnection.java:234)
at testMain.main(testMain.java:23)
Moreover, the code also does not print any statements on the console which have to be printed via R from the Rscript. Here is the Java code:
import java.util.Scanner;
import org.rosuda.REngine.REXP;
import org.rosuda.REngine.REXPMismatchException;
import org.rosuda.REngine.REngineException;
import org.rosuda.REngine.Rserve.RConnection;
import org.rosuda.REngine.Rserve.RserveException;
public class testMain {
static String dirPath;
public static void main(String[] args) throws REXPMismatchException, REngineException {
// For user input
Scanner scanner = new Scanner(System.in );
System.out.println("Enter the file path: ");
dirPath = scanner.nextLine();
RConnection c = new RConnection();
// source the Palindrome function
c.eval("source('/home/workspace/TestR/Main.R')");
REXP valueReturned = c.eval("Main(\""+dirPath+"\")");
//c.eval("Main(\""+dirPath+"\")");
System.out.println(valueReturned.length());
}
}
And, here is the R script:
Main <- function(FILE_PATH)
{
## load libraries
library(MALDIquant)
library(MALDIquantForeign)
library(dcemriS4)
require(gridExtra) # also loads grid
library(lattice)
library(fields)
library(matlab)
library(rJava)
#Call the source files of the function which this script will use
source('/home/workspace/TestR/importAnalyzeFormat.R', echo=TRUE)
source('/home/workspace/TestR/exportFile.R', echo=TRUE)
source('/home/workspace/TestR/readRecalibratedSpectra.R', echo=TRUE)
spectralDataObjects <- importAnalyzeFormat(FILE_PATH)
p <- detectPeaks(spectralDataObjects, method="MAD", halfWindowSize=1, SNR=1)
# Assign the p to preprocessedDataObjects
preprocessedDataObjects<-p
dir.create("PreprocessedSpectra", showWarnings = FALSE)
setwd("PreprocessedSpectra")
for(i in 1:length(preprocessedDataObjects))
{
coordinateValue<-metaData(preprocessedDataObjects[[i]])
coordinates<-coordinateValue$imaging$pos
mzValues<-mass(preprocessedDataObjects[[i]])
intensityValues<-intensity(preprocessedDataObjects[[i]])
exportFile(coordinates,mzValues,intensityValues)
}
print("Files exported. Program will now terminate")
print("############################################################")
return(preprocessedDataObjects)
}
Can someone please help me?
You have an error in your script, a 127 means that there is a parse exception.
If you use something like this it will print out the error in the script.
c is the rserve connection in this case.
c.assign(".tmp.", myCode);
REXP r = c.parseAndEval("try(eval(parse(text=.tmp.)),silent=TRUE)");
if (r.inherits("try-error")) System.err.println("Error: "+r.toString())
else { // success .. }
Error code 127 means parsing exception.
Change your line:
c.eval("source('/home/workspace/TestR/Main.R')");
to
c.eval("source(\"/home/workspace/TestR/Main.R\")");
Now it is suppose to work.
I'm using R programing to analysis FFT . now I want to make Java web application/ java servlet and calling R to use Rcaller/Rcode for it . I have some reference about Calling Rcode in java application. http://code.google.com/p/rcaller/wiki/Examples
I have CSV File
for example A.csv
time Amplitude
1 0.00000 -0.021
2 0.00001 -0.024
3 0.00003 -0.013
4 0.00004 -0.023
5 0.00005 0.019
6 0.00007 -0.002
7 0.00008 -0.013
then I want to upload this file and use R Code for analysis FFT and Plot it.
Help is much appreciated! Thanks in advance, Maria
You start creating an instance of RCaller and set the current location of install Rscript.exe file. You can start with
RCaller caller = new RCaller();
Globals.detect_current_rscript();
caller.setRscriptExecutable(Globals.Rscript_current);
RCode code = new RCode();
or you can give the exact location
RCaller caller = new RCaller();
caller.setRscriptExecutable("c:\\path\\to\\Rscript.exe");
RCode code = new RCode();
Suppose your data is saved in a file mydata.csv.
code.addRCode("dat <- read.cvs(\"mydata.csv\", header=T, sep=\",\"");
then we are plotting the Amplitude
File file = code.startPlot();
code.addRCode("plot.ts(dat$Amplitude)");
code.endPlot();
and sending our code to R:
caller.setRCode(code);
caller.runOnly();
And now, the file variable holds the image data. It can be shown on screen using the code
code.showPlot(file);
For further reading, follow the blog entries on stdioe blog
When I execute this code is running but didn't show anything !!!!!!!
package test2;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.swing.ImageIcon;
import rcaller.RCaller;
import rcaller.RCode;
import rcaller.exception.RCallerExecutionException;
import rcaller.exception.RCallerParseException;
public class Test2 {
public static void main(String[] args) {
Test2 test2=new Test2();
}
private int span;
#SuppressWarnings("empty-statement")
public void test2()throws IOException{
try {
RCaller caller = new RCaller();
caller.setRscriptExecutable("C:\\Program Files\\R\\R-3.0.3\\bin\\Rscript.exe");
RCode code = new RCode();
code.addRCode("dat<-read.csv(\"NetBeansProjects\"test2\"A.csv\",header=T,sep=\",\"");
File file=code.startPlot();
code.addRCode("plot.ts(dat$Amplitude)");
code.endPlot();
caller.setRCode(code);
caller.runOnly();
ImageIcon i=code.getPlot(file);
code.showPlot(file);
} catch (RCallerExecutionException | RCallerParseException e) {
System.out.println(e.toString());
}
}
}