Adding Object[] method to main() - user-interface

I am trying to pass this method through my main() function but The loadMap already has the bufferreader so I am trying to use that rather than creating my own new buffer reader. How can I do this?
public static void main(String args[]) {
//throw exceptions here if args is empty
filename = args[0];
System.out.println(MapIO.loadMap(filename)[0]);
System.out.println(MapIO.loadMap(filename)[1]);
if (args.length < 1) {
System.err.println("Usage:\n" +"java CrawlGui mapname");
System.exit(1);
}
List<String> names=new LinkedList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(new
File(filename)))) {
String line;
while ((line = reader.readLine()) != null)
names.add(line);
System.out.println(names);
} catch (IOException e) {
e.printStackTrace();
}
MapIO.loadMap(filename);
launch(args);
}
/** Read information from a file created with saveMap
* #param filename Filename to read from
* #return null if unsucessful. If successful, an array of two Objects.
[0] being the Player object (if found) and
[1] being the start room.
* #detail. Do not add the player to the room they appear in, the caller
will be responsible for placing the player in the start room.
*/
public static Object[] loadMap(String filename) {
Player player = null;
try {
BufferedReader bf = new BufferedReader(
new FileReader(filename));
String line = bf.readLine();
int idcap = Integer.parseInt(line);
Room[] rooms = new Room[idcap];
for (int i = 0; i < idcap; ++i) {
line = bf.readLine();
if (line == null) {
return null;
}
rooms[i] = new Room(line);
}
for (int i = 0; i < idcap; ++i) { // for each room set up exits
line = bf.readLine();
int exitcount=Integer.parseInt(line);
for (int j=0; j < exitcount; ++j) {
line = bf.readLine();
if (line == null) {
return null;
}
int pos = line.indexOf(' ');
if (pos < 0) {
return null;
}
int target = Integer.parseInt(line.substring(0,pos));
String exname = line.substring(pos+1);
try {
rooms[i].addExit(exname, rooms[target]);
} catch (ExitExistsException e) {
return null;
} catch (NullRoomException e) {
return null;
}
}
}
for (int i = 0;i<idcap;++i) {
line = bf.readLine();
int itemcount = Integer.parseInt(line);
for (int j = 0; j < itemcount; ++j) {
line = bf.readLine();
if (line == null) {
return null;
}
Thing t = decodeThing(line, rooms[0]);
if (t == null) {
return null;
}
if (t instanceof Player) { // we don't add
player = (Player)t; // players to rooms
} else {
rooms[i].enter(t);
}
}
}
Object[] res = new Object[2];
res[0] = player;
res[1] = rooms[0];
return res;
} catch (IOException ex) {
return null;
} catch (IndexOutOfBoundsException ex) {
return null;
} catch (NumberFormatException nfe) {
return null;
}
}

You shouldn't do anything in main() other than call launch(). Move all the other startup code to your start() method. You can get the content of the args array using getParameters().getRaw():
#Override
public void start(Stage primaryStage) {
//throw exceptions here if args is empty
filename = getParameters().getRaw().get(0);
System.out.println(MapIO.loadMap(filename)[0]);
System.out.println(MapIO.loadMap(filename)[1]);
if (args.length < 1) {
System.err.println("Usage:\n" +"java CrawlGui mapname");
System.exit(1);
}
List<String> names=new LinkedList<String>();
try (BufferedReader reader = new BufferedReader(new FileReader(new
File(filename)))) {
String line;
while ((line = reader.readLine()) != null)
names.add(line);
System.out.println(names);
} catch (IOException e) {
e.printStackTrace();
}
Object[] whateverThisThingIs = MapIO.loadMap(filename);
// Now you have access to everything you need, at the point where you need it.
// existing start() code goes here...
}
public static void main(String args[]) {
launch(args);
}

Related

NullException on Bitmap ,bitmaps is getting null value

