How to make these strings print beside each other - java

public static void main(String[] args) {
String A = " AAA \n"
+ " A:::A \n"
+ " A:::::A \n"
+ " A:::::::A \n"
+ " A:::::::::A \n"
+ " A:::::A:::::A \n"
+ " A:::::A A:::::A \n"
+ " A:::::A A:::::A \n"
+ " A:::::A A:::::A \n"
+ " A:::::AAAAAAAAA:::::A \n"
+ " A:::::::::::::::::::::A \n"
+ " A:::::AAAAAAAAAAAAA:::::A \n"
+ " A:::::A A:::::A \n"
+ " A:::::A A:::::A \n"
+ " A:::::A A:::::A \n"
+ "AAAAAAA AAAAAAA";
String B = "\nBBBBBBBBBBBBBBBBB \n"
+ "B::::::::::::::::B \n"
+ "B::::::BBBBBB:::::B \n"
+ "BB:::::B B:::::B\n"
+ " B::::B B:::::B\n"
+ " B::::B B:::::B\n"
+ " B::::BBBBBB:::::B \n"
+ " B:::::::::::::BB \n"
+ " B::::BBBBBB:::::B \n"
+ " B::::B B:::::B\n"
+ " B::::B B:::::B\n"
+ " B::::B B:::::B\n"
+ "BB:::::BBBBBB::::::B\n"
+ "B:::::::::::::::::B \n"
+ "B::::::::::::::::B \n"
+ "BBBBBBBBBBBBBBBBB ";
System.out.print(A);
System.out.print(B);
}
}
here's a simplified version of what im trying to do, when I run it A appears on top of B, I want A and B to print out beside each other but I have no clue how. very new to this, probably a stupid question but i cant find anything on the web so I'm hoping someone here can help me out

you can use \n to determine each line and print it side by side:
final String[] aa = A.split("\n");
final String[] ba = B.split("\n");
IntStream.range(0, aa.length).forEach((int idx) -> System.out.printf("%s %s\n", aa[idx], ba[idx]));

If you split each character into lines, you can then iterate over the number of lines and print them "in parallel." A much simpler example follows.
class Test {
public static void main(String[] args) {
String box1 = "+-+\n" +
"| |\n" +
"+-+";
String box2 = "+-+\n" +
"|x|\n" +
"+-+";
String[] lines1 = box1.split("\n");
String[] lines2 = box2.split("\n");
for (int i = 0; i < lines1.length; i++) {
System.out.printf("%s %s\n", lines1[i], lines2[i]);
}
}
}

