How to solve Error: Unable to initialize main class selection.ClustererExecution - java

I want to do some work with weka in java. I've added the weka-src.jar and the weka-dev-3.7.10 jar in the java build path and my code doesn't show any error before running it. After I run the code it gives me the following error
Error: Unable to initialize main class selection.ClustererExecution
Caused by: java.lang.NoClassDefFoundError: weka/filters/Filter
Here is my code:
package selection;
import weka.clusterers.ClusterEvaluation;
import weka.clusterers.SimpleKMeans;
import weka.core.Instances;
import weka.core.converters.ConverterUtils.DataSource;
import weka.filters.*;
import weka.filters.unsupervised.attribute.Remove;
public class ClustererExecution {
public static void main(String[] args) {
try {
//Loading data
Instances data = DataSource.read("/Data_Cortex_Nuclear.arff");
System.out.println("The number of attributes is: " + data.numAttributes() + " while the number of instances is: " + data.numInstances());
data.setClassIndex(data.numAttributes()-1);
System.out.println("The class index is: " + data.classIndex());
//Create copy without class attribute
Remove rem = new Remove();
rem.setAttributeIndices("" + (data.classIndex() + 1));
rem.setInputFormat(data);
Instances dataClusterer = Filter.useFilter(data, rem);
//Build clusterer
SimpleKMeans clusterer = new SimpleKMeans();
clusterer.setMaxIterations(100);
clusterer.setNumClusters(8);
clusterer.buildClusterer(dataClusterer);
//Evaluate clusterer with original data
ClusterEvaluation eval = new ClusterEvaluation();
eval.setClusterer(clusterer);
eval.evaluateClusterer(data);
System.out.println(eval.clusterResultsToString());
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Does anyone know how to fix the error?I am using eclipse if that makes any difference. Thank you!

As said in the comments below by Zastai, you added the weka jars to the build path, but the relevant weka jar needs to be in the classpath as well.

Related

Weka runtime error

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.

In Java, on Windows how do i determine if drive is local or remote drive

This is required for Windows machines only to decide whether to enforce Windows Explorer 259 path char limit. I have the following method that uses Filestore determine if partition is a windows based partition but I also need to know if local or remote drive.
Im using Java 8.
Update
I tried against root of networked drive mounted on Z:\, this actually throws an exception so that does help deterine if networked or not, but I cant see how to know that Z:\Drive is mounting \nas because if I want to find fs I need to use \nas ?
public static boolean isNTFSOrFAT32(String newPath)
{
Path root = Paths.get(newPath).getRoot();
if(root==null)
{
return false;
}
try
{
FileStore fs = Files.getFileStore(root);
if (fs.type().equals("NTFS")
|| fs.type().equals("FAT")
|| fs.type().equals("FAT32))
{
return true;
}
return false;
}
catch(IOException ex)
{
MainWindow.logger.log(Level.SEVERE, ex.getMessage(), ex);
return false;
}
}
I would prefer a proper pure Java implementation, the answer given as a possible duplicate Java: how to determine the type of drive a file is located on? is rather flaky code
Update
package com.test;
import java.nio.file.FileStore;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Iterator;
public class Fs
{
public static void main(String[] args) throws Exception
{
Path p = Paths.get("Z:\\\\").getRoot();
System.out.println(p+":"+Files.exists(p));
Iterator<FileStore> i = p.getFileSystem().getFileStores().iterator();
while(i.hasNext())
{
FileStore fs = i.next();
System.out.println("--" + fs.type() + ":" + fs.name() + ":" + fs.getTotalSpace());
}
//Files.getFileStore(p);
Path p2 = Paths.get("\\nas").getRoot();
System.out.println(p2+":"+Files.exists(p2));
FileStore fs2 = Files.getFileStore(p2);
System.out.println("--" + fs2.type() + ":" + fs2.name() + ":" + fs2.getTotalSpace());
FileStore fs = Files.getFileStore(p);
}
}
Outputs
Z:\:false
--NTFS::478854123520
--NTFS:New Volume:1000202039296
--exFAT:MacMusic:2000378920960
\:true
--NTFS::478854123520
Exception in thread "main" java.nio.file.NoSuchFileException: Z:\
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:79)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsLinkSupport.getFinalPath(WindowsLinkSupport.java:107)
at sun.nio.fs.WindowsFileStore.create(WindowsFileStore.java:83)
at sun.nio.fs.WindowsFileSystemProvider.getFileStore(WindowsFileSystemProvider.java:482)
at java.nio.file.Files.getFileStore(Files.java:1461)
at com.jthink.songkong.Fs.main(Fs.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

Program dismisses steps when running quickly (Java)

I am running a tool that runs an external Java program several times in its operation. The external tool starts with opening a JOptionPane inside a JFrame.
Here is a test script I wrote to try to solve my issue.
import java.io.File;
public class Test {
public static void main(String[] args) throws Exception {
for(int i=0; i<6; i++) {
//Thread.sleep(1000);
String toRun = "java -jar \"" + "C:\\Folder\\File.jar" + "\" " + i;
Runtime.getRuntime().exec(toRun, null, new File("C:\\Folder"));
}
}
}
When this runs, only the final run's JOptionPane (i=5) appears, but it seems that others are "trying" to appear as panes seem to be opening and immediately closing.
When I uncomment the Thread.sleep however, all of the panes open separately. If i set the sleep to 300 (0.3 seconds) about half of the panes appear, usually the first and last ones.
I would like to find a way to run all instances of the external program fully without needing to use Thread.sleep() at all, if possible.
Edit: As per requirement's I've minimalised my external program as well.
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
public class File {
static JFrame frame = new JFrame("Frame");
private static String doc1Address = "C:\\Folder\\doc1.csv";
private static String doc2Address = "C:\\Folder\\doc2.csv";
public static void main(String[] args) throws Exception {
if(args.length == 1) {
SimpleDateFormat form = new SimpleDateFormat("yyyy-MM-dd hh-mm-ss");
Date date = new Date();
String currentDate = form.format(date);
//Save Backup of doc1
String doc1BackAddress = doc1Log.substring(0, doc1Log.length()-15) + "doc1Back " + currentDate + ".csv";
Path todoc1 = Paths.get(doc1Address);
Path todoc1Back = Paths.get(doc1BackAddress);
Files.copy(todoc1, todoc1Back);
Files.setAttribute(todoc1Back, "dos:readonly", true);
//Save Backup of doc2
String doc2BackAddress = doc2Log.substring(0, doc2Log.length()-16) + "doc2Back " + currentDate + ".csv";
Path todoc2 = Paths.get(doc2Address);
Path todoc2Back = Paths.get(doc2BackAddress);
Files.copy(todoc2, todoc2Back);
Files.setAttribute(todoc2Back, "dos:readonly", true);
//Format JFrame
frame.pack();
frame.setLodoc1ionRelativeTo(null);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
JOptionPane.showMessageDialog(frame, args[0]);
frame.dispose();
}
}
}
Found my own issue; since the backup files use the format yyyy-MM-dd hh-mm-ss, and files saved during the same second result in a FileAlreadyExists Exception, meaning only the first file to finish saving allows the program to continue running.
Having a 1 second pause results in the files having different save names, so no error occurs.
Having a sub-1 second pause results in some file name overlap, but some different names too, hence some files appear.
Solution: either change the name format (i.e. include milliseconds), or include the backup functions in an if-statement, that is ignored if the file with the same time already exists.
(also; thank you #ErwinBolwidt, in being encouraged to format my question properly I realised that the issue in my code was not where I assumed it to be).

Problems reading an ini file in Java

I am having trouble using Apache commons configuration to read an ini file. I attached the imports incase I am missing something. Below is an example I found on stackoverflow, and as far as I can find, there are no other examples to look at. The problem is iniObj. Using Eclipse it is highlighted in red.
If I initialize the variable, new "HierarchicalINIConfiguration(iniFile); gets angry and wants to add a try/catch or throws... which should be no problem... but then the try/catch or throws gets angry and says "No exception of type ConfigurationException can be thrown; an exception type must be a subclass of Throwable."
Which then brought me to this question. I added the commons lang 3.1. I have commons config 1.9, commons collections 3.2.1. commons logging 1.1.1 as well. I have also tried this with commons config 1.8 and lang 2.6. Now I get a new error "Exception in thread "main" java.lang.NullPointerException at com.toolbox.dev.ReadIni.main(ReadIni.java:28)" You can see the new code below after the adjustments I made to try and resolve the errors.
My code:
import java.util.Iterator;
import java.util.Set;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.HierarchicalINIConfiguration;
import org.apache.commons.configuration.SubnodeConfiguration;
public static void main(String[] args) throws ConfigurationException {
String iniFile = "file.ini";
HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(iniFile);
// Get Section names in ini file
Set setOfSections = iniConfObj.getSections();
Iterator sectionNames = setOfSections.iterator();
while(sectionNames.hasNext()) {
String sectionName = sectionNames.next().toString();
HierarchicalINIConfiguration iniObj = null;
SubnodeConfiguration sObj = iniObj.getSection(sectionName);
Iterator it1 = sObj.getKeys();
while (it1.hasNext()) {
// Get element
Object key = it1.next();
System.out.print("Key " + key.toString() + " Value " +
sObj.getString(key.toString()) + "\n");
}
}
}
Original code from Stack Overflow:
import java.util.Iterator;
import java.util.Set;
import org.apache.commons.configuration.HierarchicalINIConfiguration;
import org.apache.commons.configuration.SubnodeConfiguration;
public class ReadIni {
public static void main(String[] args) {
String iniFile = "";
HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(iniFile);
// Get Section names in ini file
Set setOfSections = iniConfObj.getSections();
Iterator sectionNames = setOfSections.iterator();
while(sectionNames.hasNext()) {
String sectionName = sectionNames.next().toString();
SubnodeConfiguration sObj = iniObj.getSection(sectionName);
Iterator it1 = sObj.getKeys();
while (it1.hasNext()) {
// Get element
Object key = it1.next();
System.out.print("Key " + key.toString() + " Value " +
sObj.getString(key.toString()) + "\n");
}
}
Since you have already initialized the HierarchicalINIConfiguration (second line in "main") as :
HierarchicalINIConfiguration iniConfObj = new HierarchicalINIConfiguration(iniFile);
I believe you want to remove HierarchicalINIConfiguration iniObj = null; (around 5 lines down) from your code and change
SubnodeConfiguration sObj = iniObj.getSection(sectionName);
to (use iniConfObj in place of iniObj)
SubnodeConfiguration sObj = iniConfObj.getSection(sectionName);
This doesn't look promising ?
HierarchicalINIConfiguration iniObj = null;
SubnodeConfiguration sObj = iniObj.getSection(sectionName);
Is this line 28 ?
You could try JINIFile. Is a translation of the TIniFile from Delphi, but for java. It fully supports all the INI file features
https://github.com/SubZane/JIniFile

Indentation issues with Staxmate API

I am using Staxmate API to generate XML file. After reading the tutorial: http://staxmate.codehaus.org/Tutorial I tried making the changes in my code. At last I added the call
doc.setIndentation("\n ", 1, 1);
Which causes the newly generated XML file to be empty! Without this method call entire XML file gets generated as expected.
Suspecting something fishy in in project setup, I created a Test class in the same package with the code given in tutorial:
package ch.synlogic.iaf.export;
import java.io.File;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import org.codehaus.staxmate.SMOutputFactory;
import org.codehaus.staxmate.out.SMOutputDocument;
import org.codehaus.staxmate.out.SMOutputElement;
public class Test {
public static void main(String[] args) {
main("c:\\tmp\\empl.xml");
}
public static void main(String fname)
{
// 1: need output factory
SMOutputFactory outf = new SMOutputFactory(XMLOutputFactory.newInstance());
SMOutputDocument doc;
try {
doc = outf.createOutputDocument(new File(fname));
// (optional) 3: enable indentation (note spaces after backslash!)
doc.setIndentation("\n ", 1, 1);
// 4. comment regarding generation time
doc.addComment(" generated: "+new java.util.Date().toString());
SMOutputElement empl = doc.addElement("employee");
empl.addAttribute(/*namespace*/ null, "id", 123);
SMOutputElement name = empl.addElement("name");
name.addElement("first").addCharacters("Tatu");
name.addElement("last").addCharacters("Saloranta");
// 10. close the document to close elements, flush output
doc.closeRoot();
} catch (XMLStreamException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Now when I invoke the main(String) method from my code the problem still persists whereas if I just run class Test as it is it works smoothly! My code involves database initializations and some other product specific actions.
I am lost, any thoughts on how should I proceed with this?
Indentation works with Woodstox API
WstxOutputFactory factory = new WstxOutputFactory();
factory.setProperty(WstxOutputFactory.P_AUTOMATIC_EMPTY_ELEMENTS, true);
SMOutputFactory outf = new SMOutputFactory(factory);
doc = outf.createOutputDocument(fout);
doc.setIndentation("\n ", 1, 1);
Below works for me -
context.setIndentation("\r\n\t\t\t\t\t\t\t\t", 2, 1); // indent by windows lf and 1 tab per level

Categories

Resources