I'm trying to get multiple images from the gallery, show it in >Recyclerview, and sending it to server but showing this error >Here's my code to write the images to file,the error is at the >initialization of inputstream
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d("Data any THING", String.valueOf(data));
if (requestCode == ImagePicker.IMAGE_PICKER_REQUEST_CODE && resultCode == RESULT_OK) {
List<String> mPaths = data.getStringArrayListExtra(ImagePicker.EXTRA_IMAGE_PATH);
Log.d("mPaths MainActivity", String.valueOf(mPaths));
for (int i = 0; i < mPaths.size(); i++) {
files.add(new File(mPaths.get(i)));
}
if (inputStream==null) {
for (int i = 0; i < files.size(); i++) {
try {
inputStream = getContentResolver().openInputStream(Uri.fromFile( files.get(i)));
Toast.makeText(this, "Inputstream"+String.valueOf(inputStream), Toast.LENGTH_SHORT).show();
bitmaps = BitmapFactory.decodeStream(inputStream);
Log.e("File", String.valueOf(files));
Log.e("stream", String.valueOf(inputStream));
editText.setText(String.valueOf(files)+String.valueOf(inputStream));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Log.d("DATASSSSSSSSSSSTTTT", String.valueOf(data.getData()));
Log.e("IMages From Stream", String.valueOf(bitmaps));
Log.d("Images from Steam", String.valueOf(bitmaps));
recyclerAdapter.fileMOthod(files);
if (bitmaps != null) {
resizeIMagestoAdapter();
imageResize(bitmaps);
} else {
}
}
}
}
}
The files array has only indices 0 to files.size()-1, but your i variable goes from 0 to files.size() in the loop:
for (int i = 0; i < files.size()+1; i++)
Therefore, files.get(i) fails with the IndexOutOfBoundsException.
Index: 2, Size: 2 means that the size of files is 2 (it has only indices 0 and 1), but you are trying to access index 2.

Move TreeNode to the top, up, down and to the bottom C#