According to the Information that i have to this case, i could suggest you a Souloution like this.
This is maybe not the prettiest soloution, but it is simple to understand, and it works.
public class Main {
public static void main(String[] args) {
String A = " AAA \n"
+ " A:::A \n"
+ " A:::::A \n"
+ " A:::::::A \n"
+ " A:::::::::A \n"
+ " A:::::A:::::A \n"
+ " A:::::A A:::::A \n"
+ " A:::::A A:::::A \n"
+ " A:::::A A:::::A \n"
+ " A:::::AAAAAAAAA:::::A \n"
+ " A:::::::::::::::::::::A \n"
+ " A:::::AAAAAAAAAAAAA:::::A \n"
+ " A:::::A A:::::A \n"
+ " A:::::A A:::::A \n"
+ " A:::::A A:::::A \n"
+ "AAAAAAA AAAAAAA";
String B = "\nBBBBBBBBBBBBBBBBB \n"
+ "B::::::::::::::::B \n"
+ "B::::::BBBBBB:::::B \n"
+ "BB:::::B B:::::B\n"
+ " B::::B B:::::B\n"
+ " B::::B B:::::B\n"
+ " B::::BBBBBB:::::B \n"
+ " B:::::::::::::BB \n"
+ " B::::BBBBBB:::::B \n"
+ " B::::B B:::::B\n"
+ " B::::B B:::::B\n"
+ " B::::B B:::::B\n"
+ "BB:::::BBBBBB::::::B\n"
+ "B:::::::::::::::::B \n"
+ "B::::::::::::::::B \n"
+ "BBBBBBBBBBBBBBBBB ";
List<String> arrayA = List.of(A.split("\n"));
List<String> arrayB = List.of(B.split("\n"));
for(int i = 0; i < arrayA.size(); i++){
System.out.println(arrayA.get(i)+arrayB.get(i));
}
}

Related

Firebase Firestore query bug if the document uses a large Map field

After I upgraded the Firestore android sdk from v20.1.0 to v21.6.0, my Firestore queries are not working as expected.
If I make a simple get() query or a snapshotListener query (realtime) on a single document, the query works once (or twice) then stops working or getting updates (if realtime query), the onEvent() method wouldn't be triggered.
After deep investigation and multiple tests, we (my work team) found that what causes this is that our documents, each, contain a large Map field with at least 5 levels of multi key-value pairs.
Our map field is called "items", when we tried to remove it from the document, the realtime query works perfectly as expected.
P.S: we tried to check the size of the documents, the average was between 6k bytes and 5k bytes, and Firestore allows 1Mb (1M bytes) as a maximum document size.
To reproduce the bug, follow below steps :
Add this line into your project gradle file :
dependencies {
classpath 'com.google.gms:google-services:4.3.3'
}
Add those two lines into the module:app gradle file :
dependencies {
implementation 'com.google.firebase:firebase-firestore:21.6.0'
implementation 'com.google.code.gson:gson:2.8.6'
}
Add this code to create and write a copy of my document into
firestore :
private void createAndWriteDocument() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.setDateFormat("MMM d, yyyy HH:mm:ss");
gson = gsonBuilder.create();
FirebaseFirestore.getInstance()
.collection(COLLECTION_ORDERS)
.document("ZYaJKmQF9n1RknziD1tj")
.set(gson.fromJson(jsonOrder2, FireStoreOrder.class));
}
private final String jsonOrder2 = "{\n" +
" \"app_name\":\"Firestore-Sample\",\n" +
" \"app_version\":\"1.0.0\",\n" +
" \"canceled_at\":\"Sep 4, 2020 15:12:34\",\n" +
" \"comments_count\":4,\n" +
" \"countryID\":\"fr\",\n" +
" \"created_at\":\"Sep 4, 2020 12:21:55\",\n" +
" \"currency\":\"EUR\",\n" +
" \"delivered_at\":\"Sep 4, 2020 15:11:30\",\n" +
" \"delivery_agent_id\":\"1rvlTtfJKNVPVxZ2mp4T2CcI1Fj2\",\n" +
" \"delivery_assignment_status\":\"accepted\",\n" +
" \"delivery_fee\":5.0,\n" +
" \"distance\":3.2547,\n" +
" \"hearts_count\":0,\n" +
" \"in_progress_at\":\"Sep 4, 2020 15:06:51\",\n" +
" \"is_friends\":false,\n" +
" \"is_private\":false,\n" +
" \"is_public\":true,\n" +
" \"is_visible\":true,\n" +
" \"items\":{\n" +
" \"-MGNqMoKy8YovI11-QUK\":{\n" +
" \"category_id\":\"-LlbKEnwkC4KZtJyN691\",\n" +
" \"discount_price\":0.0,\n" +
" \"extras\":{\n" +
" \"-M1-qhcXr8tp5KpnLp9p\":{\n" +
" \"max\":10,\n" +
" \"name\":\"Chèvre\",\n" +
" \"price\":0.6,\n" +
" \"quantity\":5,\n" +
" \"row\":6\n" +
" },\n" +
" \"-M1-rHnm7Xzjo7rE73Pk\":{\n" +
" \"max\":10,\n" +
" \"name\":\"Vache kiri\",\n" +
" \"price\":0.6,\n" +
" \"quantity\":7,\n" +
" \"row\":4\n" +
" },\n" +
" \"-M1-me-3qKOqWzul67Sr\":{\n" +
" \"is_sub_extra\":true,\n" +
" \"max\":3,\n" +
" \"name\":\"Crispy Tenders\",\n" +
" \"price\":0.0,\n" +
" \"quantity\":1,\n" +
" \"row\":0\n" +
" },\n" +
" \"-M1-mKvK76SYLJBf3zh-\":{\n" +
" \"is_sub_extra\":true,\n" +
" \"max\":3,\n" +
" \"name\":\"Escalope de Poulet\",\n" +
" \"price\":0.0,\n" +
" \"quantity\":2,\n" +
" \"row\":0\n" +
" },\n" +
" \"-M1-rNaEFCyHlf9WIOaH\":{\n" +
" \"max\":10,\n" +
" \"name\":\"Raclette\",\n" +
" \"price\":0.6,\n" +
" \"quantity\":4,\n" +
" \"row\":5\n" +
" }\n" +
" },\n" +
" \"extras_title\":\"Suppléments\",\n" +
" \"ingredients\":{\n" +
" \"-MEYbO7SlOBFWUVzcvg6\":{\n" +
" \"description\":\"Ingredients description\",\n" +
" \"name\":\"Cheddar\",\n" +
" \"row\":0\n" +
" },\n" +
" \"-MEYbLvKvqPu3YZPPAjo\":{\n" +
" \"description\":\"Ingredients description\",\n" +
" \"name\":\"Laitus\",\n" +
" \"row\":0\n" +
" }\n" +
" },\n" +
" \"ingredients_title\":\"Ingrédients : Décocher pour enlever\",\n" +
" \"itemPrice\":0.0,\n" +
" \"main_image\":{\n" +
" \"ref\":\"/ZKRBeLgCauXKZ15rfRcuQTY2S1k1/-LlXe_ZbTQytlKujrhLF/products/1582717663739.jpg\",\n" +
" \"url\":\"https://firebasestorage.googleapis.com/v0/b/urban-food-a9a70.appspot.com/o/ZKRBeLgCauXKZ15rfRcuQTY2S1k1%2F-LlXe_ZbTQytlKujrhLF%2Fproducts%2F1582717663739.jpg?alt\\u003dmedia\\u0026token\\u003d1bbfd8a0-be5a-44c2-8dd9-d5a7dacf2243\"\n" +
" },\n" +
" \"max_extras\":30,\n" +
" \"name\":\"Tacos\",\n" +
" \"options\":{\n" +
" \"-LlfWYJR_zKtO1l0DjnF\":{\n" +
" \"elements\":{\n" +
" \"-LlfWj5L6weXYZUPUoGW\":{\n" +
" \"extras_title\":\"3 Viandes\",\n" +
" \"max\":1,\n" +
" \"max_extras\":3,\n" +
" \"min_extras\":3,\n" +
" \"name\":\"L : Choisir 3 Viandes\",\n" +
" \"price\":9.5,\n" +
" \"row\":0\n" +
" }\n" +
" },\n" +
" \"name\":\"Taille\",\n" +
" \"row\":-1\n" +
" },\n" +
" \"-LlfX5HY1rzcQpz1p6mG\":{\n" +
" \"elements\":{\n" +
" \"-LlfXbVB-QA-utApD3HO\":{\n" +
" \"max\":3,\n" +
" \"name\":\"Barbecue\",\n" +
" \"price\":0.0,\n" +
" \"quantity\":2,\n" +
" \"row\":0\n" +
" },\n" +
" \"-LlfXxF-7RRTZhFwXhyX\":{\n" +
" \"max\":3,\n" +
" \"name\":\"Marocaine\",\n" +
" \"price\":0.0,\n" +
" \"quantity\":2,\n" +
" \"row\":0\n" +
" }\n" +
" },\n" +
" \"max_quantity\":4,\n" +
" \"min_quantity\":1,\n" +
" \"name\":\"Sauces\",\n" +
" \"row\":3\n" +
" },\n" +
" \"-LlfWPIAjjgTiqtqEzep\":{\n" +
" \"elements\":{\n" +
" \"-LlfWPI9_w1gH1A3HTsB\":{\n" +
" \"name\":\"Tacos\",\n" +
" \"price\":0.0,\n" +
" \"row\":0\n" +
" }\n" +
" },\n" +
" \"name\":\"Type\",\n" +
" \"row\":2\n" +
" }\n" +
" },\n" +
" \"price\":0.0,\n" +
" \"product_id\":\"-LlfTFlgrNBdLZRn5xgn\",\n" +
" \"quantity\":2,\n" +
" \"sub_category_id\":\"-LlbKEnvPMIV3DnSiYlJ\"\n" +
" },\n" +
" \"-MGNqOGcRfYb-myLgc1d\":{\n" +
" \"category_id\":\"-LlkUx5iBSXhKdMYGxTA\",\n" +
" \"discount_price\":3.5,\n" +
" \"extras\":{\n" +
" \"-M2JOJaB_Gsc28GT8wEg\":{\n" +
" \"max\":2,\n" +
" \"name\":\"Harissa\",\n" +
" \"price\":0.0,\n" +
" \"quantity\":1,\n" +
" \"row\":2\n" +
" }\n" +
" },\n" +
" \"extras_title\":\"Sauces\",\n" +
" \"itemPrice\":0.0,\n" +
" \"main_image\":{\n" +
" \"ref\":\"/ZKRBeLgCauXKZ15rfRcuQTY2S1k1/-LlXe_ZbTQytlKujrhLF/products/1582809519364.jpg\",\n" +
" \"url\":\"https://firebasestorage.googleapis.com/v0/b/urban-food-a9a70.appspot.com/o/ZKRBeLgCauXKZ15rfRcuQTY2S1k1%2F-LlXe_ZbTQytlKujrhLF%2Fproducts%2F1582809519364.jpg?alt\\u003dmedia\\u0026token\\u003dabc457cb-2462-44be-886a-af83db3cb501\"\n" +
" },\n" +
" \"max_extras\":2,\n" +
" \"name\":\"Oignons frites\",\n" +
" \"options\":{\n" +
" \"-M15mpsXwAzsDRlLDHJI\":{\n" +
" \"elements\":{\n" +
" \"-M15mpsXwAzsDRlLDHJG\":{\n" +
" \"name\":\"Cheddar\",\n" +
" \"price\":0.0,\n" +
" \"row\":0\n" +
" }\n" +
" },\n" +
" \"name\":\"Au choix :\",\n" +
" \"row\":-1\n" +
" }\n" +
" },\n" +
" \"price\":3.5,\n" +
" \"product_id\":\"-M15mV_4Ui2B90GlzsaR\",\n" +
" \"quantity\":1,\n" +
" \"sub_category_id\":\"-LlkUx5h8rXECP8L_hjQ\"\n" +
" },\n" +
" \"-MGNqOxoHFGoigUXao96\":{\n" +
" \"category_id\":\"-LlkUx5iBSXhKdMYGxTA\",\n" +
" \"discount_price\":3.5,\n" +
" \"extras\":{\n" +
" \"-M2JOmBf1oN1BmUUHeiY\":{\n" +
" \"name\":\"Biggy burger\",\n" +
" \"price\":0.0,\n" +
" \"quantity\":1,\n" +
" \"row\":0\n" +
" }\n" +
" },\n" +
" \"itemPrice\":0.0,\n" +
" \"main_image\":{\n" +
" \"ref\":\"/ZKRBeLgCauXKZ15rfRcuQTY2S1k1/-LlXe_ZbTQytlKujrhLF/products/1582809369789.jpg\",\n" +
" \"url\":\"https://firebasestorage.googleapis.com/v0/b/urban-food-a9a70.appspot.com/o/ZKRBeLgCauXKZ15rfRcuQTY2S1k1%2F-LlXe_ZbTQytlKujrhLF%2Fproducts%2F1582809369789.jpg?alt\\u003dmedia\\u0026token\\u003d705593e0-e403-4931-b040-5b2261cb96e5\"\n" +
" },\n" +
" \"name\":\"Bacon frites\",\n" +
" \"options\":{\n" +
" \"-M15lyQyHs1GujtZxMtS\":{\n" +
" \"elements\":{\n" +
" \"-M15lyQxrRFaLAWGaa3i\":{\n" +
" \"name\":\"Sauce fromagère\",\n" +
" \"price\":0.0,\n" +
" \"row\":0\n" +
" }\n" +
" },\n" +
" \"name\":\"Au choix :\",\n" +
" \"row\":-1\n" +
" }\n" +
" },\n" +
" \"price\":3.5,\n" +
" \"product_id\":\"-M15lqmhF16ZOLqebPzs\",\n" +
" \"quantity\":1,\n" +
" \"sub_category_id\":\"-LlkUx5h8rXECP8L_hjQ\"\n" +
" }\n" +
" },\n" +
" \"itemsCount\":0,\n" +
" \"level_one_zone_id\":\"Île-de-France\",\n" +
" \"level_two_zone_id\":\"Paris\",\n" +
" \"order_id\":\"ZYaJKmQF9n1RknziD1tj\",\n" +
" \"order_number\":31,\n" +
" \"order_type\":\"delivery\",\n" +
" \"paid\":false,\n" +
" \"paid_with_loyalty\":0.0,\n" +
" \"picked_at\":\"Sep 4, 2020 15:12:46\",\n" +
" \"platform\":\"android\",\n" +
" \"processedAt\":{\n" +
" \"nanoseconds\":994000000,\n" +
" \"seconds\":1599228406\n" +
" },\n" +
" \"restaurant_photo\":\"https://firebasestorage.googleapis.com/v0/b/menutium-319d0.appspot.com/o/LHx3fTdtoaRlrAHSjznJSaPz9rP2%2F-MEYUb7iepk3pLwUyWX3%2Fprofile%2F1597250393877.jpg?alt\\u003dmedia\\u0026token\\u003dcbccd3fe-91fd-4397-ab34-79f5f241def2\",\n" +
" \"status\":\"picked\",\n" +
" \"store_id\":\"-MEYUb7iepk3pLwUyWX3\",\n" +
" \"store_name\":\"La Fourchette\",\n" +
" \"total_price\":50.2,\n" +
" \"updated_at\":\"Sep 7, 2020 18:54:02\",\n" +
" \"user_address\":\"166 Quai de Stalingrad, 92130 Issy-les-Moulineaux, France\\nIssy-les-Moulineaux\",\n" +
" \"user_coordinates\":\"48.8256954,2.2579879\",\n" +
" \"user_name\":\"Mo Salah\",\n" +
" \"user_phone\":\"+21650001002\",\n" +
" \"user_photo\":\"https://firebasestorage.googleapis.com/v0/b/menutium-319d0.appspot.com/o/2Bz8euUmPgMqc4Z7QZWJjLfsgV72%2Fphoto_profile?alt\\u003dmedia\\u0026token\\u003df5dcee5b-fdda-45bd-9ec3-982cfe7832bd\",\n" +
" \"user_uid\":\"2Bz8euUmPgMqc4Z7QZWJjLfsgV72\",\n" +
" \"validated_at\":\"Sep 4, 2020 15:12:42\",\n" +
" \"validatedBy\":{\n" +
" \"name\":\"Urban-Admin\",\n" +
" \"id\":\"admin\"\n" +
" }\n" +
"}";
Start a realtime query on this document :
FirebaseFirestore.getInstance()
.collection("orders")
.document("ZYaJKmQF9n1RknziD1tj")
.addSnapshotListener(new EventListener<DocumentSnapshot>() {
#Override
public void onEvent(#Nullable DocumentSnapshot value,
#Nullable FirebaseFirestoreException error) {
Log.d("testing", "onEvent triggered");
if (error != null) {
Log.i("testing", "test error : "+ error.getMessage());
}
}
});
We created two Android projects (Java code), put them into public Github repos so that anyone could reproduce the issue we are facing.
Everything is detailed into the Readme repos.
First Project repository
Second Project repository with minimal code
Before i create this question, i created an issue within the official firebase-android-sdk repository.
After five days, someone from the Firebase team answered me, they did found a bug in the Firestore sdk, fixed it, but still didn't released it, so he recommended to downgrade to older version than 21.5.0 to avoid the bug as a temporary workaround.
Github issue link here

