i am having an issue, where java is reading an array list from a YAML file of numbers, or strings, and it is interpreting the numbers as octal if it has a leading 0, and no 8-9 digit.
is there a way to force java to read the yaml field as a string?
code:
ArrayList recordrarray = (ArrayList) sect.get("recordnum");
if (recordrarray != null) {
recno = join (recordrarray, " ");
}
HAVE ALSO TRIED:
Iterator<String> iter = recordrarray.iterator();
if (iter.hasNext()) recno = " " +String.valueOf(iter.next());
System.out.println(" this recnum:" + recno);
while (iter.hasNext()){
recno += ""+String.valueOf(iter.next()));
System.out.println(" done recnum:" + String.valueOf(iter.next()));
}
the input is such:
061456 changes to 25390
061506 changes to 25414
061559 -> FINE
it took a while to figure out what it was doing, and apparently this is a common issue for java,
ideas?
thanks
edit: using jvyaml
yaml:
22:
country_code: ' '
description: ''
insection: 1
recordnum:
- 061264
type: misc
yaml loading:
import org.jvyaml.YAML;
Map structure = new HashMap();
structure = (Map) YAML.load(new FileReader(structurefn)); // load the structure file
Where are you reading the file? The problem lies in where the file contents are being read. Most likeley the recordarray list contains integers, ie. they have alreadey been parsed. Find the place where the records are being read. Maybe you are doing something like this:
int val = Integer.parseInt(record);
Use this instead:
int val = Integer.parseInt(record, 10);
Related
Here is an example of a String:
val message = "Customer name is $name saved on $date"
I needed to find every instance of $variable within the string message and replace it with querySnapShot.get(variable) and that has been answered here Previous Answer. querySnapShot here just contains data from within Firestore listener.
Here is the working Kotlin code:
val message = "Customer name is $name saved on $date"
val arr = message.split(" ").toTypedArray()
for (i in 0 until arr.size) {
val s = arr[i]
if (s.contains("$")) {
arr[i] = "+ querySnapshot.get(" + "\"" + s.substring(1) + "\"" + ")"
}
}
Log.d("Mate", java.lang.String.join(" ", *arr))
which prints:
customer name is querySnapShot.get("name") saved on querySnapshot.get("data)
literally as it is.
QUESTION:
How can I add Kotlin's expression ${} correctly while splitting and joining in order for it to treat querySnapshot.get("variable") as an expression that captures and returns dynamic data after joining? And not just a mere String.
Write
arr[i] = querySnapshot.get(s.substring(1))
The solution isn't to try to use Kotlin string templating, it's to stop putting your own code in strings when you want to run it instead!
I'm trying to load a csv file and split 'timespan' into 'begin' and 'end'. If the timespan consists of one date 'begin' and 'end' are the same.
timespan,someOtherField, ...
27.03.2017 - 31.03.2017,someOtherValue, ...
31.03.2017,someOtherValue, ...
Result:
begin,end,someOtherField
27.03.2017,31.03.2017,someOtherValue, ...
31.03.2017,31.03.2017,someOtherValue, ...
At the moment I'm loading the file line by line using OpenCSV. This works pretty good but i don't know how to split one attribute. Propably I have to parse the CSV into an array?
For any line l you can use StringTokenizer to get the tokens separated by ,:
StringTokenizer tokens = new StringTokenizer(l, ",")
The first token represents timespan, so:
String timespan = tokens.nextToken()
Then you can split timespan based on " - ", so:
String[] startEnd = timespan.split(" - ");
Finally, you have to compute the size of the startEnd, if startEnd.length == 1, then you absolutely know that start begin and end coincides, so startEnd[0],startEnd[0]
otherwise the result would look like the following startEnd[0],startEnd[1]
I hope this could help you solve the problem.
Thanks for your answer! I parsed the csv into an extra class and created an object for each record. The code below shows the splitting of the timespan. I will now rebuild a new csv file from all objects.
// Load CSV as Booking objects
ArrayList<Booking> bookings = Utils.readCSV(csvClean);
for (int i = 0; i < bookings.size(); i++) {
String timespan = bookings.get(i).getTimespan();
String begin = "";
String end = "";
if (timespan.contains(" - ")) {
// Split timespan and set values
String[] parts = timespan.split(" - ");
begin = parts[0].trim();
end = parts[1].trim();
bookings.get(i).setBegin(begin);
bookings.get(i).setEnd(end);
} else {
bookings.get(i).setBegin(timespan.trim());
bookings.get(i).setEnd(timespan.trim());
} // end if else
} // end for
I have a CSV file generated in other platform (Salesforce), by default it seems Salesforce is not handling break lines in the file generation in some large text fields, so in my CSV file I have some rows with break lines like this that I need to fix:
"column1","column2","my column with text
here the text continues
more text in the same field
here we finish this","column3","column4"
Same idea using this piece of code:
List<String> listWords = new ArrayList<String>();
listWords.add("\"Hi all");
listWords.add("This is a test");
listWords.add("of how to remove");
listWords.add("");
listWords.add("breaklines and merge all in one\"");
listWords.add("\"This is a new Line with the whole text in one row\"");
in this case I would like to merge the elements. My first approach was to check for the lines were the last char is not a ("), concatenates the next line and just like that until we see the las char contains another double quote.
this is a non working sample of what I was trying to achieve but I hope it gives you an idea
String[] csvLines = csvContent.split("\n");
Integer iterator = 0;
String mergedRows = "";
for(String row:csvLines){
newCsvfile.add(row);
if(row != null){
if(!row.isEmpty()){
String lastChar = String.valueOf(row.charAt(row.length()-1));
if(!lastChar.contains("\"")){
//row += row+" "+csvLines[iterator+1].replaceAll("\r", "").replaceAll("\n", "").replaceAll("","").replaceAll("\r\n?|\n", "");
mergedRows += row+" "+csvLines[iterator+1].replaceAll("\r", "").replaceAll("\n", "").replaceAll("","").replaceAll("\r\n?|\n", "");
row = mergedRows;
csvLines[iterator+1] = null;
}
}
newCsvfile.add(row);
}
iterator++;
}
My final result should look like (based on the list sample):
"Hi all This is a test of how to remove break lines and merge all in one"
"This is a new Line with the whole text in one row".
What is the best approach to achieve this?
In case you don't want to use a CSV reading library like #RealSkeptic suggested...
Going from your listWords to your expected solution is fairly simple:
List<String> listSentences = new ArrayList<>();
String tmp = "";
for (String s : listWords) {
tmp = tmp.concat(" " + s);
if (s.endsWith("\"")){
listSentences.add(tmp);
tmp = "";
}
}
I am using www.wordnet.princeton.edu open source dictionary with www.projects.csail.mit.edu/jwi/api/edu/mit/jwi library?
I am unable to find out antonyms of a word. People claim that this is a very good dictionary but I could not find my words in it. I need Antonyms and other related words. Good descriptions and other vocabulary info but I am unable to find what I need.
Here is my code:
List<IWordID> wordIDList = indexWordList.get(0).getWordIDs();
for(int idIndex = 0; idIndex < wordIDList.size(); idIndex++)
{
IWordID wordID = wordIDList.get(idIndex);
IWord word = m_Dict.getWord(wordID);
System.out.println("Id = " + wordID);
System.out.println(" Lemma = " + word.getLemma());
System.out.println(" Gloss = " + word.getSynset().getGloss());
ISynset synset = word.getSynset();
String LexFileName = synset.getLexicalFile().getName();
System.out.println("Lexical Name : " + LexFileName);
/** Finding stem for the word. */
WordnetStemmer stem = new WordnetStemmer(m_Dict);
//System.out.println("test" + stem.findStems(key, POS.NOUN));
ArrayList<String> antonymsList = new ArrayList<String>();
List<IWordID> relatedWords = word.getRelatedWords();
Map<IPointer, List<IWordID>> map = word.getRelatedMap();
AdjMarker marker = word.getAdjectiveMarker();
for (IWordID antonym : word.getRelatedWords()) {
String meaning = m_Dict.getWord(antonym).getLemma();
antonymsList.add(meaning);
System.out.println("Antonym: " + meaning);
System.out.println("Antonym POS: " + m_Dict.getWord(antonym).getPOS());
}
}
What I actually need? :::
I need suggestions on how can I get that relevant information from WordNet. Also, **I am open to accept any other API or library that will provide me the latest version of Dictionary, antonyms, Synonyms and well written description.** Every suggestion is appreciated.
Use IWord#getRelatedMap to get map java.util.Map<IPointer,java.util.List<IWordID>>. This map contain map of relations of current Lemma(word) with other words.
Check presence of Pointer#Antonym in this map.
Take a look at wordnet interface Artha to compare correctness of your dictionary lookup result.
There is not direct way of having list of all words. Have used a hack:
sed 's/^\ *//' index.adj | cut -f1 -d\
Dot this for all index files: index.adj, index.adv, index.noun, index.sense, index.verb
In Java, I'm trying to concatenate the Strings from an ArrayList (called filesToReport) into a single String, as I want to display all file names in a single error message in a dialog box if they do not match certain criteria in a file opener. The solution I'm using now is a StringBuilder, and in principle it works. However, the problem is that if I eg. open three files that don't match the criteria, I first get one box listing file no. 1, then a box listing files no. 1 and 2, and then finally a box listing files no. 1, 2 and 3. The last box is the single box I want. Is there a way to achieve this?
My solution so far looks as follows:
if(filesToReport.size() > 0) {
StringBuilder sb = new StringBuilder();
for(String fileToReport : filesToReport) {
sb.append(fileToReport).append(",");
}
String incompatibleFiles = sb.toString();
String errorMessage = "The following files were not loaded \n" +
"as the are incompatible: \n" +
incompatibleFiles;
JOptionPane.showMessageDialog(frame, errorMessage);
}
I can't see the problem in this code snipplet, but my guess would be that you are appending the error message to the same filesToReport List. So it will contain the previous error messages.
As you were posting here, you may have corrected your error. The behavior you describe would have been caused by a misplaced brace:
if(filesToReport.size() > 0) {
StringBuilder sb = new StringBuilder();
for(String fileToReport : filesToReport) {
sb.append(fileToReport).append(",");
String incompatibleFiles = sb.toString();
String errorMessage = "The following files were not loaded \n" +
"as the are incompatible: \n" +
incompatibleFiles;
JOptionPane.showMessageDialog(frame, errorMessage);
}
}