parseLine(String nextLine, boolean multi) in opencsv - opencsv

I am learning opencsv now,the method parseLine(String nextLine, boolean multi) in CSVParser is a little complex. What is the mearning of the field 'inField' in the class CSVParser? What does 'inQuotes' and 'fromQuotedField' denote in method parseLine(String nextLine, boolean multi); Thanks!
about line 112 in CSVParser : private boolean inField = false ;
about 348 line in parseLine(String nextLine, boolean multi):
boolean inQuotes = false;
boolean fromQuotedField = false;

The inQuotes tells the parser that the data it is reading is inside a quoted string - so if a delemeter character is met then it is part of the string instead of a signal to start a new field.
inField has basically the same functionality but it is a global variable (and it is not dependent on quotations). The reason openCSV needs to know this is that the CSVReader feeds the one line at a time - so if there is a line feed inside one of the fields then it will take multiple calls to the CSVParser to build one complete record. Hence the parseLineMulti.
The fromQuoteFields is a new addition for feature request #60. This is used with the null field indicator to detect if you have a set of empty quotes should the field be an empty string or null.

Related

Populating an Apex Map from a SOQL query

// I have a custom metadata object named boatNames__mdt and I'm using two methods to get a list of picklist values in a String[];
First Method
Map<String, boatNames__mdt> mapEd = boatNames__mdt.getAll();
string boatTypes = (string) mapEd.values()[0].BoatPick__c;
// BoatPick__c is a textarea field (Eg: 'Yacht, Sailboat')
string[] btWRAP = new string[]{};
**btWRAP**.addAll(boatTypes.normalizeSpace().split(','));
Second Method
string[] strL = new string[]{};
Schema.DescribeFieldResult dfr = Schema.SObjectType.boatNames__mdt.fields.BoatTypesPicklist__c;
// BoatTypesPicklist__c is a picklist field (Picklist Values: 'Yacht, Sailboat')
PicklistEntry[] picklistValues = dfr.getPicklistValues();
for (PicklistEntry pick : picklistValues){
**strl**.add((string) pick.getLabel());
}
Map with SOQL query
Map<Id, BoatType__c> boatMap = new Map<Id, BoatType__c>
([Select Id, Name from BoatType__c Where Name in :btWRAP]);
When I run the above Map with SOQL query(btWRAP[]) no records show up.
But when I used it using the strl[] records do show up.
I'm stunned!
Can you please explain why two identical String[] when used in exact SOQL queries behave so different?
You are comparing different things so you get different results. Multiple fails here.
mapEd.values()[0].BoatPick__c - this takes 1st element. At random. Are you sure you have only 1 element in there? You might be getting random results, good luck debugging.
normalizeSpace() and trim() - you trim the string but after splitting you don't trim the components. You don't have Sailboat, you have {space}Sailboat
String s = 'Yacht, Sailboat';
List<String> tokens = s.normalizeSpace().split(',');
System.debug(tokens.size()); // "2"
System.debug(tokens); // "(Yacht, Sailboat)", note the extra space
System.debug(tokens[1].charAt(0)); // "32", space's ASCII number
Try splitting by "comma, optionally followed by space/tab/newline/any other whitespace symbol": s.split(',\\s*'); or call normalize in a loop over the split's results?
pick.getLabel() - in code never compare using picklist labels unless you really know what you're doing. Somebody will translate the org to German, French etc and your code will break. Compare to getValue()

Getting char value from ComboBox in JavaFX