Eclipse java ASTParser ArrayIndexOutOfBoundsException error

i'm trying to make AST of java code in eclipse.
i'm following example of https://help.eclipse.org/2019-12/index.jsp?topic=%2Forg.eclipse.jdt.doc.isv%2Freference%2Fapi%2Forg%2Feclipse%2Fjdt%2Fcore%2Fdom%2FASTParser.html
As Example of the link, i write my code to create sample AST
But, after run the code, i have ArrayIndexOutOfBoundsException error.
full code and error message is attached below
Does anyone know why this error happened?
my code
import java.util.Map;
import org.eclipse.jface.text.Document;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
public class ASTtest {
static String src = "public class Sample {\r\n" +
" public static void main(String[] args){\r\n" +
" case1();\r\n" +
" case2();\r\n" +
" case3();\r\n" +
" }\r\n" +
" static void case1(){\r\n" +
" int a = 1000;\r\n" +
" int b = 10000;\r\n" +
"\r\n" +
" for (int i = 0; i <100 ; i++) {\r\n" +
" if(a<i){\r\n" +
" a=i;\r\n" +
" }else{\r\n" +
" b--;\r\n" +
" }\r\n" +
" }\r\n" +
" }\r\n" +
" static void case2(){\r\n" +
" int a = 1000;\r\n" +
" int b = 10000;\r\n" +
" for (int i = 0; i <1000 ; i++) {\r\n" +
" if(a<i){\r\n" +
" a=i;\r\n" +
" }else{\r\n" +
" b--;\r\n" +
" }\r\n" +
" }\r\n" +
" }\r\n" +
" static void case3(){\r\n" +
" int a=0;\r\n" +
" int b=120847;\r\n" +
" while(a==10000){\r\n" +
" a++;\r\n" +
" b--;\r\n" +
" b+=200;\r\n" +
" for (int i = 0; i <1000 ; i++) {\r\n" +
" a+=1;\r\n" +
" a-=1;\r\n" +
" int k =1;\r\n" +
" while(k <10000){\r\n" +
" k++;\r\n" +
" }\r\n" +
" }\r\n" +
" }\r\n" +
" for (int i = 0; i < 900; i++) {\r\n" +
" a++;\r\n" +
" for (int j = 0; j <100 ; j++) {\r\n" +
" a--;\r\n" +
" a++;\r\n" +
" }\r\n" +
" a--;\r\n" +
" }\r\n" +
" }\r\n" +
"}\r\n" +
"";
public static void main(String[] args) {
char[] source = src.toCharArray();
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(source);
Map options = JavaCore.getOptions();
JavaCore.setComplianceOptions(JavaCore.VERSION_1_5, options);
CompilationUnit result = (CompilationUnit) parser.createAST(null);
}
}
Error message
> Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1
at org.eclipse.jdt.internal.compiler.parser.Parser.parse(Parser.java:11671)
at org.eclipse.jdt.internal.compiler.parser.Parser.parse(Parser.java:11924)
at org.eclipse.jdt.internal.compiler.parser.Parser.parse(Parser.java:11881)
at org.eclipse.jdt.internal.compiler.parser.Parser.dietParse(Parser.java:10286)
at org.eclipse.jdt.core.dom.CompilationUnitResolver.parse(CompilationUnitResolver.java:535)
at org.eclipse.jdt.core.dom.ASTParser.internalCreateAST(ASTParser.java:1227)
at org.eclipse.jdt.core.dom.ASTParser.createAST(ASTParser.java:823)
at ASTtest.main(ASTtest.java:78)
in error message , the problem line (ASTtest.java:78) is this
CompilationUnit result = (CompilationUnit) parser.createAST(null);

