Java to php, Byte, Type, Array - java

Here is a small Java Code Snippet.
ConfigData[] cd = new ConfigData[1];
cd[0] = new ConfigData();
byte[] tmpbyte ={1,(byte)0x01};
cd[0].settmpdata(tmpbyte);
"ConfigData" is my custom Type (int, Byte Array).
In my last thread i found the tip how to Build / work with a "ByteArray" in php.
But this seems to be a question of the structure of those objects / array.
So..
How can i depict that in PHP.

I hope that this can make some guidelines for you, in the terms of what you can do in PHP, and in a relation to your code snippet (the code is tested):
<?php
// define class
class ConfigData
{
var $intVal;
var $tmpData;
}
$cData = new ConfigData(); // new ConfigData instance
$array[0] = $cData; // put it in a single element array
$array[0]->intVal = 5; // assign an integer to intVal
$array[0]->tmpData = array(1, 1, 2); // assign an array of whatever to tmpData
foreach($array[0]->tmpData as $val) // iterate through assigned array
echo $val." "; // print array item (and append " " )
?>
Now, you might also want to check how byte manipulation in PHP is achieved. I suggest you to do a little Google search, and maybe check the official manual. You question was not specific enough, so I can't say more.

Related

From java.util.ArrayList to a dictionary in java

Im using a JBPM to make a SQL query in the DB. The sql output is return to a variable that is java.util.ArrayList. The table that im queryin is like this in MariaDB:
variable value
math 1
physics 4
biology 10
...
sport 5
chemistry 9
The query that I'm making is SELECT * from school_data. It is returning me in a form of list like [math,1,phycics,4,biology,10.....] and only 20 elements.
Is there a way to transform the output in dictionary and then extract the values easly? I python it would be like this:
cur = connection.cursor()
cur.execute("SELECT * from school_data")
result = cur.fetchall()
query_result = dict((x, y) for x, y in result)
math=query_result['math']
physics=query_result['physics']
biology=query_result['biology']
Java does not have lists or dictionaries / maps as built-in data types, so it does not offer syntax or built-in operators for working with them. One can certainly perform transformations such as you describe, but it's a matter of opinion whether it can be done "easily". One way would be something like this:
Map<String, String> query_result = new HashMap<>();
for (int i = 0; i < result_array.length; i += 2) {
query_result.put(result_array[i], result_array[i + 1]);
}
String biology = query_result.get("biology");
// ...
That makes some assumptions about the data types involved, which you might need to adjust for your actual data.

java.lang.IndexOutOfBoundsException: Index: 38, Size: 38

