why JProgressBar value does not refreshed? - java

What i am trying to do is when i click a button, i copy some files from a portable drive like usb and copy those files to my local drive, then i read all csv files which i copied ealier and i put it's values in an arraylist and inject it to database, and then i can delete those files, and i want to show the process in progress bar based on process completion. so this is what i do :
void main()
{
JButton btnTransfer = new JButton("Transfer");
Image transferIMG = ImageIO.read(new File("C:\\Users\\User\\Desktop\\images\\transfer.png"));
btnTransfer.setIcon(new ImageIcon(transferIMG));
btnTransfer.setPreferredSize(new Dimension(110, 90));
btnTransfer.setOpaque(false);
btnTransfer.setContentAreaFilled(false);
btnTransfer.setBorderPainted(false);
btnTransfer.setVerticalTextPosition(SwingConstants.BOTTOM);
btnTransfer.setHorizontalTextPosition(SwingConstants.CENTER);
btnTransfer.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
File csvpath = new File(fileList1.getSelectedValue() + "\\salestablet\\report\\csv");
File htmlpath = new File(fileList1.getSelectedValue() + "\\salestablet\\report\\html");
String removepath = fileList1.getSelectedValue() + "\\salestablet\\report";
if(csvpath.listFiles().length > 0 && htmlpath.listFiles().length > 0)
{
File[] csvarr = csvpath.listFiles();
File[] htmlarr = htmlpath.listFiles();
try
{
copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath);
}
catch (IOException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
});
JPanel ButtonCont = new JPanel(new GridLayout(4, 1, 5, 0));
ButtonCont.setBackground(Color.LIGHT_GRAY);
ButtonCont.add(btnTransfer);
gui.add(ButtonCont , BorderLayout.EAST);
frame.setContentPane(gui);
frame.setExtendedState(Frame.MAXIMIZED_BOTH);
frame.setMinimumSize(new Dimension(900, 100));
frame.pack();
frame.setLocationByPlatform(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
private static void copyFileUsingStream(File[] csvsources, File[] htmlsources, String dest, String removepath) throws IOException
{
int count = 0;
int MaxCount = countprocess(csvsources, htmlsources);
progressBar = new JProgressBar(0, MaxCount);
progressBar.setStringPainted(true);
InputStream is = null;
OutputStream os = null;
String csvfolderpath = dest + "\\csv";
String htmlfolderpath = dest + "\\html";
if(!(new File(csvfolderpath)).exists())
{
(new File(csvfolderpath)).mkdirs(); //create csv folder;
}
if(!(new File(htmlfolderpath)).exists())
{
(new File(htmlfolderpath)).mkdirs(); //create csv folder;
}
for(int i= 0; i < csvsources.length; i++) //copy all csv files to csv folder
{
try
{
is = new FileInputStream(csvsources[i]);
os = new FileOutputStream(csvfolderpath + "\\" + csvsources[i].getName());
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0)
{
os.write(buffer, 0, length);
}
}
finally
{
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
is.close();
os.close();
}
}
for(int i= 0; i < htmlsources.length; i++) //copy all html, images and css to html folder
{
if(htmlsources[i].isFile())
{
try
{
is = new FileInputStream(htmlsources[i]);
os = new FileOutputStream(htmlfolderpath + "\\" + htmlsources[i].getName());
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0)
{
os.write(buffer, 0, length);
}
}
finally
{
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
is.close();
os.close();
}
}
else if(htmlsources[i].isDirectory()) //for subfolder
{
String path = dest + "\\html\\" + htmlsources[i].getName();
if(!new File(path).exists())
{
(new File(path)).mkdirs(); //create subfolder;
}
File[] arr = (new File(htmlsources[i].getAbsolutePath())).listFiles();
for(int j = 0; j < arr.length; j++)
{
if(arr[j].isFile())
{
try
{
is = new FileInputStream(arr[j]);
os = new FileOutputStream(path + "\\" + arr[j].getName());
byte[] buffer = new byte[1000000];
int length;
while ((length = is.read(buffer)) > 0)
{
os.write(buffer, 0, length);
}
}
finally
{
if(htmlsources[i].getName().contains("images"))
{
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
is.close();
os.close();
}
}
}
}
}
ArrayList<String > DBValues = new ArrayList<String>(); //read all csv files values
File f1 = new File(csvfolderpath);
for(int i = 0; i < f1.listFiles().length; i++)
{
if(f1.listFiles()[i].isFile())
{
FileReader fl = new FileReader(f1.listFiles()[i]);
BufferedReader bfr = new BufferedReader(fl);
for(int j = 0; j < 2; j++)
{
if(j == 1)
{
DBValues.add(bfr.readLine());
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
else
{
bfr.readLine();
}
}
bfr.close();
}
}
/*for(int x = 0; x < DBValues.size(); x++)
{
//System.out.println(DBValues.get(x));
}*/
//removing csv in local computer
File f2 = new File(csvfolderpath);
File[] removelist = f2.listFiles();
for(int x = 0; x < removelist.length; x++)
{
if(removelist[x].isFile())
{
removelist[x].delete();
count += 1;
progressBar.setValue((count / MaxCount) * 100);
// progressBar.repaint();
//progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
}
//removing csv in device
File f3 = new File(removepath + "\\csv");
if(f3.isDirectory())
{
removelist = f3.listFiles();
for(int y = 0; y < removelist.length; y++)
{
try
{
if(removelist[y].isFile())
{
//System.out.println(removelist[y].getName());
removelist[y].delete();
count += 1;
progressBar.setValue((count / MaxCount) * 100);
//progressBar.repaint();
// progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
//removing html and images in device
File f4 = new File(removepath + "\\html");
if(f4.isDirectory())
{
removelist = f4.listFiles();
for(int z = 0; z < removelist.length; z++)
{
try
{
if(removelist[z].isFile())
{
removelist[z].delete();
count += 1;
progressBar.setValue((count / MaxCount) * 100);
// progressBar.repaint();
// progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
else if(removelist[z].isDirectory())
{
if(removelist[z].getName().contains("images"))
{
File[] subfolder = removelist[z].listFiles();
for (int idx = 0; idx < subfolder.length; idx++)
{
if(subfolder[idx].isFile())
{
subfolder[idx].delete();
count += 1;
progressBar.setValue((count / MaxCount) * 100);
// progressBar.repaint();
// progressBar.revalidate();
progressBar.update(progressBar.getGraphics());
}
}
}
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
/* JProgressBar progressBar = new JProgressBar();
progressBar.setValue(25);
progressBar.setStringPainted(true);*/
Border border = BorderFactory.createTitledBorder("Reading...");
progressBar.setBorder(border);
gui.add(progressBar, BorderLayout.SOUTH);
gui.repaint();
gui.revalidate();
// System.out.println(count);
}
private static int countprocess(File[] csv, File[] html_image)
{
int x = 0;
int y = 0;
int z = 0;
for(int i = 0; i < csv.length; i++)
{
if(csv[i].isFile())
{
x += 1;
}
} //get total count of csv files throught loop
for(int i = 0; i < html_image.length; i++)
{
if(html_image[i].isFile())
{
y += 1;
}
else if(html_image[i].isDirectory())
{
if(html_image[i].getName().contains("images"))
{
File[] flist = html_image[i].listFiles();
for(int j = 0; j < flist.length; j++)
{
z += 1;
}
}
} //get total count of html and images files throught loop
}
return ((4*x) + (2*y) + (2*z));
}
so i tried to refresh my progress bar value by setting it's value like this
progressBar.setValue((count / MaxCount) * 100);
but somehow i can't make it to work, my progress bar does not showing it's progress like 1% 2% 3%.. 10% and so on.. instead it's only show 100% when it's process completed.. what i miss here?
note : i also have tried to set my progress bar value this way progressBar.setValue(count); still no luck.

Reviewing your whole code will take a while. But, inside your btnTransfer.addActionListener's actionPerformed function you are trying to copy stream which might take a while. Any kind of event listener is performed in event dispatch thread. Please refer to this answer for more details.
Now as a quick solution:
put your copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath); function inside a in-line thread:
new Thread()
{
public void run()
{
copyFileUsingStream(csvarr, htmlarr, txt.getText(), removepath);
}
}.start();
}
Put your progress update of JProgressBar inside SwingUtilities.invokeLater and make the (count/MaxCount) computation by casting one of them to double, as follows:
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
count += 1;
progressBar.setValue((int) (((double)count/ MaxCount) * 100));
}
});
as count is local to the copyFileUsingStream function, please try to declare it in your class context to access and change.
But SwingWorker is preferable for this kind of task.
Tutorial Resources:
Worker Threads and SwingWorker
How to use progress bars with swing worker
ProgressBar Demo with SwingWorker

You are setting a value in your progress bar to a percent complete. But the max value of your progress bar is actually the total number of items.
Instead, you need to just set your progressbar value to your current count and get rid of the calculation for the %.
Something like:
progressBar.setValue(count );
Also you should be doing your long running task in a SwingWorker thread so that you don't have to force repainting of the GUI.

Related

In Eclipse, why am I getting the error "Error: Could not find or load main class Coordinator.java"?

I have a project to run a matrix-multiplication demo via Java networking.
I am getting the following error when I run Eclipse :
'Error: Could not find or load main class Coordinator.java'
But the class I am running does have a main method. I'm not sure what is going on with this.
I include screenshot here of the Eclipse screen where I was : http://i.imgur.com/uMoUcmp.png
I realize it's most likely an eclipse/configuration error ,but anyway I include here below the Worker.java and DataIO.java code , altogether it is 5 classes, and the other 3 I put into a jsfiddle , though its not Java ( MatrixMultiple.java Connection.java Coordinator.java DataIO.java, and Worker.java - Coordinator.java is which runs the java code ; )
package socket_example_1row;
import java.io.*;
import java.util.Scanner;
import java.net.InetAddress;
import java.util.Arrays;
import matrix.*;
public class Worker {
int nodeNum;
int localPort;
Connection conn;
int dim;
int width;
int[][] a;
int[][] b;
int[][] c;
DataInputStream disCoor;
DataOutputStream dosCoor;
DataOutputStream dosLeft;
DataInputStream disRight;
public Worker(int nodeNum, int localPort) {
this.nodeNum = nodeNum;
this.localPort = localPort;
}
void configurate(String coorIP, int coorPort) {
try {
conn = new Connection(localPort);
DataIO dio = conn.connectIO(coorIP, coorPort);
dosCoor = dio.getDos();
dosCoor.writeInt(nodeNum);
dosCoor.writeUTF(InetAddress.getLocalHost().getHostAddress());
dosCoor.writeInt(localPort);
disCoor = dio.getDis();
dim = disCoor.readInt(); //get matrix dimension from coordinator
width = disCoor.readInt();
a = new int[dim][width];
b = new int[dim][width];
c = new int[dim][width];
String ipLeft = disCoor.readUTF(); //left block connection info
int portLeft = disCoor.readInt();
String ipRight = disCoor.readUTF(); //right block connection info
int portRight = disCoor.readInt();
if (nodeNum%2==0) { // Even # worker connecting manner
dosLeft = conn.connect2write(ipLeft, portLeft);
disRight = conn.accept2read();
} else { // Odd # worker connecting manner
disRight = conn.accept2read();
dosLeft = conn.connect2write(ipRight, portRight);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
System.out.println("Configuration done.");
}
// shift matrix a toward left, even # worker send before receive
void shiftLeftSend1st(int[][] mat, DataOutputStream dosL, DataInputStream disR) {
// send leftmost column
for (int i = 0; i < dim; i++) {
try {
dosLeft.writeInt(mat[i][0]);
} catch (IOException ioe) {
System.out.println("error in sending to left, row=" + i);
ioe.printStackTrace();
}
}
// local shift
for (int i = 0; i < dim; i++) {
for (int j = 1; j < width; j++) {
mat[i][j - 1] = mat[i][j];
}
}
// receive the rightmost column
for (int i = 0; i < dim; i++) {
try {
mat[i][width - 1] = disRight.readInt();
} catch (IOException ioe) {
System.out.println("error in receiving from right, row=" + i);
ioe.printStackTrace();
}
}
}
// shift matrix a toward left, odd # worker receive before send
void shiftLeftReceive1st(int[][] mat, DataOutputStream dosL, DataInputStream disR) {
int[] tempIn = new int[dim];
int[] tempOut = new int[dim];
for (int i = 0; i < dim; i++) { // receive a column from right
try {
tempIn[i] = disRight.readInt();
} catch (IOException ioe) {
System.out.println("error in receiving from right, row=" + i);
ioe.printStackTrace();
}
}
for (int i = 0; i < dim; i++) { // local shift
tempOut[i] = a[i][0];
}
for (int i = 0; i < dim; i++) {
for (int j = 1; j < width; j++) {
a[i][j - 1] = a[i][j];
}
}
for (int i = 0; i < dim; i++) {
a[i][width - 1] = tempIn[i];
}
for (int i = 0; i < dim; i++) { // send leftmost column to left node
try {
dosLeft.writeInt(tempOut[i]);
} catch (IOException ioe) {
System.out.println("error in sending left, row=" + i);
ioe.printStackTrace();
}
}
}
// shift matrix upward
void shiftUp(int[][] mat) {
// copy top row
int[] tempTop = new int[mat[0].length];
for (int j = 0; j < tempTop.length; j++) {
tempTop[j] = mat[0][j];
}
// local shift
for (int i = 0; i < mat.length-1; i++) {
for (int j = 0; j < mat[0].length; j++) {
mat[i][j] = mat[i+1][j];
}
}
for (int j = 0; j < tempTop.length; j++) {
mat[mat.length-1][j] = tempTop[j];
}
}
void compute() {
// get the block of a from coordinator
for (int i = 0; i < dim; i++) {
for (int j = 0; j <width; j++) {
try {
a[i][j] = disCoor.readInt();
} catch (IOException ioe) {
System.out.println("error: matrix a " + i + ", " + j);
ioe.printStackTrace();
}
}
}
MatrixMultiple.displayMatrix(a);
// get the block of b from coordinator
for (int i = 0; i < dim; i++) {
for (int j = 0; j <width; j++) {
try {
b[i][j] = disCoor.readInt();
} catch (IOException ioe) {
System.out.println("error: matrix b " + i + ", " + j);
ioe.printStackTrace();
}
}
}
MatrixMultiple.displayMatrix(b);
c = new int[a.length][a[0].length];
for (int i=0; i < a.length; i++) {
Arrays.fill(c[i], 0);
}
// multiplication
for (int r = 0; r < a.length; r++) {
// computer one term in c
for (int i = 0; i < a.length; i++) {
for (int j = 0; j <a[0].length; j++) {
c[i][j] = c[i][j] + a[i][j] * b[i][j];
}
}
System.out.println("Matrix c");
MatrixMultiple.displayMatrix(c, 8);
// shift matrix a toward left
if (nodeNum%2==0) { // Even # worker shifting procedure
shiftLeftSend1st(a, dosLeft, disRight);
} else { // Odd # worker shifting procedure
shiftLeftReceive1st(a, dosLeft, disRight);
}
shiftUp(b);
System.out.println("Shifted matrix a, r=" + r);
MatrixMultiple.displayMatrix(a);
System.out.println("Shifted matrix b");
MatrixMultiple.displayMatrix(b);
}
System.out.println("Matrix c");
MatrixMultiple.displayMatrix(c, 8);
}
public static void main(String[] args) {
if (args.length != 4) {
System.out.println("usage: java Worker workerID worker-port-num coordinator-ip coordinator-port-num");
}
int workerID = Integer.parseInt(args[0]);
int portNum = Integer.parseInt(args[1]);
Worker worker = new Worker(workerID, portNum);
worker.configurate(args[2], Integer.parseInt(args[3]));
worker.compute();
try {
Thread.sleep(6000);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("Press the enter key to exit.");
try {
new BufferedReader(new InputStreamReader(System.in)).readLine();
} catch (IOException ioe) {ioe.printStackTrace();}
}
}
DataIO.java
package socket_example_1row;
import java.io.*;
public class DataIO {
DataInputStream dis;
DataOutputStream dos;
public DataIO(DataInputStream dis, DataOutputStream dos) {
this.dis = dis;
this.dos = dos;
}
public DataInputStream getDis() {
return dis;
}
public void setDis(DataInputStream dis) {
this.dis = dis;
}
public DataOutputStream getDos() {
return dos;
}
public void setDos(DataOutputStream dos) {
this.dos = dos;
}
}
jsfiddle with the rest of Java code in it = Coordinator.java ; MatrixMultiple.java ; Connection.java :
http://jsfiddle.net/31y0ehep/
thanks so much
I can't really tell why you also have a main method in your Worker class, but to make sure it isn't an Eclipse related error try the following:
Right click your project;
At Run As, go to Run Configurations;
Delete every run configuration related to your project.

How to read from a persian pdf file in java

I want read a pdf file that contains Persian characters using itext . I read from this , but words are reverse. For example "ره" instead of "هر" .
I split it with "\n" and read every text in every line from end , but i think that maybe there is a better solution to read from this Pdf .
That is my code :
public class Main extends JFrame {
private static final int WIDTH = 600;
private static final int HEIGHT = 600;
/**
* by Shomeis
*/
private static final long serialVersionUID = 1L;
public Main() {
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int x = dim.width / 2 - WIDTH / 2;
int y = dim.height / 2 - HEIGHT / 2;
setBounds(x, y, WIDTH, HEIGHT);
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setMinimumSize(new Dimension(600, 600));
//
File pdf = new File("E:\\guide1.pdf");
if (!pdf.canRead() || !pdf.isFile()) {
System.err.println("cannot read input file " + pdf.getAbsolutePath());
return;
}
try {
PdfReader reader = new PdfReader(pdf.getAbsolutePath());
String page;
String areaText = "";
System.out.println(reader.getNumberOfPages());
for (int k = 1; k <= reader.getNumberOfPages(); k++) {
System.out.println(k);
page = PdfTextExtractor.getTextFromPage(reader, k);
String[] b = page.split("\n");
for (int i = 0; i < b.length; i++) {
for (int j = (b[i].length() - 1); j >= 0; j--) {
areaText += b[i].charAt(j);
}
areaText += "\n";
}
}
JTextArea text = new JTextArea(areaText);
JScrollPane sc = new JScrollPane(text);
text.setWrapStyleWord(true);
text.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
this.setContentPane(sc);
this.setVisible(true);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
new Main().setVisible(true);
}
}
You can reverse the words:
String res = strategy.getResultantText();
res = new StringBuilder(res).reverse().toString();

Binary Search, Array Index Out of Bounds Java

Firstly, I would like to say I am not asking for an answer more so advice so I can learn from this problem. Every time I run my code I get Array Index Out of Bounds on Line 254 of the ArrayOperations java file.
if (SearchKey == tempArray[middle])
I have added as many checks as I possibly can to this code and also have commented it as much as possible for your ease. Once again I am looking for advice on this not just a direct answer if possible. The Error always seems to give me the negative version of 1/2 of my data items
ex: 100,000 data items, Array Index Out of Bounds: -49,999.
import javax.swing.*;
// File-related imports
import java.io.IOException;
import java.util.Scanner;
import java.io.File;
public class ArrayOperations
{
// File Parameters
String DataFilePath;
String DataFileName;
String KeysFilePath;
String KeysFileName;
int NumberOfDataItems;
int NumberOfKeys;
int N;
int BucketHashArraySize;
int NoBuckets;
//Array
int[] OriginalArray = new int[1000000];
int[] SortedArray = new int[1000000];
int[] HashedArray = new int[2000000];
int[] BucketHashedArray = new int[2000000];
int[] KeysArray = new int[1000000];
long SSAverageAccessTime;
long SSAverageCompSuc;
long SSAverageCompFailed;
long SSNumberKeysSuc;
long SSNumberKeysFailed ;
long BSAverageAccessTime;
long BSAverageCompSuc ;
long BSAverageCompFailed;
long BSNumberKeysSuc ;
long BSNumberKeysFailed ;
long HSAverageAccessTime;
long HSAverageCompSuc ;
long HSAverageCompFailed;
long HSNumberKeysSuc ;
long HSNumberKeysFailed ;
public ArrayOperations()
{
// File Parameters
DataFilePath = null;
DataFileName = null;
KeysFilePath = null;
KeysFileName = null;
NumberOfDataItems=0;
NumberOfKeys =0;
N =0;
BucketHashArraySize = 0;
NoBuckets =0;
// Statistics
SSAverageAccessTime = 0;
SSAverageCompSuc = 0;
SSAverageCompFailed = 0;
SSNumberKeysSuc = 0;
SSNumberKeysFailed = 0;
}
public void ReadDataFile() throws IOException
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
DataFilePath = chooser.getSelectedFile().getPath();
DataFileName = chooser.getSelectedFile().getName();
}
// read data file and copy it to original array
if (DataFilePath != null)
{
try
{
int index = 0;
Scanner integerTextFile = new Scanner(new File(DataFilePath));
while (integerTextFile.hasNext())
{
// read the next integer
OriginalArray[index] = integerTextFile.nextInt();
index++;
}
// end of file detected
integerTextFile.close();
NumberOfDataItems = index;
}
catch (IOException ioe)
{
System.exit(0);
}
}
else
NumberOfDataItems = 0;
}
public void ReadKeysFile() throws IOException
{
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Keys File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
KeysFilePath = chooser.getSelectedFile().getPath();
KeysFileName = chooser.getSelectedFile().getName();
}
// read data file and copy it to original array
if (KeysFilePath != null)
{
try
{
int index = 0;
Scanner integerTextFile = new Scanner(new File(KeysFilePath));
while (integerTextFile.hasNext())
{
// read the next integer
KeysArray[index]= integerTextFile.nextInt();
index++;
}
// end of file detected
integerTextFile.close();
NumberOfKeys = index;
}
catch (IOException ioe)
{
System.exit(0);
}
}
else
NumberOfKeys = 0;
}
public void SequentialSearch()
{
SSAverageAccessTime = 0;
SSAverageCompSuc = 0;
SSAverageCompFailed = 0;
SSNumberKeysSuc = 0;
SSNumberKeysFailed = 0;
int SearchKey;
int TotalNumberOfComparisons;
long startTime = System.nanoTime();
boolean found = false;
for (int k=0; k<NumberOfKeys; k++)
{
found = false;
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
for (int d=0; d<NumberOfDataItems; d++)
{
TotalNumberOfComparisons++;
if (SearchKey == OriginalArray[d])
{
found = true;
}
if (found)break;
}
if(found)
{
SSAverageCompSuc = SSAverageCompSuc + TotalNumberOfComparisons;
SSNumberKeysSuc ++;
}
else
{
SSAverageCompFailed = SSAverageCompFailed + TotalNumberOfComparisons;
SSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
SSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
SSAverageAccessTime = 0;
if(SSNumberKeysSuc != 0)
SSAverageCompSuc = Math.round (SSAverageCompSuc / SSNumberKeysSuc) ;
else
SSAverageCompSuc = 0;
if (SSNumberKeysFailed != 0)
SSAverageCompFailed = Math.round (SSAverageCompFailed / SSNumberKeysFailed) ;
else
SSNumberKeysFailed = 0;
return;
}
public void BinarySearch()
{
// makes a temporary array the length of the number of data items we gave it int[] tempArray = new int[NumberOfDataItems];
// copies a portion of the original array (origionalArray = new int[1000000] above) that has the data inputs
// we are copying only the portion of the original array the was given the data inputs when we opened the data item .txt
for (int i = 0; i < NumberOfDataItems; i ++)
{
tempArray[i]=OriginalArray[i];
}
// takes the temporary array and sorts it
java.util.Arrays.sort(tempArray);
BSAverageAccessTime = 0;
BSAverageCompSuc = 0;
BSAverageCompFailed = 0;
BSNumberKeysSuc = 0;
BSNumberKeysFailed = 0;
int SearchKey;
int TotalNumberOfComparisons;
long startTime = System.nanoTime();
boolean found = false;
int low = 0;
int high = tempArray.length-1;
// sets the midpoint
int middle = (low-high)/2;
for(int k = 0; k<NumberOfKeys; k++)
{
SearchKey = KeysArray[k];
TotalNumberOfComparisons = 0;
for (int d=0; d< Math.log(tempArray.length -1); d++)
{
TotalNumberOfComparisons++;
// makes sure low doesn't go out of bounds
if (low < 0)
{
low = 0;
}
// make sure high doesn't go out of bounds
if(high >= tempArray.length)
{
high = tempArray.length-1;
}
// checks the midpoint against the key we are using
if (SearchKey == tempArray[middle])
{
found = true;
}
// makes sure that if the midpoint doesn't equal the key we get false
else
if (low == high && SearchKey != tempArray[middle])
{
found = false;
}
// if the key is greater than the middle we check the upper portion
else
if (SearchKey > tempArray[middle])
{
low = (middle +1);
}
// if the key is less than the middle we check the lower portion
else
if (SearchKey < tempArray[middle])
high = (middle -1);
if (found)break;
}
if(found)
{
BSAverageCompSuc = BSAverageCompSuc + TotalNumberOfComparisons;
BSNumberKeysSuc ++;
}
else
{
BSAverageCompFailed = BSAverageCompFailed + TotalNumberOfComparisons;
BSNumberKeysFailed ++;
}
}
long estimatedTime = System.nanoTime() - startTime;
if (NumberOfKeys != 0)
BSAverageAccessTime = Math.round((estimatedTime/NumberOfKeys));
else
BSAverageAccessTime = 0;
if(BSNumberKeysSuc != 0)
BSAverageCompSuc = Math.round (BSAverageCompSuc / BSNumberKeysSuc) ;
else
BSAverageCompSuc = 0;
if (BSNumberKeysFailed != 0)
BSAverageCompFailed = Math.round (BSAverageCompFailed / BSNumberKeysFailed) ;
else
BSNumberKeysFailed = 0;
return;
}
public void HashedSearch()
{
HSAverageAccessTime = 0;
HSAverageCompSuc = 0;
HSAverageCompFailed = 0;
HSNumberKeysSuc = 0;
HSNumberKeysFailed = 0;
int SearchKey;
int TotalNumberOfComparisons;
long startTime = System.nanoTime();
boolean found = false;
}
public int FindPrime()
{
return 0;
}
public void Initialize()
{
}
public void BHSearch()
{
}
}
Here is the Java GUI Code:
// GUI-related imports
import java.awt.*;
import java.awt.event.*;
// File-related imports
import java.io.IOException;
public class Project04 extends Frame implements ActionListener
{
ArrayOperations arr = new ArrayOperations();
String command = "";
public static void main(String[] args)
{
Frame frame = new Project04();
frame.setResizable(false);
frame.setSize(900,620);
frame.setVisible(true);
}
public Project04()
{
setTitle("Search Routines");
// Create Menu Bar and menu items
MenuBar mb = new MenuBar();
setMenuBar(mb);
// Create Menu Group Labeled "File"
Menu FileMenu = new Menu("File");
// Add it to Menu Bar
mb.add(FileMenu);
// Create Menu Items
// Add action Listener
// Add to "File" Menu Group
MenuItem miOpen = new MenuItem("Open");
miOpen.addActionListener(this);
FileMenu.add(miOpen);
MenuItem miExit = new MenuItem("Exit");
miExit.addActionListener(this);
FileMenu.add(miExit);
// Create Menu Group Labeled "File"
Menu SearchMenu = new Menu("Search");
// Add it to Menu Bar
mb.add(SearchMenu);
// Create Menu Items
// Add action Listener
// Add to "Search" Menu Group
MenuItem miSequentialSearch = new MenuItem("Sequential Search");
miSequentialSearch.addActionListener(this);
SearchMenu.add(miSequentialSearch);
MenuItem miBinarySearch = new MenuItem("Binary Search");
miBinarySearch.addActionListener(this);
SearchMenu.add(miBinarySearch);
MenuItem miHashedSearch = new MenuItem("Hashed Search");
miHashedSearch.addActionListener(this);
SearchMenu.add(miHashedSearch);
WindowListener l = new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{
System.exit(0);
}
public void windowActivated(WindowEvent ev)
{
repaint();
}
public void windowStateChanged(WindowEvent ev)
{
repaint();
}
};
ComponentListener k = new ComponentAdapter()
{
public void componentResized(ComponentEvent e)
{
repaint();
}
};
// register listeners
this.addWindowListener(l);
this.addComponentListener(k);
}
//******************************************************************************
// called by windows manager whenever the application window performs an action
// (select a menu item, close, resize, ....
//******************************************************************************
public void actionPerformed (ActionEvent ev)
{
// figure out which command was issued
command = ev.getActionCommand();
// take action accordingly
if("Open".equals(command))
{
try
{
arr.ReadDataFile();
arr.ReadKeysFile();
}
catch (IOException ioe)
{
System.exit(0);
}
repaint();
}
else
if("Exit".equals(command))
{
System.exit(0);
}
else
if("Sequential Search".equals(command))
{
arr.SequentialSearch();
repaint();
}
if("Binary Search".equals(command))
{
arr.BinarySearch();
repaint();
}
if("Hashed Search".equals(command))
{
arr.HashedSearch();
repaint();
}
if("Bucket Hashed Search".equals(command))
{
arr.BHSearch();
repaint();
}
}
//********************************************************
// called by repaint() to redraw the screen
//********************************************************
public void paint(Graphics g)
{
if("Open".equals(command))
{
// Acknowledge that file was opened
if (arr.DataFileName != null)
{
g.drawString("File -- "+arr.DataFileName+" -- was successfully opened", 300, 200);
g.drawString("Number of Data Items = "+Integer.toString(arr.NumberOfDataItems), 330, 250);
}
else
{
g.drawString("NO Data File is Open", 300, 200);
}
if (arr.KeysFileName != null)
{
g.drawString("File -- "+arr.KeysFileName+" -- was successfully opened", 300, 300);
g.drawString("Number of Keys = "+Integer.toString(arr.NumberOfKeys), 330, 350);
}
else
{
g.drawString("NO Keys File is Open", 300, 300);
}
return;
}
if("Sequential Search".equals(command) || "Binary Search".equals(command)||
"Hashed Search".equals(command) || "Bucket Hashed Search".equals(command) )
{
g.drawRect(100, 100, 700, 420);
g.drawString("Experiment", 135, 200);
g.drawLine(250,100,250,520);
g.drawString("Data File Attributes -- "+Integer.toString(arr.NumberOfDataItems)+" Data Items", 450, 130);
g.drawString("Key File Attributes -- "+Integer.toString(arr.NumberOfKeys)+" Keys", 450, 155);
g.drawLine(250,175,800,175);
g.drawString("Measured Criteria", 475,190 );
g.drawLine(250,215,800,215);
g.drawString("Successful Search", 410, 230);
g.drawString("Unccessful Search", 640, 230);
g.drawLine(360,245,800,245);
g.drawLine(100,310,800,310);
g.drawString("Sequential Search", 110, 325);
g.drawLine(100,340,800,340);
g.drawString("Average", 285, 260);
g.drawString("Access", 285, 275);
g.drawString("Time", 290, 290);
g.drawLine(360,215,360,520);
g.drawString("#", 400, 260);
g.drawString("Keys", 400, 275);
g.drawString("Found", 390, 290);
g.drawLine(470,245,470,520);
g.drawString("Average", 500, 260);
g.drawString("No. Of", 500, 275);
g.drawString("Comparisons", 485, 290);
g.drawLine(580,215,580,520);
g.drawString("# ", 620, 260);
g.drawString("Keys", 620, 275);
g.drawString("Not Found", 600, 290);
g.drawLine(690,245,690,520);
g.drawString("Average", 720, 260);
g.drawString("No. Of", 720, 275);
g.drawString("Comparisons", 700, 290);
g.drawString(Long.toString(arr.SSAverageAccessTime), 255, 325);
g.drawString(Long.toString(arr.SSNumberKeysSuc), 365, 325);
g.drawString(Long.toString(arr.SSAverageCompSuc), 475, 325);
g.drawString(Long.toString(arr.SSNumberKeysFailed), 585, 325);
g.drawString(Long.toString(arr.SSAverageCompFailed), 695, 325);
g.drawString("Binary Search", 110, 355);
g.drawLine(100,370,800,370);
g.drawString(Long.toString(arr.BSAverageAccessTime), 255, 355);
g.drawString(Long.toString(arr.BSNumberKeysSuc), 365, 355);
g.drawString(Long.toString(arr.BSAverageCompSuc), 475, 355);
g.drawString(Long.toString(arr.BSNumberKeysFailed), 585, 355);
g.drawString(Long.toString(arr.BSAverageCompFailed), 695, 355);
g.drawString("Hashed Search", 110, 385);
g.drawLine(100,400,800,400);
g.drawString(Long.toString(arr.HSAverageAccessTime), 255, 385);
g.drawString(Long.toString(arr.HSNumberKeysSuc), 365, 385);
g.drawString(Long.toString(arr.HSAverageCompSuc), 475, 385);
g.drawString(Long.toString(arr.HSNumberKeysFailed), 585, 385);
g.drawString(Long.toString(arr.HSAverageCompFailed), 695, 385);
// add code to display results for other searches
}
}
}
You are doing a wrong calculation
change below:
int middle = (low-high)/2;
to:
int middle = (high-low)/2;
low is always less than high so you are getting a negative number and that negative index will not exist in your array.
Although I have not checked any other possible problems or the algorithm's validity, the above is the solution to the problem you are having

Count occurrences of all 256 characters (GUI/Arrays)

I need help tweaking my code. I need to write a program that outputs the count of individual ascii characters in a txt file that the user uploads, but I'm having a lot of problems trying to get the array that I count into the GUI portion of the program that "draws" the data on the screen.
I have the output looking how I want, but I can't figure out how to get the character count up there
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.io.FileReader; // both needed
import java.io.BufferedReader;
import java.io.IOException;
public class textreader extends Frame implements ActionListener
{
String dataFilePath = null;
String dataFileName = null;
int[] counter = new int[256];
String command = "";
public static void main(String[] args)
{
Frame frame = new textreader();
frame.setResizable(true);
frame.setSize(1000,850);
frame.setVisible(true);
}
public textreader()
{
setTitle("Text File Processing");
// Menu Creation
MenuBar mn = new MenuBar();
setMenuBar(mn);
// Create "File" and add it
Menu fileMenu = new Menu("File");
mn.add(fileMenu);
// Create Menu Items, Add action Listener, Add to "File" Menu Group
// Open file
MenuItem miOpen = new MenuItem("Open");
miOpen.addActionListener(this);
fileMenu.add(miOpen);
// Process file
MenuItem miProcess = new MenuItem("Process");
miProcess.addActionListener(this);
fileMenu.add(miProcess);
// Exit program
MenuItem miExit = new MenuItem("Exit");
miExit.addActionListener(this);
fileMenu.add(miExit);
// To Terminate
WindowListener d = new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{
System.exit(0);
}
public void windowActivated(WindowEvent ev)
{
repaint();
}
public void windowStateChanged(WindowEvent ev)
{
repaint();
}
};
ComponentListener k = new ComponentAdapter()
{
public void componentResized(ComponentEvent e)
{
repaint();
}
};
// listener registry
this.addWindowListener(d);
this.addComponentListener(k);
}
public void actionPerformed (ActionEvent ev)
{
// which command was issued?
command = ev.getActionCommand();
// act
if("Open".equals(command))
{
dataFilePath = null;
dataFileName = null;
JFileChooser chooser = new JFileChooser();
chooser.setDialogType(JFileChooser.OPEN_DIALOG );
chooser.setDialogTitle("Open Data File");
int returnVal = chooser.showOpenDialog(null);
if( returnVal == JFileChooser.APPROVE_OPTION)
{
dataFilePath = chooser.getSelectedFile().getPath();
dataFileName = chooser.getSelectedFile().getName();
}
repaint();
}
else
if("Process".equals(command))
{
try
{
// Initialize
int[] aCount = new int[256];
// "Instantiate" streams
BufferedReader inputStream = new BufferedReader(new FileReader(dataFilePath));
// read the file line by line and count the characters read
String line = null;
char c = 0;
int lineLength = 0;
int charValue = 0;
while ((line = inputStream.readLine()) != null)
{
// ********* process line
for (int i = 0; i < line.length(); i++)
{
char ch = line.charAt(i);
if (ch >= 0 && ch <= 255)
{
counter[(int)ch]++;
}
else
{ // silently ignore non-ASCII characters
}
// count newline at the end
counter['\n']++;
}
}
}
catch(IOException ioe)
{
System.out.print("You want to run that by me again?");
}
repaint();
}
else
if("Exit".equals(command))
{
System.exit(0);
}
}
//********************************************************
//called by repaint() to redraw the screen
//********************************************************
public void paint(Graphics g)
{
if("Open".equals(command))
{
// Acknowledge that file was opened
if (dataFileName != null)
{
g.drawString("File -- "+dataFileName+" -- was successfully opened", 400, 400);
}
else
{
g.drawString("NO File is Open", 400, 400);
}
return;
}
else
if("Process".equals(command))
{
for(int i = 0; i < 256; i++)
{
int x = 100;
int y = 100;
g.drawString("Int", x, y);
g.drawString("Char", x+50, y);
g.drawString("Count", x+100, y);
g.drawLine(100, y+15, x+120, y+15);
y = y + 30;
int line = 0;
for(int j = 0; j < 256; j++)
{
line++;
g.drawString(Integer.toString(j), x, y);
g.drawString(Character.toString((char)j), x + 50, y); // Converts the # to a char, then to a String
// This part of the code adds a new column when the flag reaches 43
if(line == 45)
{
x = x + 150;
y = 100;
g.drawString("Int", x, y);
g.drawString("Char", x+50, y);
g.drawString("Count", x+100, y);
g.drawLine(100, y+15, x+120, y+15);
y = y + 15;
line = 0;
}
y = y+15;
}
}
return;
}
}
}
Your charValue variable appears to break your logic. You should remove it. This is sufficient:
for (int i=0; i<alphabetArray.length; i++)
alphabetArray[i] = 0; // set initial values
while ((line = inputStream.readLine()) != null) {
for(int i=0; i<line.length(); i++)
alphabetArray[(int)line.charAt(i)]++; // use the ASCII value of the character as an index
}
Your alphabet counter also seems to go out of scope. Either (1) make alphabetArray an instance variable of the class, or (2) display its contents before it goes out of scope. I think #1 is preferable.
I'd also be concerned about this line:
System.out.println(c + " : "+ char.alphabetArray[i]);
char is a datatype, and alphabetArray does not exist inside of it (and technically doesn't exist anywhere at this point since it's gone out of scope). c is also undefined. Take advantage of ASCII values! However, be careful printing non-printable characters and such. Your output will look really funky.
System.out.println((char)i + " : "+ alphabetArray[i]);
Of course, you'd still need to make alphabetArray accessible somehow.

How to resolve huge matrix multiplication performance issue in Android

I have huge .csv files (the biggest one, 72mb) that I need to load to my Android App. They contain matrices e.g [7500x1000], which I later use to multiply another one. Because their are too big to read them at one time () I'm reading line after line and perform some multiplication. I tested this on Nexus 4 and It took something about 15 minutes to do everything. When I copied the code from Android project to JAVA one(the only difference is that in Android i'm using Bitmap and in JAVA BufferedImage) and ran this as java application it took few seconds. Do you have any idea why is so and how to shorten this time? Here Is my code:
Android:
public class NetworkThread extends Thread {
private static boolean threadIsWorking = false;
private Context context;
private SQLiteHandler sql;
private static NetworkThread REFERENCE = null;
private String w1 = "w1.csv";
private String w2 = "w2.csv";
private String w3 = "w3.csv";
private String w4 = "w4.csv";
String NEURON_PATH = "/data/data/com.ZPIProject/neuronFiles/";
public static NetworkThread getInstance(Context context, SQLiteHandler sql) {
if (REFERENCE == null)
REFERENCE = new NetworkThread(context, sql);
return REFERENCE;
}
private NetworkThread(Context context, SQLiteHandler sql) {
this.context = context;
this.sql = sql;
}
#Override
public void start() {
if (!threadIsWorking) {
threadIsWorking = true;
try {
Log.i("MATRIX", "THREAD ID: " + Thread.currentThread().getId());
Bitmap bit = BitmapFactory.decodeResource(context.getResources(), R.drawable.aparat_small);
double[] imageInfo = ImageUtils.getImageInfo(bit);
copyNeuronWeightsToMemoryOnPhone();
double[] m4 = multiplyImageWithNeuronWeights(imageInfo);
List<WeightWithId> best10 = findBest10Results(m4);
for (int i = 0; i < best10.size(); i++) {
Log.e("IDS", best10.get(i).getId() + "");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
private List<WeightWithId> findBest10Results(double[] m4) throws SQLException, CloneNotSupportedException {
List<WeightWithId> best10 = new ArrayList<WeightWithId>(20);
for (int j = 0; j < 19; j++) {
Map<Integer, double[]> readDescriptions = sql.getDescriptionForShoeId(j * 100, j * 100 + 100);
List<WeightWithId> distances = new ArrayList<WeightWithId>(100);
for (Integer i : readDescriptions.keySet()) {
double dist = dist(m4, readDescriptions.get(i));
distances.add(new WeightWithId(i, dist));
}
Collections.sort(distances);
for (int i = 0; i < 10; i++) {
best10.add(distances.get(i).clone());
}
Collections.sort(best10);
if (best10.size() > 10) {
for (int i = 10; i < best10.size(); i++) {
best10.remove(i);
}
}
}
return best10;
}
private double[] multiplyImageWithNeuronWeights(double[] imageInfo) throws IOException {
Log.i("MATRIX MULTIPLY", "M1");
double[] m1 = MatrixMaker.multiplyMatrixWithCsvMatrix(NEURON_PATH + w1, imageInfo, 1000, false);
Log.i("MATRIX MULTIPLY", "M2");
double[] m2 = MatrixMaker.multiplyMatrixWithCsvMatrix(NEURON_PATH + w2, m1, 500, false);
Log.i("MATRIX MULTIPLY", "M3");
double[] m3 = MatrixMaker.multiplyMatrixWithCsvMatrix(NEURON_PATH + w3, m2, 250, false);
Log.i("MATRIX MULTIPLY", "M4");
return MatrixMaker.multiplyMatrixWithCsvMatrix(NEURON_PATH + w4, m3, 50, true);
}
private void copyNeuronWeightsToMemoryOnPhone() throws IOException {
Log.i("MATRIX COPY", "W1");
CopyUtils.copyFileIntoDevice(NEURON_PATH, w1, context);
Log.i("MATRIX COPY", "W2");
CopyUtils.copyFileIntoDevice(NEURON_PATH, w2, context);
Log.i("MATRIX COPY", "W3");
CopyUtils.copyFileIntoDevice(NEURON_PATH, w3, context);
Log.i("MATRIX COPY", "W4");
CopyUtils.copyFileIntoDevice(NEURON_PATH, w4, context);
}
private double dist(double[] a, double[] b) {
double result = 0;
for (int i = 0; i < a.length; i++)
result += (a[i] - b[i]) * (a[i] - b[i]);
return result;
}
}
Matrix Operations:
public class MatrixMaker {
public static double[] multiplyImageInfoWithCsvMatrix(String csvFilePath, double[] imageInfo, int expectedSize, boolean lastOne) throws IOException {
InputStream inputStream = new FileInputStream(new File(csvFilePath));
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
//counter - to which position calculated value should be setted
int counter = 0;
//result array
double[] multipliedImageInfoWithCsvMatrix = new double[expectedSize + 1];
//declaration of array for read line (parsed into double array)
double[] singleLineFromCsv = new double[imageInfo.length];
while ((line = bufferedReader.readLine()) != null) {
//splitting and parsing values from read line
String[] splitted = line.split(",");
for (int i = 0; i < splitted.length; i++) {
singleLineFromCsv[i] = Double.valueOf(splitted[i]);
}
//multiply imageInfo array with single row from csv file
multipliedImageInfoWithCsvMatrix[counter] = multiplyOneRow(imageInfo, singleLineFromCsv);
//ugly flag 'lastOne' needed to other business case
if (!lastOne) {
multipliedImageInfoWithCsvMatrix[counter] = 1d / (1 + Math.exp(-multipliedImageInfoWithCsvMatrix[counter]));
}
counter++;
//logging progress
if (counter % 100 == 0)
Log.i("MULTIPLY PROGRESS", counter + " " + System.currentTimeMillis());
}
if (!lastOne)
multipliedImageInfoWithCsvMatrix[expectedSize] = 1d;
bufferedReader.close();
inputStream.close();
return multipliedImageInfoWithCsvMatrix;
}
private static double multiplyOneRow(double first[], double second[]) {
double result = 0d;
for (int i = 0; i < first.length; i++) {
result += first[i] * second[i];
}
return result;
}
}
onCreate in one of Activity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
final SQLiteHandler sql = new SQLiteHandler(this);
sql.init();
NetworkThread.getInstance(this, sql).start();
} catch (IOException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
JAVA:
Multiply equivalent of Matrix Maker
import java.io.*;
public class Multiply {
public static double[] multiplyMatrixWithCsvMatrix(String csvFilePath, double[] imageInfo,
int expectedSize, boolean lastOne) throws IOException {
InputStream inputStream = new FileInputStream(new File(csvFilePath));
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
// counter - to which position calculated value should be setted
int counter = 0;
// result array
double[] multipliedImageInfoWithCsvMatrix = new double[expectedSize + 1];
// declaration of array for read line (parsed into double array)
double[] singleLineFromCsv = new double[imageInfo.length];
while ((line = bufferedReader.readLine()) != null) {
// splitting and parsing values from read line
String[] splitted = line.split(",");
for (int i = 0; i < splitted.length; i++) {
singleLineFromCsv[i] = Double.valueOf(splitted[i]);
}
// multiply imageInfo array with single row from csv file
multipliedImageInfoWithCsvMatrix[counter] = multiplyOneRow(imageInfo, singleLineFromCsv);
// ugly flag 'lastOne' needed to other business case
if (!lastOne) {
multipliedImageInfoWithCsvMatrix[counter] = 1d / (1 + Math
.exp(-multipliedImageInfoWithCsvMatrix[counter]));
}
counter++;
// logging progress
if (counter % 100 == 0)
System.out.println(counter + " " + System.currentTimeMillis());
}
if (!lastOne)
multipliedImageInfoWithCsvMatrix[expectedSize] = 1d;
bufferedReader.close();
inputStream.close();
return multipliedImageInfoWithCsvMatrix;
}
private static double multiplyOneRow(double first[], double second[]) {
double result = 0d;
for (int i = 0; i < first.length; i++) {
result += first[i] * second[i];
}
return result;
}
}
Executable class
public class MRunner {
private static final int RED_INDEX = 0;
private static final int GREEN_INDEX = 2500;
private static final int BLUE_INDEX = 5000;
private static final String w1 = "w1.csv";
private static final String NEURON_PATH = "C:\\Users\\Vortim\\Desktop\\";
public static void main(String[] args) {
new Thread(new Runnable() {
#Override
public void run() {
try {
Multiply.multiplyMatrixWithCsvMatrix(NEURON_PATH + w1, getImageInfo(ImageIO
.read(new File("C:\\Users\\Vortim\\git\\MatrixMaker\\but.png"))), 1000,
false);
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
public static double[] getImageInfo(BufferedImage source) {
double[] result = new double[7501];
int width = source.getWidth();
int height = source.getHeight();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
if (x == 0) {
result[y + RED_INDEX] = 255d;
result[y + GREEN_INDEX] = 255d;
result[y + BLUE_INDEX] = 255d;
} else if (y == 0) {
result[x * 50 + RED_INDEX] = 255d;
result[x * 50 + GREEN_INDEX] = 255d;
result[x * 50 + BLUE_INDEX] = 255d;
} else {
int pixel = source.getRGB(x, y);
double r = (pixel) >> 16 & 0xff;
double g = (pixel) >> 8 & 0xff;
double b = (pixel) & 0xff;
result[x * y + RED_INDEX] = 1d - (r / 255d);
result[x * y + GREEN_INDEX] = 1d - (g / 255d);
result[x * y + BLUE_INDEX] = 1d - (b / 255d);
}
}
}
result[7500] = 1;
return result;
}
}

Categories