EDIT: I have posted it earlier for java. But it working in Java but not in android. So I am posting the android code now.
I am trying to use a custom class into a HashMap in my android application. But it is not giving my desired output. Please help.
I want to do something like this...
//Code for android application:
//Point class
class Point{
private int x;
private int y;
public Point(){
}
public Point(int _x, int _y){
this.x = _x;
this.y = _y;
}
}
DataManager.java
public class DataManager {
private Vector<Integer> RSSI = null;
private int numOfRSSI;
private Map<Vector<Integer>, Point> SingleData = null;
private Vector<Map<Vector<Integer>, Point>> Data = null;
private Context context;
public DataManager(Context _context) {
this.context = _context;
Data = new Vector<Map<Vector<Integer>, Point>>();
}
public void loadData(String filename) {
if (Data == null) {
System.out.println("***ERROR: DataSet not initalized!!!\n");
}
readFile(filename);
}
public void printData(){
Vector<Integer> rssi = null;
Map<Vector<Integer>, Point> single = null;
Point point = null;
for(int i=0;i<Data.size();i++){
single = new HashMap<Vector<Integer>, Point>() ;
single = Data.get(0);
for (Map.Entry<Vector<Integer>, Point> entry :single.entrySet()) {
rssi = new Vector<Integer>();
point = new Point();
rssi = entry.getKey();
point = entry.getValue();
System.out.print("("+point.x+" "+point.y+") ");
for(int j = 0;j<rssi.size(); j++){
System.out.print(rssi.get(j)+" ");
}
System.out.println("");
}
}
}
private void readFile(String filename) {
InputStream is = null;
try {
is = context.getResources().getAssets().open("datasets.txt");
} catch (IOException e) {
e.printStackTrace();
System.out.println("error file reading");
}
if (is != null) {
StringBuilder text = new StringBuilder();
int flag = 0;
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
if(flag==0){
flag=1;
this.numOfRSSI = Integer.parseInt(line);
System.out.println("number of RSSI: "+numOfRSSI);
}
else if(flag==1){
parseLine(line);
}
}
} catch (IOException e) {
// Error reading file
}
finally {
// myHelper.print(text.toString());
}
}
}
private void parseLine(String line) {
RSSI = new Vector<Integer>();
SingleData = new HashMap<Vector<Integer>, Point>();
StringTokenizer st = new StringTokenizer(line, ",");
int co = 0;
int x=0,y=0;
while (st.hasMoreTokens()) {
if(co < this.numOfRSSI){
RSSI.add(Integer.parseInt(st.nextToken()));
co++;
}
else{
x = Integer.parseInt(st.nextToken());
y = Integer.parseInt(st.nextToken());
}
}
Point point = new Point(x,y);
SingleData.put(RSSI, point);
Data.add(SingleData);
}
}
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
DataManager dataManager = new DataManager(MainActivity.this);
dataManager.loadData("datasets.txt");
dataManager.printData();
}
}
datasets.txt
5
-61,-51,-46,-41,-28,1,0
-60,-50,-51,-47,-34,2,0
-72,-52,-53,-55,-37,3,0
-60,-44,-58,-53,-40,3,1
-68,-55,-46,-47,-45,2,1
-66,-60,-48,-43,-37,1,1
-62,-57,-49,-45,-34,0,2
Output is showing.....
1 0 -61 -51 -46 -41-28
1 0 -60 -50 -51 -47 -34
1 0 -72 -52 -53 -55 -37
etc.....
But it should be...
1 0 -61 -51 -46 -41-28
2 0 -60 -50 -51 -47 -34
etc...
So this is my problem.
Below is working fine on my machine :-
import java.util.Map;
import java.util.Vector;
public class Demo {
public static void main(String[] args) {
Map<Vector<Integer>, Point> vectorPointMap = new HashMap<Vector<Integer>, Point>();
Vector<Integer> vector1 = new Vector<Integer>();
vector1.add(1);
vector1.add(2);
vector1.add(3);
vectorPointMap.put(vector1, new Point(10, 10));
Vector<Integer> vector2 = new Vector<Integer>();
vector2.add(4);
vector2.add(5);
vector2.add(6);
vectorPointMap.put(vector2, new Point(20, 20));
// Print data
for (Map.Entry<Vector<Integer>, Point> entry : vectorPointMap.entrySet()) {
Vector<Integer> keyVector = entry.getKey();
Point valuePoint = entry.getValue();
System.out.print("(" + valuePoint.x + " " + valuePoint.y + ") ");
for (int j = 0; j < keyVector.size(); j++) {
System.out.print(keyVector.get(j) + " ");
}
System.out.println("");
}
}
}
You should change this from
for(int i=0;i<Data.size();i++){
single = new HashMap<Vector<Integer>, Point>() ;
single = Data.get(0);
}
to
for(int i=0;i<Data.size();i++){
single = new HashMap<Vector<Integer>, Point>() ;
single = Data.get(i);
}
try changing:
single = Data.get(0);
to
single = Data.get(i);
What does it mean, "it does not give right"?
You can put your own classes to Map, there is no problem. But remember, when you put items to HashMap in some order, there is no guarantee, it will come out in the same order. If you need to have same order on output, as on input, instead HashMap use LinkedHashMap. You can use it in the same way as HashMap, but it preserves order of inserted items.
Related
Using PDFBox, given data notated like this: [G]Glory be to [D]God [Em]the [C]Father,\n[G]And to [A]Christ the [D]Son,, I am creating a guitar chord sheet like this:
My approach was to iterate through each character in the song and check the current index against the map.. whenever the map has an entry to that character index, we "jump" to the line above, write the chord, then jump back down.
The method setTextRise looked promising, but still processes the horizontal spacing incorrectly:
Here's an SSCCE (needs PDFBox libraries) that produces the PDF above:
public static void main(String[] args) {
try {
String extracted_text = "Capo 1\n\n1\n[G]Glory be to [D]God [Em]the [C]Father,\n[G]And to [A]Christ the [D]Son,\n[B7]Glory to the [Em]Holy [C]Spirit—\n[D-D7]Ever [ G]One.\n\n2\nAs we view the vast creation,\nPlanned with wondrous skill,\nSo our hearts would move to worship,\nAnd be still.\n\n3\nBut, our God, how great Thy yearning\nTo have sons who love\nIn the Son e’en now to praise Thee,\nLove to prove!\n\n4\n’Twas Thy thought in revelation,\nTo present to men\nSecrets of Thine own affections,\nTheirs to win.\n\n5\nSo in Christ, through His redemption\n(Vanquished evil powers!)\nThou hast brought, in new creation,\nWorshippers!\n\n6\nGlory be to God the Father,\nAnd to Christ the Son,\nGlory to the Holy Spirit—\nEver One.\n".replaceAll("\n", "\r");
String[] lines = extracted_text.split("\\r");
ArrayList<SongLine> songlines = new ArrayList<>();
for(String s : lines) {
LinkedHashMap<Integer, String> chords = new LinkedHashMap();
StringBuilder line = new StringBuilder();
StringBuilder currentchord = null;
int index = 0;
for(char c : s.toCharArray()) {
if(currentchord != null) {
if(c == ']') {
chords.put(index, currentchord.toString());
currentchord = null;
} else {
currentchord.append(c);
}
} else {
if(c == '[') {
currentchord = new StringBuilder();
} else {
line.append(c);
index++;
}
}
}
SongLine sl = new SongLine();
if(chords.size() > 0)
sl.char_index_to_chords = chords;
sl.line = line.toString();
songlines.add(sl);
}
try (PDDocument doc = new PDDocument()) {
PDPage page = new PDPage();
PDPageContentStream pcs = new PDPageContentStream(doc, page);
int firstLineX = 25;
int firstLineY = 700;
boolean first = true;
float leading = 14.5f;
pcs.beginText();
pcs.newLineAtOffset(firstLineX, firstLineY);
pcs.setFont(PDType1Font.TIMES_ROMAN, 12);
pcs.setLeading(leading);
for(SongLine line : songlines) {
if(line.char_index_to_chords != null)
System.out.println(line.char_index_to_chords.toString());
System.out.println(line.line);
if(!first) {
pcs.newLine();
}
first = false;
if(line.char_index_to_chords != null) {
pcs.newLine();
}
for(int i = 0; i < line.line.length(); i++) {
pcs.showText(String.valueOf(line.line.charAt(i)));
if(line.char_index_to_chords != null && line.char_index_to_chords.containsKey(i)) {
pcs.setTextRise(12);
pcs.showText(line.char_index_to_chords.get(i));
pcs.setTextRise(0);
}
}
}
pcs.endText();
pcs.close();
doc.addPage(page);
String path = "0001.pdf";
doc.save(path);
Desktop.getDesktop().open(new File(path));
}
} catch (Exception e) {
e.printStackTrace();
}
}
static class SongLine {
Map<Integer, String> char_index_to_chords;
String line;
}
What would you do in PDFBox to create the text aligned with chords (like in the first image)?
I got it. The answer was not setTextRise, rather newLineAtOffset while using getStringWidth to calculate font size:
for(SongLine line : songlines) {
if(!first) {
pcs.newLine();
}
first = false;
if(line.char_index_to_chords != null) {
float offset = 0;
for(Entry<Integer, String> entry : line.char_index_to_chords.entrySet()) {
float offsetX = font.getStringWidth(line.char_index_to_leading_lyrics.get(entry.getKey())) / (float)1000 * fontSize;
pcs.newLineAtOffset(offsetX, 0);
offset += offsetX;
pcs.showText(entry.getValue());
}
pcs.newLineAtOffset(-offset, -leading);
}
pcs.showText(line.line);
}
So I am making a "game" with LWJGL, and I started loading 3D Models (Using Wavefront .obj files). I have successfully loaded the model, but instead of having textures, I wanted to try out the .mtl files, to specify the materials. I "sort of" made it, but it seems to be not completely working. Here is my code, and a picture of the Tree model I tried to render:
Tree Model
Now here is my code:
private static OBJMesh mesh;
public static Mesh load3DModel(String objFileName)
{
mesh = new OBJMesh();
BufferedReader reader = null;
try
{
reader = new BufferedReader(new FileReader(new File(objFileName)));
}
catch (FileNotFoundException e)
{
System.err.println("Could not locate OBJ File at " + objFileName);
e.printStackTrace();
}
String mtlFileName = null;
String line = null;
String currentFaceMat = null;
try
{
while ((line = reader.readLine()) != null)
{
String[] lineParts = line.split(" ");
switch (line.substring(0, 2))
{
case "v ":
Vertex v = new Vertex(lineParts[1], lineParts[2], lineParts[3]);
mesh.addVertex(v);
break;
case "vn":
Normal n = new Normal(lineParts[1], lineParts[2], lineParts[3]);
mesh.addNormal(n);
break;
case "mt":
mtlFileName = FileHelper.getDirectory(objFileName) + lineParts[1];
break;
case "us":
currentFaceMat = lineParts[1];
break;
case "f ":
Face face = createFace(currentFaceMat, lineParts);
mesh.addFace(face);
break;
}
}
reader = new BufferedReader(new FileReader(mtlFileName));
Material mat = null;
while ((line = reader.readLine()) != null)
{
String[] lineParts = line.split(" ");
if (line.length() > 1)
{
switch (line.substring(0, 2))
{
case "ne":
mat = new Material(lineParts[1]);
mesh.addMaterial(lineParts[1], mat);
break;
case "Ka":
mat.setKa(createVector(lineParts));
break;
case "Kd":
mat.setKd(createVector(lineParts));
break;
case "Ks":
mat.setKs(createVector(lineParts));
break;
case "Ns":
mat.setNs(Float.parseFloat(lineParts[1]));
break;
case "d ":
mat.setD(Float.parseFloat(lineParts[1]));
break;
case "il":
mat.setIllum(Integer.parseInt(lineParts[1]));
break;
}
}
}
reader.close();
}
catch (IOException e)
{
e.printStackTrace();
}
mesh.normalArray = new float[mesh.vertices.size() * 3];
for (Face face : mesh.faces)
{
decodeNormals(face.indices1);
decodeNormals(face.indices2);
decodeNormals(face.indices3);
}
mesh.vertexArray = new float[mesh.vertices.size() * 3];
mesh.indexArray = new int[mesh.indices.size() * 3];
mesh.colorArray = new float[mesh.faces.size() * 3];
int vertexPointer = 0;
for (Vertex vertex : mesh.vertices)
{
mesh.vertexArray[vertexPointer++] = vertex.x;
mesh.vertexArray[vertexPointer++] = vertex.y;
mesh.vertexArray[vertexPointer++] = vertex.z;
}
for (int i = 0; i < mesh.indices.size(); i++)
{
mesh.indexArray[i] = mesh.indices.get(i);
}
int colorPointer = 0;
for (Face face : mesh.faces)
{
mesh.colorArray[colorPointer++] = mesh.materials.get(face.material).Kd.x;
mesh.colorArray[colorPointer++] = mesh.materials.get(face.material).Kd.y;
mesh.colorArray[colorPointer++] = mesh.materials.get(face.material).Kd.z;
}
return MeshLoader.genVertexModel(mesh.vertexArray, mesh.indexArray, mesh.colorArray);
}
private static Face createFace(String materialName, String[] lineData)
{
String[] indices1 = General.replaceEmptySlashes(lineData[1]).split("/");
String[] indices2 = General.replaceEmptySlashes(lineData[2]).split("/");
String[] indices3 = General.replaceEmptySlashes(lineData[3]).split("/");
return new Face(materialName, indices1, indices2, indices3);
}
private static Vector3f createVector(String[] lineData)
{
float x = Float.parseFloat(lineData[1]);
float y = Float.parseFloat(lineData[2]);
float z = Float.parseFloat(lineData[3]);
return new Vector3f(x, y, z);
}
private static void decodeNormals(Vector3f vertex)
{
int vertexPointer = (int) vertex.x - 1;
mesh.indices.add(vertexPointer);
Normal normal = mesh.normals.get((int) vertex.z - 1);
mesh.normalArray[vertexPointer * 3] = normal.x;
mesh.normalArray[vertexPointer * 3 + 1] = normal.y;
mesh.normalArray[vertexPointer * 3 + 2] = normal.z;
}
The OBJMesh class:
public List<Vertex> vertices = new ArrayList<Vertex>();
public List<Normal> normals = new ArrayList<Normal>();
public List<Integer> indices = new ArrayList<Integer>();
public List<Face> faces = new ArrayList<Face>();
public Map<String, Material> materials = new HashMap<String, Material>();
public float[] vertexArray;
public float[] normalArray;
public float[] colorArray;
public int[] indexArray;
public void addVertex(Vertex vertex)
{
vertices.add(vertex);
}
public void addNormal(Normal normal)
{
normals.add(normal);
}
public void addMaterial(String name, Material material)
{
materials.put(name, material);
}
public void addFace(Face face)
{
faces.add(face);
}
The Face class:
public Vector3f indices1;
public Vector3f indices2;
public Vector3f indices3;
public String material;
public Face(String material, String[] v1, String[] v2, String[] v3)
{
this.material = material;
this.indices1 = new Vector3f(Float.parseFloat(v1[0]), Float.parseFloat(v1[1]), Float.parseFloat(v1[2]));
this.indices2 = new Vector3f(Float.parseFloat(v2[0]), Float.parseFloat(v2[1]), Float.parseFloat(v2[2]));
this.indices3 = new Vector3f(Float.parseFloat(v3[0]), Float.parseFloat(v3[1]), Float.parseFloat(v3[2]));
}
The Material class just contains RGB values.
If you could find something, let me know; I have been searching for weeks (No joke!). Thank you
OpenGL expects all vertex attributes to be, well, per-vertex. The way you are at the moment populating your colorArray suggests you are only doing this per-face. Change this and it should give the correct results.
I am working on implementing a generic code to solve left recursion problem in a grammar using java so my code is working as follows I am reading an input like this as each line goes to the next line:
E
E+T|T
T
T*F|F
F
(E)|id|number
and the required output is supposed to be like this one :
E->[TE']
T->[FT']
F->[(E), id, number]
E'->[+TE', !]
T'->[*FT', !]
I wrote that code which is storing input in Arraylists to iterate over them and produce the output:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class IleftRecursion {
//storing each line in its corresponding Arraylist
static ArrayList<String> leftRules = new ArrayList<>();
static ArrayList<String> rightRules = new ArrayList<>();
public static void read_file(String file) throws IOException {
FileReader in = new FileReader(file);
BufferedReader br = new BufferedReader(in);
String line;
while ((line = br.readLine()) != null) {
leftRules.add(line);
rightRules.add(br.readLine());
}
br.close();
}
public static void ss() {
for (int i = 0; i < leftRules.size(); i++) {
for (int j = 1; j <= i - 1; j++) {
//splitting inputs on bars "|" to iterate through them
for (String x : rightRules.get(i).split("\\|")) {
if (x.contains(leftRules.get(j))) {
String f = "";
String ff = "";
for (int k=0; k<rightRules.get(k).split("\\|").length;k++) {
f = x;
f = f.replaceAll(leftRules.get(i), rightRules.get(k).split("\\|")[k]);
ff += f;
}
rightRules.remove(i);
rightRules.add(i, ff);
}
}
}
//Recursive or Not boolean
boolean isRec = false;
for (String z : rightRules.get(i).split("\\|")) {
if (z.startsWith(leftRules.get(i))) {
isRec = true;
break;
}
}
if (isRec) {
String a = "";
String b = "";
for (String s : rightRules.get(i).split("\\|")) {
if (s.startsWith(leftRules.get(i))) {
b += s.replaceAll(leftRules.get(i), "") + leftRules.get(i) + "',";
} else {
a += s + leftRules.get(i) + "'";
}
}
b += "!";
if(a.length()>=1)
a.substring(1, a.length() - 1);
rightRules.add(i, a);
rightRules.add(i + 1, b);
leftRules.add(leftRules.get(i) + "'");
}
}
}
public static void main(String[] args) throws IOException {
read_file("Sample.in");
ss();
for (int i=0;i<leftRules.size();i++)
{
System.out.print(leftRules.get(i)+"->");
System.out.println("["+rightRules.get(i)+"]");
}
}
}
I debugged the code many times trying to figure out why Am I getting output like this
E->[TE']
T->[+TE',!]
F->[T]
E'->[T*F]
Which is missing One rule and also not all the new productions generated in the right way but I couldn't fix could anyone help me through that ?
I have such a big problem with implementation the svm_predict function. I have trained svm, and prepare datatest. Both files are in .txt. file.Datatest are from LBP( Local Binary patterns) and it looks like:
-0.6448744548418511
-0.7862774302452588
1.7746263060948377
I'm loading it to the svm_predict function and at my console after compiling my program there is:
Accuracy = 0.0% (0/800) (classification)
So it's look like it can't read datatest?
import libsvm.*;
import java.io.*;
import java.util.*;
class svm_predict {
private static double atof(String s)
{
return Double.valueOf(s).doubleValue();
}
private static int atoi(String s)
{
return Integer.parseInt(s);
}
private static void predict(BufferedReader input, DataOutputStream output, svm_model model, int predict_probability) throws IOException
{
int correct = 0;
int total = 0;
double error = 0;
double sumv = 0, sumy = 0, sumvv = 0, sumyy = 0, sumvy = 0;
int svm_type=svm.svm_get_svm_type(model);
int nr_class=svm.svm_get_nr_class(model);
double[] prob_estimates=null;
if(predict_probability == 1)
{
if(svm_type == svm_parameter.EPSILON_SVR ||
svm_type == svm_parameter.NU_SVR)
{
System.out.print("Prob. model for test data: target value = predicted value + z,\nz: Laplace distribution e^(-|z|/sigma)/(2sigma),sigma="+svm.svm_get_svr_probability(model)+"\n");
}
else
{
int[] labels=new int[nr_class];
svm.svm_get_labels(model,labels);
prob_estimates = new double[nr_class];
output.writeBytes("labels");
for(int j=0;j<nr_class;j++)
output.writeBytes(" "+labels[j]);
output.writeBytes("\n");
}
}
while(true)
{
String line = input.readLine();
if(line == null) break;
StringTokenizer st = new StringTokenizer(line," \t\n\r\f:");
double target = atof(st.nextToken());
int m = st.countTokens()/2;
svm_node[] x = new svm_node[m];
for(int j=0;j<m;j++)
{
x[j] = new svm_node();
x[j].index = atoi(st.nextToken());
x[j].value = atof(st.nextToken());
}
double v;
if (predict_probability==1 && (svm_type==svm_parameter.C_SVC || svm_type==svm_parameter.NU_SVC))
{
v = svm.svm_predict_probability(model,x,prob_estimates);
output.writeBytes(v+" ");
for(int j=0;j<nr_class;j++)
output.writeBytes(prob_estimates[j]+" ");
output.writeBytes("\n");
}
else
{
v = svm.svm_predict(model,x);
output.writeBytes(v+"\n");
}
if(v == target)
++correct;
error += (v-target)*(v-target);
sumv += v;
sumy += target;
sumvv += v*v;
sumyy += target*target;
sumvy += v*target;
++total;
}
if(svm_type == svm_parameter.EPSILON_SVR ||
svm_type == svm_parameter.NU_SVR)
{
System.out.print("Mean squared error = "+error/total+" (regression)\n");
System.out.print("Squared correlation coefficient = "+
((total*sumvy-sumv*sumy)*(total*sumvy-sumv*sumy))/
((total*sumvv-sumv*sumv)*(total*sumyy-sumy*sumy))+
" (regression)\n");
}
else
System.out.print("Accuracy = "+(double)correct/total*100+
"% ("+correct+"/"+total+") (classification)\n");
}
private static void exit_with_help()
{
System.err.print("usage: svm_predict [options] test_file model_file output_file\n"
+"options:\n"
+"-b probability_estimates: whether to predict probability estimates, 0 or 1 (default 0); one-class SVM not supported yet\n");
System.exit(1);
}
public static void main(String argv[]) throws IOException
{
int i, predict_probability=0;
// parse options
for(i=0;i<argv.length;i++)
{
if(argv[i].charAt(0) != '-') break;
++i;
switch(argv[i-1].charAt(1))
{
case 'b':
predict_probability = atoi(argv[i]);
break;
default:
System.err.print("Unknown option: " + argv[i-1] + "\n");
exit_with_help();
}
}
if(i>=argv.length-2)
exit_with_help();
try
{
BufferedReader input = new BufferedReader(new FileReader(argv[i]));
DataOutputStream output = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(argv[i+2])));
svm_model model = svm.svm_load_model(argv[i+1]);
if(predict_probability == 1)
{
if(svm.svm_check_probability_model(model)==0)
{
System.err.print("Model does not support probabiliy estimates\n");
System.exit(1);
}
}
else
{
if(svm.svm_check_probability_model(model)!=0)
{
System.out.print("Model supports probability estimates, but disabled in prediction.\n");
}
}
predict(input,output,model,predict_probability);
input.close();
output.close();
}
catch(FileNotFoundException e)
{
exit_with_help();
}
catch(ArrayIndexOutOfBoundsException e)
{
exit_with_help();
}
}
}
It's difficult to know becasue its a big process
make sure you follow their classification guide
the data should be scaled it seems it goes above 1 right now
i am reading the bytes from binary file and now i have to get the index position of the stream and i am using CountingInputStream class and method getByteCount but this method returning me 0.
Here is my Code.
public void readIndex(InputStream iStream)
{
SwappedDataInputStream input;
input = new SwappedDataInputStream(iStream);
int locKey;
int x=0;
int y=0;
try{
setINoOfTiles(input.readInt());
CountingInputStream cis = new CountingInputStream(iStream);
for(int i=0; i<iNoOfTiles; i++)
{
x = input.readInt()/100;
y =input.readInt()/100;
MapTileHeader tTile = new MapTileHeader(x, y, mapType);
locKey = input.readInt();
HashMap<Integer, MapTileHeader> iTileListOffsets = new HashMap<Integer, MapTileHeader>();
iTileListOffsets.put(locKey, tTile);
}
String out = IOUtils.toString(cis);
long count = cis.getByteCount();
Log.i("count", "count =" + count);
}catch(Exception e )
{
e.printStackTrace();
}
}
Use input = new SwappedDataInputStream(cis); and rearrange declarations accordingly.