How to rename Field of an object in java - java

I have one Java object, to which I'm adding an objectlist.
Objects data = new Objects();
data.setName("E");
if(!fvalue1.equals("")){
Objects subObj3 = new Objects();
subObj3.setField(" OPERATOR", "=");
subObj3.setField("VALUE1", value1);
CObjectList cObjList3 = new CObjectList();
cObjList3.add(subObj3);
data.setSubObjects("SEL", ckObjList3);
}
if(err.length()>0){
Objects subObj8 = new Objects ();
subObj8.setField(" OPERATOR", "=");
subObj8.setField("VALUE1", err);
CObjectList ckObjList8 = new CObjectList();
cObjList8.add(subObj8);
data.setSubObjects("SEL", cObjList8);
//data.setSubObjects("SEL2", cObjList8);
//data.getField("SEL2").replace("SEL2", "SEL");
}
When I give "data.setSubObjects("SEL", cObjList8); ", the first SEL is replaced with the second. But I need both the SEL fields to be there. I have tried naming as SEL2 and then renaming it to SEL. But it doesn't work.
I am trying to create a dynamic xml from this.
Can someone help me to rename SEL2 to SEL?

Related

Convert string to object name Java

it might be a simple question or even impossible without any kind of Interface (Arrays, Maps etc.) but I would like to know if there's any possibility of converting an object name to String so I can pass as argument. I have two classes Paciente and Sintomas with multiple objects that I need to pass as argument to a function but I don't want to use arrays (it must be like that) and I can't figure any other way of doing so without manually make an insert for each one.
Paciente Paciente1 = new Paciente("001", "Ana Melo", 33, "");
Paciente Paciente2 = new Paciente("002", "Rui Costa", 13, "");
Paciente Paciente3 = new Paciente("003", "Joana Martins", 85, "");
Paciente Paciente4 = new Paciente("004", "Pedro Torres", 53, "");
Paciente Paciente5 = new Paciente("005", "Ana Gomes", 93, "");
Paciente Paciente6 = new Paciente("006", "Jorge Costa", 56, "");
Sintomas Sintoma1 = new Sintomas("001", "febre");
Sintomas Sintoma2 = new Sintomas("001", "dores");
Sintomas Sintoma3 = new Sintomas("001", "machas");
Sintomas Sintoma4 = new Sintomas("002", "febre");
Sintomas Sintoma5 = new Sintomas("002", "manchas");
Sintomas Sintoma6 = new Sintomas("003", "febre");
Sintomas Sintoma7 = new Sintomas("003", "dores");
Sintomas Sintoma8 = new Sintomas("004", "febre");
Sintomas Sintoma9 = new Sintomas("006", "manchas");
Sintomas Sintoma10 = new Sintomas("006", "dores");
// now I would like to pass to a function as argument something like this:
for(int i = 0 ; i < 6 ; i++)
kSession.insert("Paciente"+(i+1));
// instead of making
kSession.insert(Paciente1);
kSession.insert(Paciente2);
kSession.insert(Paciente3);
// and so on.
Something like this should work(asuming you mean no array because of size constraints), note that there has to be somewhere you add the data, it's also possible to load it from a txt or something, but it has to be defined at some point
List<Paciente> pacientes = new ArrayList<>(); // no size constraints, automatically expands if too small
pacientes.add(new Paciente("", "", ""));
for (Paciente paciente : pacientes) { // loop all Patientes in pacientes
kSession.insert(paciente); // add a paciente to the session, for every entry
}
ofcource same can be done for any class, or object
It all really comes down to, how do you wish to store and access the data, and where do you need to store and access it. Using ArrayList and Map's offer the utility of easily changing the size and content of a list of data, but as any data it must be initially inserted
As a side note if the patients have an ID then using a Map
Map<String, Paciente> pacientes = new HashMap<>();
provides a way to acces the patiens very fast, and the TreeMap structure is sorted on key, should that be needed.
Other options could be
Wrapper classes that manage the data, will work similarily to an ArrayList<> but you can define, rules for adding, deleting, and such from the list.
public class Wrapper{
private List<Paciente> pacientes = new ArrayList<>();
public void addPaciente(Paciente paciente){
if(!this.pacientes.contains(paciente)) // prevent multi entries
paciente.add(paciente);
}
public void addPacientes(List<Paciente> pacientes){
for(Paciente paciente : pacientes) // add all patients using the add method
this.addPaciente(paciente);
}
public List<Paciente> getPacientes(){
return this.pacientes;
}
}
You can then add the patients to the kSession, as earlier described
Finally, there is no reason why Paciente, can have the list of Sintomas, such that
public class Paciente{
private List<Sintomas> sintomas = new ArrayList<>();
public addSintomas(Sintomas sintomas){
if(!this.sintomas.contains(sintomas))
this.sintomas.add(sintomas);
}
// rest is the same principle as above in "Wrapper"
}
This way you can get a Paciente, and add a Sintomas, and then when you wish to check a Pacientes Sintomas you can just get the list of Sintomas from that Paciente