I have little knowledge on tree view. I want to be able to move the tree node to the top and to move up the tree node.
-Fruits
-Apples
-Oranges
-Bananas
-Watermelon
Below is the code i have try to implement.
First, i move the watermelon to the top, it work fine. Next when i try to move up Bananas, the index of the bananas will show -1. Is there anything else i do wrongly?
private void moveTopToolStripMenuItem_Click(object sender, EventArgs e)
{
TreeNode tv = new TreeNode();
TreeNode selectedNodeToMove = new TreeNode();
try
{
TreeNode parent = treeView.SelectedNode.Parent;
selectedNodeToMove = treeView.SelectedNode;
if (parent != null)
{
parent.Nodes.Remove(treeView.SelectedNode);
parent.Nodes[0] = selectedNodeToMove;
}
}
catch (Exception ex)
{
}
}
private void moveUpToolStripMenuItem_Click(object sender, EventArgs e)
{
TreeNode tv = new TreeNode();
TreeNode selectedNodeToMove = new TreeNode();
try
{
TreeNode parent = treeView.SelectedNode.Parent;
selectedNodeToMove = treeView.SelectedNode;
if (parent != null)
{
int index = parent.Nodes.IndexOf(treeView.SelectedNode);
if (index > 0)
{
tv = parent.Nodes[index - 1];
parent.Nodes.Remove(treeView.SelectedNode);
parent.Nodes.Remove(tv);
parent.Nodes.Insert(index - 1, selectedNodeToMove);
parent.Nodes.Insert(index, tv);
}
}
}
catch (Exception ex)
{
}
}
i manage to come out with the answer and it is working. Just want to share if anyone is looking on this.
private void moveTopToolStripMenuItem_Click(object sender, EventArgs e)
{
TreeNode selectedNodeToMove = new TreeNode();
try
{
int index = -1;
TreeNode parent = treeView.SelectedNode.Parent;
TreeNode node= this.treeView.SelectedNode.Clone() as TreeNode;
if (parent != null)
{
for (int j = 0; j < this.treeView.SelectedNode.Parent.Nodes.Count; j++)
{
if (this.treeView.SelectedNode == this.treeView.SelectedNode.Parent.Nodes[j])
{
index = j;
break;
}
}
this.treeView.BeginUpdate();
this.treeView.SelectedNode.Parent.Nodes.Insert(0, node);
this.treeView.SelectedNode.Parent.Nodes.RemoveAt(index + 1);
this.treeView.EndUpdate();
this.treeView.SelectedNode = node;
this.treeView.Select();
}
}
catch (Exception ex)
{
}
}
private void moveUpToolStripMenuItem_Click(object sender, EventArgs e)
{
TreeNode tv = new TreeNode();
TreeNode selectedNodeToMove = new TreeNode();
try
{
TreeNode parent= treeView.SelectedNode.Parent;
TreeNode node= this.treeView.SelectedNode.Clone() as TreeNode;
if (parent != null)
{
int index = -1;
for (int j = 0; j < parent.Nodes.Count; j++)
{
if (this.treeView.SelectedNode == parent.Nodes[j])
{
index = j;
break;
}
}
this.treeView_.BeginUpdate();
this.treeView.SelectedNode.Parent.Nodes.Insert(index - 1, node);
this.treeView.SelectedNode.Parent.Nodes.RemoveAt(index + 1);
this.treeView.EndUpdate();
this.treeView.SelectedNode = node;
this.treeView.Select();
}
catch (Exception ex)
{
}
}
private void moveDownToolStripMenuItem_Click(object sender, EventArgs e)
{
TreeNode tv = new TreeNode();
TreeNode selectedNodeToMove = new TreeNode();
try
{
TreeNode parent = treeView.SelectedNode.Parent;
TreeNode node = this.treeView.SelectedNode.Clone() as TreeNode;
selectedNodeToMove = treeView.SelectedNode;
if (parent != null)
{
int index = -1;
for (int j = 0; j < parent.Nodes.Count; j++)
{
if (this.treeView.SelectedNode == parent.Nodes[j])
{
index = j;
break;
}
}
this.treeView.BeginUpdate();
this.treeView.SelectedNode.Parent.Nodes.RemoveAt(index);
this.treeView.SelectedNode.Parent.Nodes.Insert(index + 1, node);
this.treeView.EndUpdate();
this.treeView.SelectedNode = node;
this.treeView.Select();
}
catch (Exception ex)
{
}
}
private void moveBottomToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
TreeNode parent = treeView.SelectedNode.Parent;
TreeNode node = this.treeView.SelectedNode.Clone() as TreeNode;
if (parent != null)
{
int index = -1;
for (int j = 0; j < parent.Nodes.Count; j++)
{
if (this.treeView.SelectedNode == parent.Nodes[j])
{
index = j;
break;
}
}
if (index != parent.Nodes.Count - 1)
{
this.treeView.BeginUpdate();
this.treeView.SelectedNode.Parent.Nodes.Insert(parent.Nodes.Count, node);
this.treeView.SelectedNode.Parent.Nodes.RemoveAt(index);
this.treeView.EndUpdate();
this.treeView.SelectedNode = node;
this.treeView.Select();
}
catch (Exception ex)
{
}
}

Optimizations for Solitaire SPOJ

Problem Code: SOLIT
Problem Link: http://www.spoj.com/problems/SOLIT/
I tried solving the SPOJ problem Solitaire. However, I ended up with a TLE (Time Limit Exceeded). My current solution is taking around 2 seconds to execute. I have no idea how to optimize my solution further in order to reduce the time. So, I would be grateful for any help in this regard.
Link to my solution: https://ideone.com/eySI91
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
class Solitaire {
enum Direction {
TOP, RIGHT, DOWN, LEFT;
};
static class Piece {
int row, col;
public Piece(int row, int col) {
this.row = row;
this.col = col;
}
#Override
public boolean equals(Object o)
{
if (!(o instanceof Piece))
return false;
Piece p = (Piece)o;
return (row==p.row && col==p.col);
}
#Override
public int hashCode()
{
return (row*10 + col)%11;
}
}
static class State {
HashSet<Piece> pieces;
public State() {
pieces = new HashSet<>(11);
}
public State(State s) {
pieces = new HashSet<>(11);
for (Piece p: s.pieces)
pieces.add(new Piece(p.row, p.col));
}
#Override
public boolean equals(Object o) {
if (!(o instanceof State))
return false;
State s = (State) o;
if (pieces.size()!=s.pieces.size())
return false;
for (Piece p: pieces)
{
if (!s.pieces.contains(p))
return false;
}
return true;
}
#Override
public int hashCode() {
final int MOD = 1000000007;
long code = 0;
for (Piece p: pieces) {
code = (code + p.hashCode())%MOD;
}
return (int) code;
}
#Override
public String toString()
{
String res = "";
for (Piece p: pieces)
res = res + " (" + p.row + ", " + p.col + ")";
return res;
}
public int getCloseness(State s)
{
int medianRow=0, medianCol=0, sMedianRow=0, sMedianCol=0;
for (Piece p: pieces)
{
medianRow+=p.row;
medianCol+=p.col;
}
medianRow/=4;
medianCol/=4;
for (Piece p: s.pieces)
{
sMedianRow+=p.row;
sMedianCol+=p.col;
}
sMedianRow/=4;
sMedianCol/=4;
int closeness = ((sMedianCol-medianCol)*(sMedianCol-medianCol)) + ((sMedianRow-medianRow)*(sMedianRow-medianRow));
return closeness;
}
}
static State makeMove(State curr, Piece piece, Direction dir, HashSet<State> visited) {
if (dir == Direction.TOP) {
if (piece.row==1)
return null;
if (curr.pieces.contains(new Piece(piece.row-1, piece.col)))
{
if (piece.row==2 || curr.pieces.contains(new Piece(piece.row-2, piece.col)))
return null;
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row-2, piece.col));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row-1, piece.col));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else if (dir == Direction.RIGHT) {
if (piece.col==8)
return null;
if (curr.pieces.contains(new Piece(piece.row, piece.col+1)))
{
if (piece.col==7 || curr.pieces.contains(new Piece(piece.row, piece.col+2)))
return null;
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row, piece.col+2));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row, piece.col+1));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else if (dir == Direction.DOWN) {
if (piece.row==8)
return null;
if (curr.pieces.contains(new Piece(piece.row+1, piece.col)))
{
if (piece.row==7 || curr.pieces.contains(new Piece(piece.row+2, piece.col)))
return null;
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row+2, piece.col));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row+1, piece.col));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else // dir == Direction.LEFT
{
if (piece.col==1)
return null;
if (curr.pieces.contains(new Piece(piece.row, piece.col-1)))
{
if(piece.col==2 || curr.pieces.contains(new Piece(piece.row, piece.col-2)))
return null;
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row, piece.col-2));
if (visited.contains(newState))
return null;
else
return newState;
}
}
else
{
State newState = new State(curr);
newState.pieces.remove(new Piece(piece.row, piece.col));
newState.pieces.add(new Piece(piece.row, piece.col-1));
if (visited.contains(newState))
return null;
else
return newState;
}
}
}
static boolean isReachableInEightMoves(State src, State target) {
Queue<State> q = new LinkedList<>();
HashSet<State> visited = new HashSet<>();
int closeness = src.getCloseness(target);
q.add(src);
int moves = 0;
while (!q.isEmpty() && moves <= 8) {
int levelNodes = q.size();
for (int i = 0; i < levelNodes; i++) {
State curr = q.remove();
if (curr.equals(target))
return true;
if (moves==8)
continue;
visited.add(curr);
for (Piece p: curr.pieces)
{
State newState = makeMove(curr, p, Direction.TOP, visited);
if (newState!=null)
{
int newCloseness = newState.getCloseness(target);
if (closeness>=newCloseness)
{
closeness=newCloseness;
visited.add(newState);
q.add(newState);
}
}
newState = makeMove(curr, p, Direction.RIGHT, visited);
if (newState!=null)
{
int newCloseness = newState.getCloseness(target);
if (closeness>=newCloseness)
{
closeness=newCloseness;
visited.add(newState);
q.add(newState);
}
}
newState = makeMove(curr, p, Direction.DOWN, visited);
if (newState!=null)
{
int newCloseness = newState.getCloseness(target);
if (closeness>=newCloseness)
{
closeness=newCloseness;
visited.add(newState);
q.add(newState);
}
}
newState = makeMove(curr, p, Direction.LEFT, visited);
if (newState!=null)
{
int newCloseness = newState.getCloseness(target);
if (closeness>=newCloseness)
{
closeness=newCloseness;
visited.add(newState);
q.add(newState);
}
}
}
}
moves++;
}
return false;
}
public static void main(String[] args) throws IOException {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(FileDescriptor.out), "ASCII"));
CustomScanner sc = new CustomScanner();
int t = sc.nextInt();
long start = System.currentTimeMillis();
while (t-- > 0) {
State src = new State(), target = new State();
for (int i = 0; i < 4; i++) {
src.pieces.add(new Piece(sc.nextInt(), sc.nextInt()));
}
for (int i = 0; i < 4; i++) {
target.pieces.add(new Piece(sc.nextInt(), sc.nextInt()));
}
if (isReachableInEightMoves(src, target))
out.write("YES");
else
out.write("NO");
out.newLine();
}
long end = System.currentTimeMillis();
out.write("Time to execute = " + Double.toString((end-start)/1000d));
out.flush();
}
static class CustomScanner {
BufferedReader br;
StringTokenizer st;
public CustomScanner() {
br = new BufferedReader(new InputStreamReader(System.in));
}
private String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
public int nextInt() {
return Integer.parseInt(next());
}
public long nextLong() {
return Long.parseLong(next());
}
public double nextDouble() {
return Double.parseDouble(next());
}
public String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}
Some notes regarding the implementation:-
I am just doing a simple bfs traversal where each node is a state of
the board.
I have defined a function called getCloseness() which measures the closeness of two different states. It is basically the square of the distance between the centroids of the two states. A centroid of a state is the sum of all row values of each piece divided by 4 and the same for columns.
After calculating each state, I am checking if the closeness of this new state is lesser than or equal to the current closeness.
If it is not closer, then I will simply discard the new discovered state.
If it is closer, then I will update the closeness value and insert this new state into the Queue for future processing.
This process terminates when either the queue becomes empty or a state is discovered which is same as the target state.
The above approach takes approximately 1-3 seconds for cases where a minimum of 7 moves are required. I would be grateful if you can tell me how I can further optimize this solution.
The expected time according to the problem is 0.896s.