How to replace following code with the following changes. Please see the code snippet

I want to change the firstPattern with the secondPattern. When I am using Pattern Matcher / String.replaceAll()
I am using the following logic to replace
System.out.println(fileContent.replaceAll(firstPattern, secondPattern));
I am getting following error =
at java.util.regex.Pattern.error(Pattern.java:1955)
at java.util.regex.Pattern.closure(Pattern.java:3157)
at java.util.regex.Pattern.sequence(Pattern.java:2134)
at java.util.regex.Pattern.expr(Pattern.java:1996)
at java.util.regex.Pattern.compile(Pattern.java:1696)
at java.util.regex.Pattern.<init>(Pattern.java:1351)
at java.util.regex.Pattern.compile(Pattern.java:1028)
at java.lang.String.replaceAll(String.java:2223)
It is happening because in the first pattern I have used "{" and "}" brace. So it is throwing an error. Don't know how to replace these.
String firstPattern = "text.append(\" where \");\r\n" +
" text.append(\"ObjId\" + \" = \");\r\n" +
" text.append(getObjId().toString());\r\n" +
"\r\n" +
" text.append(\" and \");\r\n" +
" text.append(\" LastCngDTime = \");\r\n" +
"\r\n" +
" try {\r\n" +
" tempString = dbaExecObj.Get_DataConverter()\r\n" +
" .SmsTimeStampToDBMSTimestampString(LastCngDTime,\r\n" +
" \"-WQ\");\r\n" +
" } catch (Exception e) {\r\n" +
" throw new SmsTntResult(new SmsSystemResult(logger,\r\n" +
" SmsCsvWhoAmI.getMyFullyQualifiedMethodName(),\r\n" +
" SmsTntCodes.DATA_TYPE_CONVERSION_ERROR,\r\n" +
" SmsSystemResult.ERROR));\r\n" +
" }\r\n" +
"\r\n" +
" text.append(tempString);";
String secondPattern = "text.append(\" where \");\r\n" +
" text.append(\"ObjId\" + \" = \");\r\n" +
" text.append(getObjId().toString());\r\n" +
"\r\n" +
" text.append(\" and \");\r\n" +
" text.append(\" LastCngDTime = \");\r\n" +
"\r\n" +
" try {\r\n" +
" tempString = dbaExecObj.Get_DataConverter()\r\n" +
" .SmsTimeStampToDBMSTimestampString(LastCngDTime,\r\n" +
" \"-WQ\");\r\n" +
" } catch (Exception e) {\r\n" +
" throw new SmsTntResult(new SmsSystemResult(logger,\r\n" +
" SmsCsvWhoAmI.getMyFullyQualifiedMethodName(),\r\n" +
" SmsTntCodes.DATA_TYPE_CONVERSION_ERROR,\r\n" +
" SmsSystemResult.ERROR));\r\n" +
" }\r\n" +
"\r\n" +
" text.append(\"CAST(\");" +
" text.append(tempString);" +
" text.append(\" AS datetime)\");";
String fileContent = new Scanner(new File(filePath)).useDelimiter("\\A").next();
System.out.println(fileContent.replaceAll(firstPattern, secondPattern));