Batching in Java and Excel gives different results

I need to batch elements that have similar client id (String type, but at the moment only numeric values, like "12345", "235134", etc.)
Map<String, List<Client>> _batched = new HashMap<String, List<Client>>();
for (Client c : _Clients)
{
String id = c.getIdClient();
List<Client> clients = _batched.get(id);
if(_clients == null){
clients = new ArrayList<Client>();
_batched.put(id, clients);
}
clients.add(c);
}
The problem is that when I compare this function with the results of Excel (=SUM(IF(FREQUENCY(C2:C618,C2:C618)>0,1))), then I get different results, i.e. 526 and 519.
Is something wrong with my code?
Your problem is here:
String id = c.getIdClient();
List<Client> _clients = _batched.get(id);
if(_clients == null){
pois = new ArrayList<Client>();
_batched.put(id, _clients);
}
_clients.add(c);
You create a new array into a variable called pois but then put the contents of the variable _clients into _batched. What happens with the value put into pois?
I don't understand how that doesn't null pointer exception actually.

Predicting data created on-the-fly in WEKA using a premade model file

I want to create a WEKA Java program that reads a group of newly created data that will be fed to a premade model from the GUI version.
Here is the program:
import java.util.ArrayList;
import weka.classifiers.Classifier;
import weka.core.Attribute;
import weka.core.DenseInstance;
import weka.core.Instances;
import weka.core.Utils;
public class UseModelWithData {
public static void main(String[] args) throws Exception {
// load model
String rootPath = "G:/";
Classifier classifier = (Classifier) weka.core.SerializationHelper.read(rootPath+"j48.model");
// create instances
Attribute attr1 = new Attribute("age");
Attribute attr2 = new Attribute("menopause");
Attribute attr3 = new Attribute("tumor-size");
Attribute attr4 = new Attribute("inv-nodes");
Attribute attr5 = new Attribute("node-caps");
Attribute attr6 = new Attribute("deg-malig");
Attribute attr7 = new Attribute("breast");
Attribute attr8 = new Attribute("breast-quad");
Attribute attr9 = new Attribute("irradiat");
Attribute attr10 = new Attribute("Class");
ArrayList<Attribute> attributes = new ArrayList<Attribute>();
attributes.add(attr1);
attributes.add(attr2);
attributes.add(attr3);
attributes.add(attr4);
attributes.add(attr5);
attributes.add(attr6);
attributes.add(attr7);
attributes.add(attr8);
attributes.add(attr9);
attributes.add(attr10);
// predict instance class values
Instances testing = new Instances("Test dataset", attributes, 0);
// add data
double[] values = new double[testing.numAttributes()];
values[0] = testing.attribute(0).addStringValue("60-69");
values[1] = testing.attribute(1).addStringValue("ge40");
values[2] = testing.attribute(2).addStringValue("10-14");
values[3] = testing.attribute(3).addStringValue("15-17");
values[4] = testing.attribute(4).addStringValue("yes");
values[5] = testing.attribute(5).addStringValue("2");
values[6] = testing.attribute(6).addStringValue("right");
values[7] = testing.attribute(7).addStringValue("right_up");
values[8] = testing.attribute(0).addStringValue("yes");
values[9] = Utils.missingValue();
// add data to instance
testing.add(new DenseInstance(1.0, values));
// instance row to predict
int index = 10;
// perform prediction
double myValue = classifier.classifyInstance(testing.instance(10));
// get the name of class value
String prediction = testing.classAttribute().value((int) myValue);
System.out.println("The predicted value of the instance ["
+ Integer.toString(index) + "]: " + prediction);
}
}
My references include:
Using a premade WEKA model in Java
the WEKA Manual provided in the 3.7.10 version - 17.3 Creating datasets in memory
Creating a single instance for classification in WEKA
So far the part where I create a new Instance inside the script causes the following error:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 1
in the line
double myValue = classifier.classifyInstance(testing.instance(10));
I just want to use a latest row of instance values to a premade WEKA model. How do I solve this?
Resources
Program file
Arff file
j48.model
You have the error because you are trying to access the 11th instance and have only created one.
If you always want to access the last instance you might try the following:
double myValue = classifier.classifyInstance(testing.lastInstance());
Additionally, I don't believe that you are creating the instances you hope for. After looking at your provided ".arff" file, which I believe you are trying to mimic, I think you should proceed making instances as follows:
FastVector atts;
FastVector attAge;
Instances testing;
double[] vals;
// 1. set up attributes
atts = new FastVector();
//age
attAge = new FastVector();
attAge.addElement("10-19");
attAge.addElement("20-29");
attAge.addElement("30-39");
attAge.addElement("40-49");
attAge.addElement("50-59");
attAge.addElement("60-69");
attAge.addElement("70-79");
attAge.addElement("80-89");
attAge.addElement("90-99");
atts.addElement(new Attribute("age", attAge));
// 2. create Instances object
testing = new Instances("breast-cancer", atts, 0);
// 3. fill with data
vals = new double[testing.numAttributes()];
vals[0] = attAge.indexOf("10-19");
testing.add(new DenseInstance(1.0, vals));
// 4. output data
System.out.println(testing);
Of course I did not create the whole dataset, but the technique would be the same.