WritableByteChannel into BLOB

I have to extend an existing source code. I have this method:
public final int copyStreams(InputStream in, OutputStream out, long sizeLimit) throws IOException
{
int byteCount = 0;
IOException error = null;
long totalBytesRead = 0;
try
{
byte[] buffer = new byte[BYTE_BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = in.read(buffer)) != -1)
{
// We are able to abort the copy immediately upon limit violation.
totalBytesRead += bytesRead;
if (sizeLimit > 0 && totalBytesRead > sizeLimit)
{
StringBuilder msg = new StringBuilder();
msg.append("Content size violation, limit = ")
.append(sizeLimit);
throw new ContentLimitViolationException(msg.toString());
}
out.write(buffer, 0, bytesRead);
byteCount += bytesRead;
}
out.flush();
}
finally
{
try
{
in.close();
}
catch (IOException e)
{
error = e;
logger.error("Failed to close output stream: " + this, e);
}
try
{
out.close();
}
catch (IOException e)
{
error = e;
logger.error("Failed to close output stream: " + this, e);
}
}
if (error != null)
{
throw error;
}
return byteCount;
}
and this is my main class:
public static void main (String[] arg)
{
InputStream in = new FileInputStream("pathToMyFile");
ContentLimitProvider contentLimitProvider = getContentLimitProvider();
final long sizeLimit = contentLimitProvider.getSizeLimit();
int byteCount = sizeLimitedStreamCopier.copyStreams(in, out, sizeLimit);
return byteCount;
}
and this is the method I'm forced to use to build my outputStream
public OutputStream getContentOutputStream() throws ContentIOException
{
try
{
WritableByteChannel channel = getWritableChannel();
OutputStream is = new BufferedOutputStream(Channels.newOutputStream(channel));
// done
return is;
}
catch (Throwable e)
{
throw new ContentIOException("Failed to open stream onto channel: \n" +
" writer: " + this,
e);
}
}
How can I develop a getWritableChannel() method in order to write into a BLOB field inside a Database DataTable (RBDMS). I'd like to use Spring if it is necessary.