Opencl enabling register spilling option

I converted a raytrace algortihm for C++ from scratchapixel.com site into an opencl java(compiled for gpu) form and it doesnt work for depth values equal to or greater than 7. When I set depth to 7(or higher), compiler tells:
Error:E013:Insufficient Private Resources!
because of the semi-recursive functions that each one gets another copy of 32bit private registers(60+). I need those registers to spill to main memory so I can set higher depth values without making the kernel into an iterative version. Is enabling spilling a bad idea? If not, how can I enable it?
and if I set number of spheres to value bigger than 100ish values, compiler tells:
Frontend phase failed compilation.
Error: Creating kernel rayTraceSphereRender failed!
but total buffer number and buffer length are constant until sphereNumber=4096 so its only a change of "for loop bound" from 100 to 110 and compiler gives that error. I suspect it automatically unrolls loops and that makes bigger register pressure. This leads to higher private register needs again(and needs to be spilled again)
Here is how the kernel string is built by host:
kernelx+=
"float4 trace"+(depth+1)+"(float4 *rayorig, float4 *raydir,__global sphereObject *spheres, int sphereNum, int depth, int threadNo ){return (float4)(0,0,0,0);}";
for(int iteration=depth;iteration>=0;iteration--)
{
//here is the bloating action to make traceX(...) function semi-recursive.
kernelx+=
"float4 trace"+iteration+"(float4 *rayorig, float4 *raydir,__global sphereObject *spheres, int sphereNum, int depth, int threadNo )"
+ "{"
+ " int MAX_RAY_DEPTH="+depth+";"
+ "float facingratio =0; float fresneleffect=0;"
+ "float4 refldir=(float4)(0,0,0,0);"
+ "float4 arg00=(float4)(0,0,0,0); float4 reflection=(float4)(0,0,0,0);float4 refraction=(float4)(0,0,0,0);"
+ "float4 refrdir=(float4)(0,0,0,0); float4 arg01=(float4)(0,0,0,0); "
+ "float4 surfaceColor=(float4)(0,0,0,0);"
+ "float4 phit=(float4)(0,0,0,0); "
+ "float4 nhit=(float4)(0,0,0,0);"
+ "float bias=0.000f; "
+ "float4 traceTmpReturn=(float4)(0,0,0,0);"
+ "float tnear=100000000.0f; "
+ "sphereObject so;"
+ " initElem(&so); "
+ " for(int i=0;i<sphereNum;i++)"
+ " {"
+ " float t0=100000000.0f;float t1=100000000.0f;"
+ " if(intersect(rayorig[0],raydir[0],&t0,&t1,spheres[i].center,spheres[i].radius)==1)"
+ " {"
+ " if(t0<0){t0=t1;}"
+ " if(t0<tnear)"
+ " {"
+ " tnear=t0;"
//+ " so=&spheres[i];"
+ " copyElem(&so,spheres[i]);"
+ " }"
+ " }"
+ " }"
+ " "
+ " if(so.radius<-0.5f){ return (float4)(0,0,0,0);} "
+ ""
+ " surfaceColor=(float4)(0,0,0,0);"
+ " phit=rayorig[0]+raydir[0]*tnear;"
+ " nhit=phit-so.center;"
+ " nhit=normalize(nhit);"
+ " bias=0.001f;"
+ " bool inside=false;"
+ " if(dot3X(raydir[0],nhit)>0){nhit=-nhit; inside=true;}"
+ " if(((so.transparency > 0) || (so.reflection > 0))&& (depth<MAX_RAY_DEPTH) )"
+ " {"
+ " facingratio = -dot3X(raydir[0],nhit);"
+ " fresneleffect= mixx(pow(1.0f-facingratio,3),1.0f,0.1f);"
+ " refldir = raydir[0] - nhit*2.0f*dot3X(raydir[0],nhit);"
+ " refldir=normalize(refldir);"
+ " arg00=phit+nhit*bias;"
+ " reflection=trace"+(iteration+1)+"(&arg00,&refldir,spheres,sphereNum,depth+1,threadNo);"
+ " refraction=(float4)(0,0,0,0);"
+ " if(so.transparency>0)"
+ " {"
+ " float ior=1.1f; float eta=(inside)?ior:1/ior; "
+ " float cosi=-dot3X(nhit,raydir[0]);"
+ " float k=1.0f-eta*eta*(1.0f-cosi*cosi);"
+ " refrdir = raydir[0]*eta+nhit*(eta*cosi-sqrt(k));"
+ " refrdir=normalize(refrdir);"
+ " arg01=phit-nhit*bias;"
+ " refraction=trace"+(iteration+1)+"(&arg01,&refrdir, spheres,sphereNum, depth+1, threadNo);"
+ " "
+ " }"
+ " surfaceColor=(reflection*fresneleffect+refraction*(1.0f-fresneleffect)*so.transparency)*so.surfaceColor;"
+ ""
+ " }"
+ " else"
+ " {"
+ " for(int i=0;i<sphereNum;i++)"
+ " {"
+ " if(spheres[i].emissionColor.x>0)"
+ " {"
+ " float4 transmission=(float4)(1,1,1,1);"
+ " float4 lightDirection=spheres[i].center-phit;"
+ " lightDirection=normalize(lightDirection);"
+ " for(int j=0;j<sphereNum;j++)"
+ " {"
+ " if(i!=j)"
+ " {"
+ " float t0,t1;"
+ " float4 arg02=phit+nhit*bias;"
+ " if(intersect(arg02,lightDirection,&t0,&t1,spheres[j].center,spheres[j].radius)==1)"
+ " {"
+ " transmission= (float4)(0,0,0,0);break;"
+ " } "
+ " } "
+ " }"
+ " surfaceColor += so.surfaceColor*transmission*max(0.0f, dot3X(nhit,lightDirection))*spheres[i].emissionColor;"
+ " }"
+ " }"
+ " }"
+ ""
+ " return surfaceColor+so.emissionColor; "
+ "}";
}
kernelx+= "__kernel void rayTraceSphereRender(__global float4 *center, __global float *radius,"
+ " __global float4 *surfaceColor, __global float4 *emissionColor,"
+ " __global float *transparency,"
+ " __global float *reflection, __global float4 *image,"
+ " __global sphereObject *spheres)"+
"{"+
" int gid=get_global_id(0);" +
" int lid=get_local_id(0);"
+ " "
+ " {"
+ " int numSphr="+raytraceSphereNumber0+";"
+ " int width="+n+", height="+n+";"
+ " float invWidth = 1.0f/((float)width);"
+ " float invHeight= 1.0f/((float)height);"
+ " float fov = 30.0f; float aspectratio= ((float)width)/((float)height);"
+ " float angle=tan(3.141592653589793f*0.5f*fov/(180.0f));"
+ " int y=gid/"+n+";"
+ " "
+ " int x=gid%"+n+";"
+ " "
+ " float xx=(2.0f*((x-0.5f)*invWidth)-1.0f)*angle*aspectratio;"
+ " float yy=(1.0f-2.0f*((y-0.5f)*invHeight))*angle;"
+ " float4 raydir=(float4)(xx,yy,-1.0f,0.0f);"
+ " raydir=normalize(raydir);"
+ " float4 ref=(float4)(0,0,0,0);"
+ " float4 upp=(float4)(0,0,0,0);"
+ " upp=trace0(&ref,&raydir,spheres,numSphr,0,gid);"
+ " upp.w=1.0;"
+ " if(x>(width-width/"+sayi2+")) image[y+x*"+n+"]=upp;"
+ " "
+ " "
+ " "
+ " }"
+ " "
//
+"}";
Host: FX8150 windows7-64bit home premium, Java-64bit(Eclipse)
Device: HD7870 Catalyst 13.12
Code works fine for lower depth and sphere numbers for GPU; and no problem for CPU for whatever number of depth and sphere I set:

