Convert Matlab output into ArrayList in Java - java

I'm doing sampling from log-normal distribution in Java using Matlab code (with javabuilder java).
Here is the code :
import demo2.*;
import com.mathworks.toolbox.javabuilder.*;
import java.util.*;
public class ht {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Object[] x = null; //?? What does Object[] mean?//
ArrayList th = new ArrayList();
demo y = null;
try {
y = new demo(); //the class created by Matlab builder ja//
x=y.lognorma(1, 10); //function to sample the distribution//
} catch (MWException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
What does Object[] mean in this context and how to change Object[] x into normal ArrayList in Java?

In the end of "catch" block add
th = new ArrayList(x);
or
List<Object> res = Arrays.asList(x);

Related

The infinite monkey theorem in Java [duplicate]

This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 5 years ago.
I have an exercise where are given a list of 850 basic words in English in the file basicWords.txt. I need to compose a text of 10000 words by randomly selecting words from the basic words list and write it to another file. I generated successfully the words, but I have a problem: I get an exception when the words are generated: ArrayIndexOutOfBoundsException at line 35. Also, how can I print the result into another text file?
I have a final solution for this:
package randomstring;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
*
* #author robi1
*/
public class RandomString {
public static void main(String[] args){
List<String> dictionary = readDictionaryFrom("basicWordsInEnglish.txt");
List<String> monkeyText = generateTextFrom(dictionary);
writeTextToFile(monkeyText, "final.txt");
String letters = "abcdefghijklmnopqrstuvwxyz ";
Object[] wrds = readFile("basicWordsInEnglish.txt");
int x = wrds.length;
String[] words = new String[x];
for(int i =0;i<x;i++){
words[i] = wrds[i].toString();
}
char[] let = letters.toCharArray();
String n ="";
Random r = new Random();
char t;
}
public static Object[] readFile(String name){
ArrayList<String> al = new ArrayList<String>();
FileInputStream fstream;
try {
fstream = new FileInputStream(name);
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine=br.readLine())!=null){
if(strLine.length()>4)
al.add(strLine);
}
fstream.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Object[] array = al.toArray();
return array;
}
public static List<String> readDictionaryFrom(String path) {
try {
return Files.readAllLines(new File(path).toPath());
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public RandomString(List<String> text, String path) {
try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
for(String word : text) {
file.write(word+" ");
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static List<String> generateTextFrom(List<String> words) {
Random generator = new Random();
List<String> result = new ArrayList<>();
for(int i = 0; i < 10000; i++) {
int random = generator.nextInt(words.size());
result.add(words.get(random));
}
return result;
}
public static void writeTextToFile(List<String> text, String path) {
try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
for(String word : text) {
file.write(word+" ");
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
}
Why do you not use collections? According to description this task is very easy especially when don't use bunch for, while loops and meaningless variables like n,t,j. etc.
public void main(String... args) {
List<String> dictionary = readDictionaryFrom("path to dictionary");
List<String> monkeyText = generateTextFrom(dictionary);
writeTextToFile(monkeyText, "path to destination file");
}
public List<String> readDictionaryFrom(String path) {
try {
return Files.readAllLines(new File(path).toPath());
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static void writeTextToFile(List<String> text, String path) {
try(BufferedWriter file = new BufferedWriter(new FileWriter(new File(path)))){
for(String word : text) {
file.write(word);
}
} catch(IOException e) {
throw new RuntimeException(e);
}
}
public static List<String> generateTextFrom(List<String> words) {
Random generator = new Random();
List<String> result = new ArrayList<>();
for(int i = 0; i < 10_000; i++) {
int random = generator.nextInt(words.size());
result.add(words.get(random));
}
return result;
}
Use the debugging feature of your favorite IDE (might be Eclipse), set an exception breakpoint on ArrayIndexOutOfBoundsException, run your program in debug mode.
When it hits the exception, Eclipse will halt your program. Look at your variable values, especially which array you are accessing and what value the index has, and why it got a value outside of the array size.
By the way, your code line if(n.length()>4){ cannot produce an ArrayIndexOutOfBoundsException, as there's no array indexing in that line.

xe:beanNamePicker, cant get my values from a notes view into result set

I have set up a java class that I want to use for an xe:beanNamePicker. Somehow I am not able to add a created SimplePickerResult into the result set.
package se.myorg.myproject.app;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.TreeSet;
import se.sebank.namis.utils.Utils;
import lotus.domino.Database;
import lotus.domino.Document;
import lotus.domino.DocumentCollection;
import lotus.domino.NotesException;
import lotus.domino.View;
import com.ibm.xsp.complex.ValueBindingObjectImpl;
import com.ibm.xsp.extlib.component.picker.data.INamePickerData;
import com.ibm.xsp.extlib.component.picker.data.IPickerEntry;
import com.ibm.xsp.extlib.component.picker.data.IPickerOptions;
import com.ibm.xsp.extlib.component.picker.data.IPickerResult;
import com.ibm.xsp.extlib.component.picker.data.SimplePickerResult;
public class DirectoryNamePicker extends ValueBindingObjectImpl implements INamePickerData {
private Utils utils;
Properties props;
public DirectoryNamePicker(){
//constructor
utils = new Utils();
utils.printToConsole(this.getClass().getSimpleName().toString() + " - DirectoryNamePicker() // constructor");
try {
props = utils.getDataSourceProperties();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String[] getSourceLabels () {
// TODO Auto-generated method stub
return null;
}
public boolean hasCapability (final int arg0) {
// TODO Auto-generated method stub
return false;
}
public List<IPickerEntry> loadEntries (final Object[] arg0, final String[] arg1) {
// TODO Auto-generated method stub
return null;
}
#SuppressWarnings("unchecked")
public IPickerResult readEntries (final IPickerOptions options) {
String startKey = options.getStartKey();
int count = options.getCount();
TreeSet<IPickerEntry> entries = new TreeSet<IPickerEntry>();
if (startKey != null) {
// User is performing a search
try {
entries = this.dirLookup(startKey, count);
} catch (NotesException e) {
System.err.println("Exception trying to perform directory lookup: " + e.getMessage());
e.printStackTrace();
}
}
return new SimplePickerResult((List<IPickerEntry>) entries, -1);
}
public TreeSet<IPickerEntry> dirLookup(final String search, final int limit) throws NotesException {
TreeSet<IPickerEntry> result = new TreeSet<IPickerEntry>();
String server = props.getProperty("server_notesname");
String filepath = props.getProperty("db_project_data");
Database db = utils.getSession().getDatabase(server, filepath);
View vw = db.getView("vw_all_todo_namespicker");
vw.setAutoUpdate(false);
DocumentCollection dc = vw.getAllDocumentsByKey(search, false);
int count = 0;
Document tmpdoc;
Document doc = dc.getFirstDocument();
while (doc != null && count < limit) {
String person = doc.getItemValueString("app_ProjMgrName");
IPickerEntry entry = new SimplePickerResult.Entry(person, person);
result.add(entry);
// result.add(entry does not seem to work
tmpdoc = dc.getNextDocument();
doc.recycle();
doc = tmpdoc;
count = count +1;
}
vw.setAutoUpdate(true);
return result;
}
}
Is there anyone that can tell me what I m doing wrong? I have choosen a treeset instead of an arraylist. this is because I go to a view with lots of multiple entries so I do not want duplicates and have it sorted by values.
You're casting TreeSet to (List) at the line:
return new SimplePickerResult((List<IPickerEntry>) entries, -1);
because the SimplePickerResult needs a List (it won't accept a Collection), but TreeSet does not implement List, so that cast will fail.
You'll probably have to change it back to an ArrayList.
To sort, try using java.util.Collections.sort(List list, Comparator c) with a custom comparator that compares the entry.getLabel() value, as SimplePickerResult.Entry doesn't have an in-built compare method.

Create a new instance of DB from a GUI - java

I have to implement a simple GUI to connect to MongoDB client using java driver.
This is a picture of my GUI:
As you can see, one can choose a database and then press OK to connect.
In MongoDBClient class there's a method (getDatabasesName) to detect all databases names that are present:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import com.mongodb.MongoClient;
public class MongoDBClient {
private MongoClient client;
public MongoDBClient() {
try {
this.client = new MongoClient("127.0.0.1", 27017);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public MongoClient getClient() {
return client;
}
public ArrayList<String> getDatabasesName(){
ArrayList<String> dbsName = new ArrayList<>();
List<String> dbs = this.client.getDatabaseNames();
Iterator<String> iterator = dbs.iterator();
while(iterator.hasNext()){
dbsName.add(iterator.next());
}
return dbsName;
}
}
Then, in my main I create a new instance of MongoDBClient and I pass the arrayList of databases names to the Window1 class:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
MongoDBClient mongoClient = new MongoDBClient();
ArrayList<String> dbName = mongoClient.getDatabasesName();
try {
Window1 w1 = new Window1(dbName);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
Finally, in my window one can choose a database from a group of buttons:
public void chooseDB(ArrayList<String> dbName) {
dbButton= new JRadioButton[dbName.size()];
ButtonGroup group = new ButtonGroup();
int x = 5;
for(int i = 0; i<dbName.size(); i++) {
dbButton[i] = new JRadioButton(dbName.get(i));
dbButton[i].setBounds(x, 28, 65, 15);
dbButton[i].setBackground(Color.WHITE);
this.panel.add(dbButton[i]);
x=x+100;
group.add(dbButton[i]);
}
}
After one presses OK, I want to create a new Instance of DB, but in main class not inside window1 class.

Instantiating a class in call method of T Callable Class

Basically I've got a little threading class used by ExecutorService and a fixed thread pool. Each thread instantiates my threading class and the call method is fired, works great!
However I really need to call another class (via instantiation or static means) to process & return some data within the call method, however when trying this I understandably get concurrent.ExecutionException, along with related methods.
I think it will be easier to paste all my code here, note its very rough
MainController
package com.multithreading.excutorservice;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class MainController {
private static List<String> urls;
public static void main(String[] args) {
populateList();
// futures to retrieve task results
List<Future<ArrayList>> futures = new ArrayList<Future<ArrayList>>();
// results
List<ArrayList> results = new ArrayList<ArrayList>();
// pool with 5 threads
ExecutorService exec = Executors.newFixedThreadPool(5);
// enqueue tasks
for(String url: urls) {
futures.add(exec.submit(new ThreadTask(url)));
}
// attempt to move ArrayLists within Future<ArrayList> into a normal ArrayList
for(Future<ArrayList> future: futures) {
try {
results.add(future.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// for(ArrayList<String> s: results) {
// System.out.println(s);
// }
}
private static void populateList() {
urls = new ArrayList<String>();
urls.add("http://www.google.com");
urls.add("http://www.msn.co.uk");
urls.add("http://www.yahoo.co.uk");
urls.add("http://www.google.com");
urls.add("http://www.msn.co.uk");
urls.add("http://www.yahoo.co.uk");
}
}
ThreadTask
package com.multithreading.excutorservice;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
public class ThreadTask implements Callable<ArrayList> {
private String url;
HtmlParser parseHtml;
public ThreadTask(String url) {
this.url = url;
}
public ArrayList call() {
int counter = 0;
String html = null;
try {
URL myUrl = new URL(url);
BufferedReader reader = new BufferedReader(new InputStreamReader(myUrl.openStream()));
while ((html = reader.readLine()) != null) {
//counter += inputLine.length();
html += html;
}
}
catch (Exception ex) {
System.out.println(ex.toString());
}
ArrayList<String> storeLinks = new ArrayList<String>();
HtmlParser par = new HtmlParser();
storeLinks = par.returnNewUrls(html);
// for(String s: parseHtml) {
// System.out.println(s);
// }
//returns an ArrayList of URLS which is stored in a List<Future<ArrayList>> temporarily
return storeLinks;
}
}
HtmlParser
package com.multithreading.excutorservice;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HtmlParser {
private final String regex_links = "\\s*(?i)href\\s*=\\s*(\"([^\"]*\")|'[^']*'|([^'\">\\s]+))";
private ArrayList<String> extractedUrls;
public ArrayList<String> returnNewUrls (String data) {
extractedUrls = new ArrayList<String>();
Pattern p = Pattern.compile(regex_links);
Matcher m = p.matcher(data);
System.out.println("Test");
while (m.find()) {
System.out.println("Test");
extractedUrls.add(m.group(1));
}
return getLinks();
}
//returns the links
public ArrayList getLinks() {
return extractedUrls;
}
}
You're doing some pretty weird stuff here. Multiple threads are accessing the same static extractedUrls field, and each call to returnNewUrls creates a new field. In your returnNewUrls method, create a new ArrayList which is local to the method scope. Something along the lines of:
public static ArrayList<String> returnNewUrls(String data) {
ArrayList<String> urls = new ArrayList<String>();
addStuffToUrlsList();
return urls;
}
Another thing - not a bug, but you're doing unnecessary stuff - in the call method you don't need to create a new list if you're just assigning to a variable:
ArrayList<String> parseHtml = new ArrayList<String>();
parseHtml = HtmlParser.returnNewUrls(html);
This is better:
ArrayList<String> parseHtml = HtmlParser.returnNewUrls(html);
You have several concurrent tasks, but they use the same variable HtmlParser.extractedUrls? without any synchronization. Move this variable inside the returnNewUrls method.
BTW even without concurrency, using static variables is not encouraged, especially in a case like that, where it can easily be replaced with a local variable.

Inserting records into Berkeley DB with Java

I can't seem to find sample code for constructing a Berkeley DB in Java and inserting records into it. Any samples? And I do not mean the Berkeley DB Java Edition either.
http://www.oracle.com/technology/documentation/berkeley-db/db/programmer_reference/BDB_Prog_Reference.pdf
Chapter 5
If you download db-5.0.21.NC.zip you will see plenty of samples.
Here is one that seems to do what you want
/*-
* See the file LICENSE for redistribution information.
*
* Copyright (c) 2004, 2010 Oracle and/or its affiliates. All rights reserved.
*
* $Id$
*/
// File: ExampleDatabaseLoad.java
package db.GettingStarted;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Vector;
import com.sleepycat.bind.EntryBinding;
import com.sleepycat.bind.serial.SerialBinding;
import com.sleepycat.bind.tuple.TupleBinding;
import com.sleepycat.db.DatabaseEntry;
import com.sleepycat.db.DatabaseException;
public class ExampleDatabaseLoad {
private static String myDbsPath = "./";
private static File inventoryFile = new File("./inventory.txt");
private static File vendorsFile = new File("./vendors.txt");
// DatabaseEntries used for loading records
private static DatabaseEntry theKey = new DatabaseEntry();
private static DatabaseEntry theData = new DatabaseEntry();
// Encapsulates the databases.
private static MyDbs myDbs = new MyDbs();
private static void usage() {
System.out.println("ExampleDatabaseLoad [-h <database home>]");
System.out.println(" [-i <inventory file>] [-v <vendors file>]");
System.exit(-1);
}
public static void main(String args[]) {
ExampleDatabaseLoad edl = new ExampleDatabaseLoad();
try {
edl.run(args);
} catch (DatabaseException dbe) {
System.err.println("ExampleDatabaseLoad: " + dbe.toString());
dbe.printStackTrace();
} catch (Exception e) {
System.out.println("Exception: " + e.toString());
e.printStackTrace();
} finally {
myDbs.close();
}
System.out.println("All done.");
}
private void run(String args[])
throws DatabaseException {
// Parse the arguments list
parseArgs(args);
myDbs.setup(myDbsPath);
System.out.println("loading vendors db....");
loadVendorsDb();
System.out.println("loading inventory db....");
loadInventoryDb();
}
private void loadVendorsDb()
throws DatabaseException {
// loadFile opens a flat-text file that contains our data
// and loads it into a list for us to work with. The integer
// parameter represents the number of fields expected in the
// file.
List vendors = loadFile(vendorsFile, 8);
// Now load the data into the database. The vendor's name is the
// key, and the data is a Vendor class object.
// Need a serial binding for the data
EntryBinding dataBinding =
new SerialBinding(myDbs.getClassCatalog(), Vendor.class);
for (int i = 0; i < vendors.size(); i++) {
String[] sArray = (String[])vendors.get(i);
Vendor theVendor = new Vendor();
theVendor.setVendorName(sArray[0]);
theVendor.setAddress(sArray[1]);
theVendor.setCity(sArray[2]);
theVendor.setState(sArray[3]);
theVendor.setZipcode(sArray[4]);
theVendor.setBusinessPhoneNumber(sArray[5]);
theVendor.setRepName(sArray[6]);
theVendor.setRepPhoneNumber(sArray[7]);
// The key is the vendor's name.
// ASSUMES THE VENDOR'S NAME IS UNIQUE!
String vendorName = theVendor.getVendorName();
try {
theKey = new DatabaseEntry(vendorName.getBytes("UTF-8"));
} catch (IOException willNeverOccur) {}
// Convert the Vendor object to a DatabaseEntry object
// using our SerialBinding
dataBinding.objectToEntry(theVendor, theData);
// Put it in the database.
myDbs.getVendorDB().put(null, theKey, theData);
}
}
private void loadInventoryDb()
throws DatabaseException {
// loadFile opens a flat-text file that contains our data
// and loads it into a list for us to work with. The integer
// parameter represents the number of fields expected in the
// file.
List inventoryArray = loadFile(inventoryFile, 6);
// Now load the data into the database. The item's sku is the
// key, and the data is an Inventory class object.
// Need a tuple binding for the Inventory class.
TupleBinding inventoryBinding = new InventoryBinding();
for (int i = 0; i < inventoryArray.size(); i++) {
String[] sArray = (String[])inventoryArray.get(i);
String sku = sArray[1];
try {
theKey = new DatabaseEntry(sku.getBytes("UTF-8"));
} catch (IOException willNeverOccur) {}
Inventory theInventory = new Inventory();
theInventory.setItemName(sArray[0]);
theInventory.setSku(sArray[1]);
theInventory.setVendorPrice((new Float(sArray[2])).floatValue());
theInventory.setVendorInventory((new Integer(sArray[3])).intValue());
theInventory.setCategory(sArray[4]);
theInventory.setVendor(sArray[5]);
// Place the Vendor object on the DatabaseEntry object using our
// the tuple binding we implemented in InventoryBinding.java
inventoryBinding.objectToEntry(theInventory, theData);
// Put it in the database. Note that this causes our secondary database
// to be automatically updated for us.
myDbs.getInventoryDB().put(null, theKey, theData);
}
}
private static void parseArgs(String args[]) {
for(int i = 0; i < args.length; ++i) {
if (args[i].startsWith("-")) {
switch(args[i].charAt(1)) {
case 'h':
myDbsPath = new String(args[++i]);
break;
case 'i':
inventoryFile = new File(args[++i]);
break;
case 'v':
vendorsFile = new File(args[++i]);
break;
default:
usage();
}
}
}
}
private List loadFile(File theFile, int numFields) {
List records = new ArrayList();
try {
String theLine = null;
FileInputStream fis = new FileInputStream(theFile);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while((theLine=br.readLine()) != null) {
String[] theLineArray = splitString(theLine, "#");
if (theLineArray.length != numFields) {
System.out.println("Malformed line found in " + theFile.getPath());
System.out.println("Line was: '" + theLine);
System.out.println("length found was: " + theLineArray.length);
System.exit(-1);
}
records.add(theLineArray);
}
fis.close();
} catch (FileNotFoundException e) {
System.err.println(theFile.getPath() + " does not exist.");
e.printStackTrace();
usage();
} catch (IOException e) {
System.err.println("IO Exception: " + e.toString());
e.printStackTrace();
System.exit(-1);
}
return records;
}
private static String[] splitString(String s, String delimiter) {
Vector resultVector = new Vector();
StringTokenizer tokenizer = new StringTokenizer(s, delimiter);
while (tokenizer.hasMoreTokens())
resultVector.add(tokenizer.nextToken());
String[] resultArray = new String[resultVector.size()];
resultVector.copyInto(resultArray);
return resultArray;
}
protected ExampleDatabaseLoad() {}
}
There are a number of good Getting Started Guides for Oracle Berkeley DB Java Edition. They are included in the documentation set. You'll find example code in the documentation. If you're new to Oracle Berkeley DB Java Edition that's the right place to start. There are other examples in the download package as well.
I'm the product manager for Oracle Berkeley DB, I hope this addressed your question. If not please let me know how else I can help you.

Categories

Resources