Blackberry Listfield with Live Image

I want to display a listfield with live image in all rows of the listfield
check out this
also use the following code for displaying live images:
public static String getImageFromUrl(String url) {
//Image img = null;
String imageData = null;
try
{
imageData = getDataFromUrl(url);
//img = Image.createImage(imageData.getBytes(), 0,imageData.length() );
}
catch(Exception e1) {
e1.printStackTrace();
}
return imageData;
}
public static String getDataFromUrl(String url)
throws IOException {
StringBuffer b = new StringBuffer();
InputStream is = null;
HttpConnection c = null;
long len = 0 ;
int ch = 0;
ConnectionFactory connFact = new ConnectionFactory();
ConnectionDescriptor connDesc;
connDesc = connFact.getConnection(url);
if (connDesc != null)
{
//HttpConnection httpConn;
c = (HttpConnection)connDesc.getConnection();
}
// c = (HttpConnection)Connector.open(url);
is = c.openInputStream();
len = c.getLength();
if( len != -1) {
// Read exactly Content-Length bytes
for(int i =0 ; i < len ; i++ )
if((ch = is.read()) != -1) {
b.append((char) ch);
}
} else {
//Read until the connection is closed.
while ((ch = is.read()) != -1) {
len = is.available() ;
b.append((char)ch);
}
}
is.close();
c.close();
return b.toString();
}
Hope this will help you.

Resources