Adding random arrays to random arrays in java to make it equal another array

I am learning java, and from what I can tell, what I am looking to do is a rare situation.
I am trying to use an API (kindof) to randomly generate musical notes. I want it to generate 20 times so i have it in a for loop. I realize that i could have used a list for this I just dont know how I could have implemented it. The question I have is, when I try to compile this code, the first part runs. It lets me make the seed. However after that it gives me
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at co.kbcomp.music.Main.main(Main.java:64)
What could I do to prevent this? I know that what I am doing is wrong. That much I dont need to be told. What I want to know is where am I going wrong.
package co.kbcomp.music;
import java.util.*;
import org.jfugue.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.println("Please enter a number for the seed of the song");
long seed = in.nextLong();
Calendar cal = Calendar.getInstance();
Random rand;
//rand = new Random(cal.getTime());
rand = new Random(seed);
int NoteNumber = 0;
int NoteLength = 0;
int OctiveNumber = 0;
int ChordNumber = 0;
int InversionNumber = 0;
//int Duration = rand.nextInt(100 - 5) + 5;
//This keeps track of the iteration of the for loop.
String[] NN = { " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "};
String[] NL = { " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "};
String[] IN = { " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "};
String[] CN = { " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "};
String[] ON = { " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " "};
//This is what is being played
String[] note = { "A", "B", "C", "D", "E", "F", "G" };
String[] noteLength = {"", "w", "", "h", "", "q","", "i"};
String[] octive = { "","1","", "2", "", "3", "", "4", "", "5", "", "6", "", "7", "", "8", "", "9"};
String[] chord = { "", "maj", "", "min"};
String[] inversion = {"", "^", "", "^^", "", "^^^", "", "^^^^", "", "^^^^^"};
String[] key = {"",""};
String keys= " ";
String randstr = " ";
//this is the loop that defines the music legnth
for (int i = 0; i < 21; i++) {
NoteNumber = rand.nextInt(7);
NoteLength = rand.nextInt(8);
OctiveNumber = rand.nextInt(18);
ChordNumber = rand.nextInt(4);
InversionNumber = rand.nextInt(10);
NN[i] = note[NoteNumber]; // This randomly generates the note to be played.
NL[i] = noteLength[NoteLength]; // This randomly generates the length of the note.
ON[i] = octive[OctiveNumber]; // This defines the octive to be played in.
CN[i] = chord[ChordNumber]; // This is defines the major or the minor
IN[i] = inversion[InversionNumber]; // IN[i] = inversion[InversionNumber];
key[i] = NN[i] + NL[i] + ON[i] + CN[i] + IN[i];
//randstr = c[0] + " " + c[1] + " " + c[2] + " " + c[3] + " " + c[4] + " " + c[5] + " " + c[6] + " " + c[7] + " " + c[8] + " " + c[9] + " " + c[10] + " " + c[11] + " " + c[12] + " " + c[13] + " " + c[14] + " " + c[15] + " " + c[16];
keys = (key[0] + " " + key[1] + " " + key[2] + " " + key[3] + " " + key[4] + " " + key[5] + " " + key[6] + " " + key[7] + " " + key[8] + " " + key[9] + " " + key[10] + " " + key[11] + " " + key[12] + " " + key[13] + " " + key[14] + " " + key[15] + " " + key[16] + " " + key[17] + " " + key[18] + " " + key[19] + " " + key[20]);
}
System.out.println(key);
Player player = new Player();
Pattern pattern = new Pattern(key[0]);
player.play(pattern);
}
}
You declare your key array with a length of two:
String[] key = {"",""};
But then later in your for loop, you try to access elements beyond the length of your array:
keys = (key[0] + " " + key[1] + " " + key[2] + " " + key[3] + " " + key[4] +
" " + key[5] + " " + key[6] + " " + key[7] + " " + key[8] + " " + key[9] +
" " + key[10] + " " + key[11] + " " + key[12] + " " + key[13] + " " +
key[14] + " " + key[15] + " " + key[16] + " " + key[17] + " " + key[18] +
" " + key[19] + " " + key[20]);
Since your array has only a length of two, when you try to access the third element (at array index 2), you get an ArrayIndexOutOfBoundsException.
String[] key = {"",""};
...
for (int i = 0; i < 21; i++) {
...
key[i] = ....
Do you see the problem?
As you array in only 20 in length
then this
for (int i = 0; i < 21; i++) {
is going to cause an overflow
It should be < 20
Plus this code is meaningless as your key is only an array of 2
keys = (key[0] + " " + key[1] + " " + key[2] + " " + key[3] + " " + key[4] + " " + key[5] + " " + key[6] + " " + key[7] + " " + key[8] + " " + key[9] + " " + key[10] + " " + key[11] + " " + key[12] + " " + key[13] + " " + key[14] + " " + key[15] + " " + key[16] + " " + key[17] + " " + key[18] + " " + key[19] + " " + key[20]);

Categories