I'm currently working on a project, and I got this error. I do not know why it stops at Index 38. The error is
org.apache.jasper.JasperException: javax.el.ELException: java.lang.IndexOutOfBoundsException: Index: 38, Size: 38
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:413)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:326)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:253)
javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
The code that I had used to display was a while loop
var count = ${count};
while (--count) {
var val = ${valueList.get(count)}; //get value from her code
var xValue = ${XValueList.get(count)};
var yValue = ${YValueList.get(count)};
//max = Math.max(max, val);
//
min = 0;
var point = {
x: xValue,
y: yValue,
value: val
};
points.push(point);
}
// var data = { max: max, min:min, data: points };
var data = {data: points };
return data;
};
And I have 41 records in my database. Any help?
Arrays start counting at 0, but their size is given in number of fields. An array of size 38 actually has fields 0 through 37. Accessing field 38 throws an java.lang.IndexOutOfBoundsException.
You somehow missed the fact that JSP is a HTML/CSS/JS code generator and you expected that JSP EL expressions run "in sync" with JavaScript code embedded in JSP file. This is untrue. JSP/EL runs in webserver, produces HTML/CSS/JS output, basically as one large String which get sent from webserver to webbrowser, who in turn runs the JSP/EL-produced HTML/CSS/JS output.
An easy way to realize your mistake is doing a rightclick and View Source in webbrowser (on a JSP page containing tags and EL expressions which doesn't throw a server side exception like this, of course). You'll notice that it does actually not contain any single line of JSP/EL code.
Basically, the --count in your code snippet has only effect in JavaScript, not in JSP, because you basically printed the ${count} as a JavaScript variable var count during generating the HTML output. But the value of var count in JavaScript does in no way affect the value of ${count} which is used further down in ${valueList.get(count)}. The ${count} is still 38 there and has not become 37 or so.
That was the problem. Now we can advance to the solution. I won't post an answer to fix specifically your attempted solution, for the simple reason that this is from high level seen a wrong solution to the underlying problem you tried to solve: converting a Java model object to a JavaScript object.
The right solution to that is converting the Java model object to a string in JSON format in Java side and then letting JSP print it as if it's a JavaScript variable. Your Java model object has also another issue: you seem to have decoupled the X and Y values in two separate lists instead of using a single list with entities in turn having X and Y values.
First create a decent model object:
public class Point {
private int x;
private int y;
// Add/generate constructor+getter+setter+equals+hashcode.
}
Then replace your XValueList and YValueList as below:
List<Point> points = new ArrayList<>();
points.add(new Point(1, 2));
points.add(new Point(3, 4));
points.add(new Point(5, 6));
// ...
Then use one of Java JSON APIs to convert this to a JSON string. I'll pick Gson in below example:
String pointsAsJson = new Gson().toJson(points);
Now let JSP print it as if it's a JS variable, the right way:
var data = {data: ${pointsAsJson} };
No need for a clumsy loop here massaging data forth and back.

String naming convention in java

I am currently trying to make a naming convention. The idea behind this is parsing.
Lets say I obtain an xml doc. Everything can be used once, but these 2 in the code below can be submitted several times within the xml document. It could be 1, or simply 100.
This states that ItemNumber and ReceiptType will be grabbed for the first element.
ItemNumber1 = eElement.getElementsByTagName("ItemNumber").item(0).getTextContent();
ReceiptType1 = eElement.getElementsByTagName("ReceiptType").item(0).getTextContent();
This one states that it will grab the second submission if they were in their twice.
ItemNumber2 = eElement.getElementsByTagName("ItemNumber").item(1).getTextContent();
ReceiptType2 = eElement.getElementsByTagName("ReceiptType").item(1).getTextContent();
ItemNumber and ReceiptType must both be submitted together. So if there is 30 ItemNumbers, there must be 30 Receipt Types.
However now I would like to set this in an IF statement to create variables.
I was thinking something along the lines of:
int cnt = 2;
if (eElement.getElementsByTagName("ItemNumber").item(cnt).getTextContent();)
**MAKE VARIABLE**
Then make a loop which adds one to count to see if their is a third or 4th. Now here comes the tricky part..I need them set to a generated variable. Example if ItemNumber 2 existed, it would set it to
String ItemNumber2 = eElement.getElementsByTagName("ItemNumber").item(cnt).getTextContent();
I do not wish to make pre-made variable names as I don't want to code a possible 1000 variables if that 1000 were to happen.
KUDOS for anyone who can help or give tips on just small parts of this as in the naming convention etc. Thanks!
You don't know beforehand how many ItemNumbers and ReceiptTypes you'll get ? Maybe consider using two Lists (java.util.List). Here is an example.
boolean finished = ... ; // true if there is no more item to process
List<String> listItemNumbers = new ArrayList<>();
List<String> listReceiptTypes = new ArrayList<>();
int cnt = 0;
while(!finished) {
String itemNumber = eElement.getElementsByTagName("ItemNumber").item(cnt).getTextContent();
String receiptType = eElement.getElementsByTagName("ReceiptType").item(cnt).getTextContent();
listItemNumbers.add(itemNumber);
listReceiptTypes.add(receiptType);
++cnt;
// update 'finished' (to test if there are remaining itemNumbers to process)
}
// use them :
int indexYouNeed = 32; // for example
String itemNumber = listItemNumbers.get(indexYouNeed); // index start from 0
String receiptType = listReceiptTypes.get(indexYouNeed);

how to compile java code in android [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Convert String to code
I need to evaluate a string containing valid Java code
eg. I should be able to get 6 from String code="Math.abs(2*3);";
This sounds like quite an interesting idea, can I ask what the purpose of your application will be?
The best bet is to build up a dictionary of known patterns you will support.
My first idea is that you should create an ArrayList of accepted patterns. So for example:
ArrayList<String> acceptedPatterns = new ArrayList<String>();
acceptedPatterns.add("math.abs");
acceptedPatterns.add("math.acos");
etc.
Then you can evaluate this list when you get hold of the string.
String foundPattern = null;
String myStringFromInput = editText.getText();
for (String pattern : acceptedPatterns){
if (myStringFromInput.contains(pattern){
// we have recognised a java method, flag this up
foundPattern = pattern;
break;
}
}
At this point you would have "Math.abs" in your foundPattern variable.
You could then use your knowledge of how this method works to compute it. I can't think of a super efficient way, but a basic way that would at least get you going would be something like a big if/else statement:
int result = 0;
if (foundPattern.contains("Math.abs"){
result = computeMathAbs(myStringFromInput);
}else if (foundPattern.contains("Math.acos"){
// etc
}
And then in your computeMathAbs method you would do something like this:
private int computeMathAbs(String input){
int indexOfBracket = input.indexOf("(");
int indexOfCloseBracket = input.indexOf(")");
String value = input.subString(indexOfBracket,indexOfCloseBracket);
int valueInt = computeFromString(value);
int result = Math.abs(valueInt);
return result;
}
You could then display the result passed back.
The computeFromString() method will do a similar thing, looking for the * symbol or other symbols and turning this into a multiplication like the abs example.
Obviously this is a basic example, so you would only be able to compute one java method at a time, the complexity for more than one method at a time would be quite difficult to program I think.
You would also need to put quite a bit of error handling in, and recognise that the user might not enter perfect java. Can of worms.
You can use Groovy http://groovy.codehaus.org/api/groovy/util/Eval.html
import groovy.util.Eval;
...
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("a", 2);
params.put("b", 3);
Integer res = (Integer) Eval.me("param", params, "Math.abs(param.a * param.b)");
System.out.println("res with params = " + res);
System.out.println("res without params = " + Eval.me("Math.abs(2*3)"));

How to access ilog decision variable from java?

I have a linear problem modelled in IBM ILOG CPLEX Optimization Studio, that returns correct solutions, i.e. objective values.
For simulation purposes I use an ILOG model model file and a data file that I both call from java:
IloOplFactory.setDebugMode(false);
IloOplFactory oplF = new IloOplFactory();
IloOplErrorHandler errHandler = oplF.createOplErrorHandler(System.out);
IloOplModelSource modelSource = oplF.createOplModelSource("CDA_Welfare_Examination_sparse2.mod");
IloCplex cplex = oplF.createCplex();
IloOplSettings settings = oplF.createOplSettings(errHandler);
IloOplModelDefinition def=oplF.createOplModelDefinition(modelSource,settings);
IloOplModel opl=oplF.createOplModel(def,cplex);
String inDataFile = path;
IloOplDataSource dataSource=oplF.createOplDataSource(inDataFile);
opl.addDataSource(dataSource);
opl.generate();
opl.convertAllIntVars(); // converts integer bounds into LP compatible format
if (cplex.solve()){
}
else{
System.out.println("Solution could not be achieved, probably insufficient memory or some other weird problem.");
}
Now, I would like to access the actual decision variable match[Matchable] from java.
In ILOG CPLEX Optimization Studio I use the following nomenclatura:
tuple bidAsk{
int b;
int a;
}
{bidAsk} Matchable = ...;
dvar float match[Matchable];
In Java I access the objective value in the following way (which works fine):
double sol = new Double(opl.getSolutionGetter().getObjValue());
Now, how do I access the decision variable "match"? So far I have started with
IloOplElement dVarMatch = opl.getElement("match");
but I can't seem to get any further. Help is very much appreciated! Thanks a lot!
You're on the right track. You need to get tuples which represent each valid bidAsk in Matchable, then use the tuple as an index into the decision variable object. Here's some sample code in Visual Basic (what I happen to be writing in right now, should be easy to translate to java):
' Get the tuple set named "Matchable"
Dim matchable As ITupleSet = opl.GetElement("Matchable").AsTupleSet
' Get the decision variables named "match"
Dim match As INumVarMap = opl.GetElement("match").AsNumVarMap
' Loop through each bidAsk in Matchable
For Each bidAsk As ITuple In matchable
' This is the current bidAsk's 'b' value
Dim b As Integer = bidAsk.GetIntValue("b")
' This is the current bidAsk's 'a' value
Dim a As Integer = bidAsk.GetIntValue("a")
' this is another way to get bidAsk.b and bidAsk.a
b = bidAsk.GetIntValue(0)
a = bidAsk.GetIntValue(1)
' This is the decision variable object for match[<b,a>]
Dim this_variable As INumVar = match.Get(bidAsk)
' This is the value of that decision variable in the current solution
Dim val As Double = opl.Cplex.GetValue(this_variable)
Next
You can get the variable values through the IloCplex-Object like that:
cplex.getValue([variable reference]);
I never imported a model like that. When you create the model in java, references to the decision variables are easily at hand, but there should be a way to obtain the variables. You could check the documentation:
cplex docu

Categories

Resources