How to Update an Existing Record in a Dataset

I can't seem to update an existing record in my table using a strongly-typed dataset. I can add a new record, but if I make changes to an existing record it doesn't work.
Here is my code:
private void AddEmplMaster()
{
dsEmplMast dsEmpMst = new dsEmplMast();
SqlConnection cn = new SqlConnection();
cn.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["cn.ConnectionString"];
SqlDataAdapter da1 = new SqlDataAdapter("SELECT * FROM UPR00100", cn);
SqlCommandBuilder cb1 = new SqlCommandBuilder(da1);
da1.Fill(dsEmpMst.UPR00100);
DataTable dtMst = UpdateEmpMst(dsEmpMst);
da1.Update(dsEmpMst.UPR00100);
}
This procedure is called from above to assign the changed fields to a record:
private DataTable UpdateEmpMst(dsEmplMast dsEmpMst)
{
DataTable dtMst = new DataTable();
try
{
dsEmplMast.UPR00100Row empRow = dsEmpMst.UPR00100.NewUPR00100Row();
empRow.EMPLOYID = txtEmplId.Text.Trim();
empRow.LASTNAME = txtLastName.Text.Trim();
empRow.FRSTNAME = txtFirstName.Text.Trim();
empRow.MIDLNAME = txtMidName.Text.Trim();
empRow.ADRSCODE = "PRIMARY";
empRow.SOCSCNUM = txtSSN.Text.Trim();
empRow.DEPRTMNT = ddlDept.SelectedValue.Trim();
empRow.JOBTITLE = txtJobTitle.Text.Trim();
empRow.STRTDATE = DateTime.Today;
empRow.EMPLOYMENTTYPE = "1";
dsEmpMst.UPR00100.Rows.Add(empRow);
}
catch { }
return dtMst;
}
Thank you
UPDATE:
Ok I figured it out. In my UpdateEmpMst() procedure I had to check if the record exists then to retrieve it first. If not then create a new record to add. Here is what I added:
try
{
dsEmplMast.UPR00100Row empRow;
empRow = dsEmpMst.UPR00100.FindByEMPLOYID(txtEmplId.Text.Trim());
if (empRow == null)
{
empRow = dsEmpMst.UPR00100.NewUPR00100Row();
dsEmpMst.UPR00100.Rows.Add(empRow);
}
then I assign my data to the new empRow I created and updates fine.
In order to edit an existing record in a dataset, you need to access a particular column of data in a particular row. The data in both typed and untyped datasets can be accessed via the following:
With the indices of the tables, rows, and columns collections.
By passing the table and column names as strings to their respective collections.
Although typed datasets can use the same syntax as untyped datasets, there are additional advantages to using typed datasets. For more information, see the "To update existing records using typed datasets" section below.
To update existing records in either typed or untyped datasets
Assign a value to a specific column within a DataRow object.
The table and column names of untyped datasets are not available at design time and must be accessed through their respective indices.

JAVA Macros for Android Use (Does such exist?)

I have been using VFP 8.0 for quite sometime and one of the most thing I enjoyed about it is the macro function;
name = "Paul James"
age = 25
result = My name is &name, I am &age years old.
I could also do,
dimension x[5];
x[0] = "box"
x[1] = "area"
text.&x[0]..text = "textbox" ---> textbox.text="textbox"
text.&x[1]..text = "textarea" ---> textarea.text="textarea"
That's with the FoxPro thing, I seem to have grown attached to it and am somewhat inclined wishing such exist with OOs Languages like Java (or it really does, im just missing some extra research?), anyway, I wanted to have something like that here's my problem;
I have a JSON Array, which I get all names of the response and store it in a temporary array by using the "names()" method provided in the android code factory.
Purposely, I want to create an array for each name in the temporary array that was created from the method;
To illustrate;
JSONArray response =
[{"name":"a","middlename":"aa","surname":"aaa"},{"name":"b","middlename":"bb","surname":"bbb"},{"name":"c","middlename":"cc","surname":"ccc"}]
temp[] = [{name,middlename,surname}];
Desired Output:
String[] name = new String[response.firstobject.length];
String[] middlename = new String[response.firstobject.length];
String[] surname = new String[response.firstobject.length];
Here's my actual code; The JSON Parser
#SuppressWarnings("null")
public ArrayList<String> parseJson(JSONArray ja) throws JSONException{
ArrayList<String> listItems = new ArrayList<String>();
String[] temp = null;
//Get all the fields first
for (int i=0; i<=0; ++i){
JSONObject jo = ja.getJSONObject(i);
if(jo.length()>0){
temp = new String[jo.names().length()];
for(int x=0; x<jo.names().length(); ++x){
temp[x] = jo.names().getString(x);
}
}
}
}
So I'm kinda stuck in the desired output, is this possible in the first place? Why I'm doing this, is that because I wanted to create a generic JSON response method; So that I don't have to remember all the names of the response just to use them. Im looking for a java/android solution (most likely the one that works with android).
Thanks in Advance!
I wouldn't necessarily try to replicate what you can do in Visual FoxPro since it's usually a good idea in that language to avoid macro substitution unless you absolutely have to use it, and you can't use a name expression instead.
Here is an example of a name expression:
STORE 'city' TO cVarCity
REPLACE (cVarCity) WITH 'Paris'
This is much faster especially in loops.
On the Java side you're probably looking at using the Reflection API.
I also work with vfp and I have some routines. Perhaps these functions serve you STRTRAN, CHRTRAN:
//--------- ejemplos :
// STRTRAN("Hola * mundo","*", "//") ==> "Hola // mundo"
public String STRTRAN(String cExpression, String cFindString, String cReplacement){
return cExpression.replace(cFindString, cReplacement);
}
//------------------ ejemplos:
// miToolkit.CHRTRAN("ABCDEF", "ACE", "XYZ"); // muestra XBYDZF. ok
// miToolkit.CHRTRAN("ABCDEF", "ACE", "XYZQRST"); // muestra XBYDZF. ok
// miToolkit.CHRTRAN("ABCD", "ABC", "YZ"); // muestra YZCD. No es como fox
public String CHRTRAN(String cString, String cFindChars, String cNewChars){
String cResult = cString;
char[] aFindChars;
char[] aNewChars;
int nLength = cFindChars.length();
aFindChars = cFindChars.toCharArray();
aNewChars = cNewChars.toCharArray();
if(cNewChars.length() < nLength){
nLength = cNewChars.length() ;
}
for(int i=0; i < nLength; i++){
cResult = cResult.replace( aFindChars[i], aNewChars[i] );
}
return cResult;
}
Saludos,
César Gómez,
Lima-Perú

Categories

Resources