I need to get the selected value in a combobox as of a data type char. I know how to get the selected item it's the conversion which I've got stuck on. Any suggestions?
This is the combobox and it content:
idCharCombo = new ComboBox<>();
idCharCombo.getItems().addAll("A","B","G","H","L","M","P","Z");
Now i will be using this data in a method which passes an int and a char (bellow is the use of the method where the second element is still an object rather than a char):
if (checkStaffMemberById(Integer.parseInt(idNoTxtFld.getText()), idCharCombo.getValue()) == true){
AlertBox.display("ID Validation", "ERROR! ID Already Exists.");
hope i arranged adequately
Since your combo box appears to only hold single-character strings, and you want to treat them as chars, the most obvious thing to do is to use a ComboBox<Character> instead of a ComboBox<String>. I.e. replace your declaration, which presumably looks like
ComboBox<String> idCharCombo ;
with
ComboBox<Character> idCharCombo ;
and then you can do
idCharCombo.getItems().addAll('A','B','G','H','L','M','P','Z');
Then
idCharCombo.getValue()
will return a Character which will be autounboxed to a char as needed, so your method call
checkStaffMemberById(Integer.parseInt(idNoTxtFld.getText()), idCharCombo.getValue())
should work as-is.

Cannot Solve "index was outside the bounds of the array"

I am working in C# with ASP.NET. I am familiar with this error but this time I can't solve it.
I have text in a drop-down list like this:
राम कुमार सिंह 8s2w8r
here राम कुमार सिंह is the name in HINDI while 8s2w8r is users' ID.
I need to separate these two values and need to pass them as session variables. The logic I am using is depicted in the code.
public string reverse(string s)
{
char []temp=s.ToCharArray();
Array.Reverse(temp);
return (temp.ToString());
}
string dropdowntextreversed=reverse(DropDownList1.Text);
char []delim=new char[]{' '};
string []parts=dropdowntextreversed.Split(delim,2);
string family_head_uid = reverse(parts[0]);
string family_head = reverse(parts[1]);
Session.Add("family_head", family_head);
Session.Add("family_head_uid", family_head_uid);
Response.Redirect("/WebForm1.aspx");
I always get an error as the index was outside the bounds of the array! I don't understand this because I am breaking the string into 2 parts so it should have parts[0] and parts[1]. Please suggest...
You are splitting the string into MAXIMUM 2 parts, but if there's only one you will get probably one part.
Read this documentation
Try to assert that parts.Length is == 2 or to access elemnts only there atre two elements
Try this link. As I think there is a problem in the temp.ToString() which will return System.Char[] rather than the value which are you looking for. Use string.join instead will work.
Use the following reverse method:
public string reverse(string s)
{
return String.Join(String.Empty, s.ToCharArray().Reverse());
}

Adding comma separators to numbers, asp.net

I'm trying to add comma separators to a number. I've tried the advice here: add commas using String.Format for number and and here: .NET String.Format() to add commas in thousands place for a number but I can't get it to work - they just return the number without commas. The code I'm using is here:
public static string addCommas(string cash) {
return string.Format("{0:n0}", cash).ToString();
}
Where am I going wrong?
Thanks.
Update: Hi all, thanks for your help, but all of those methods are returning the same error: "error CS1502: The best overloaded method match for 'BishopFlemingFunctions.addCommas(int)' has some invalid arguments" (or variations therof depending on what number type I'm using.) Any ideas?
Well, you are sending in a string. it looks like you want a currency back
Why are you passing in a string to the method if it is a numeric value?
String.Format will return a string so there is not need to .ToString() it again.
{0:c} = Currency format if you do not want the $ then use {0:n}
Not sure you have to but you may need to do an explicit conversion if you pass it in as a string to (decimal)cash
return String.Format("{0:c}", (decimal)cash);
or
return String.Format("{0:n}", (decimal)cash);
but i think it should be something like:
public static string addCommas(decimal cash)
{
return String.Format("{0:c}", cash);
}
but this is such a simple statement i do not see the logic in making it a method, if you method is one line, in most cases, its not a method.
In order to apply number formatting you have to pass cash as a number type (int, double, float etc)
Note the cash parameter is of type double and the .## at the end of the formatted string for cents.
EDIT
Here is the code in its entirety:
static class Program {
static void Main() {
double d = 123456789.7845;
string s = addCommas(d);
System.Console.WriteLine(s);
}
public static string addCommas(double cash) {
return string.Format("${0:#,###0.##}", cash);
}
}
This prints "$123,456,789.78" to console. If you're getting
error CS1502: The best overloaded
method match for 'addCommas(double)'
has some invalid arguments
check to make sure that you're calling the function properly and that you're actually passing in the correct data type. I encourage you to copy/paste the code I have above and run it - BY ITSELF.
i have a method on my custom class to convert any numbers
public static string ConvertToThosandSepratedNumber(object number)
{
string retValue = "";
retValue = string.Format("{0:N0}", Convert.ToDecimal(number));
return retValue;
}
Here is a fairly efficient way to Add commas for thousands place, etc.
It is written in VB.net.
It does not work for negative numbers.
Public Function AddCommas(number As Integer) As String
Dim s As String = number.ToString()
Dim sb As New StringBuilder(16)
Dim countHead As Integer = s.Length Mod 3
If countHead = 0 Then countHead = 3
sb.Append(s.Substring(0, countHead))
For I As Integer = countHead To s.Length - 1 Step 3
sb.Append(","c)
sb.Append(s.Substring(I, 3))
Next
Return sb.ToString()
End Function

How to test QueryString

I have a query string called propID and I wanna check if the passed value in it is a legal integer or not to avoid throwing an error that might reveal info about my database, how can I do it?
In other words, I want something like -but in vb.net- :
IF QueryString("propID").Content.Type = "int32" Then Proceed
You could use TryParse:
Dim myInt As Integer
If Int32.TryParse(QueryString("propID").Content, myInt) Then Proceed
Dim result as boolean
result = integer.tryparse(QueryString("propID"), myintegervariable)
boolean will return true if it parsed correctly (putting the value into your myintegervariable) and will return false if the parsing failed.
You can also write is as
if integer.tryparse(QueryString("propID"), myintegervariable) then
//continue going along with myintegervariable
else
//parsing didn't work
end if
You can just use Int32.TryParse.
You could try the 'is' keyword to check the type of on object.
If QueryString("propID").Content.Type Is Int32 Then Proceed
Otherwise Int32.TryParse would work as well.
C# version:
int _PropID;
if (int.TryParse(QueryString["propID"], out _PropID))
{
//Proceed with _PropID
}

Resources