how to maintain the spaces between the characters? - autocomplete

i am using the following code
String keyword=request.getParameter("keyword");
keyword = keyword.toLowerCase();
keyword.replaceAll(" "," "); //first double space and then single space
keyword = keyword.trim();
System.out.println(keyword);
i am given the input as t s
but iam getting as
[3/12/10 12:07:10:431 IST] 0000002c SystemOut O t s // here i am getting the two spaces
how can decrease two single space
use the follwoing program
public class whitespaces {
public static void main(String []args){
try{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
System.out.println( str.replaceAll("\b\s{2,}\b", " "));
}catch(Exception e){
e.printStackTrace();
}
}
}
thanks,
murali

If your database always have only one space, you could use some keypress event to automatically ignore any occurrences of multiple spaces (by replace double spaces with single space in the search string or something).

StackOverflow has solved the same (or at least a similar) problem regarding spaces in tags, by not having them. Instead, if you want to denote a space in a tag on SO, use - (dash). You could run a query to replace all spaces with - in your database (even though it would probably take quite some time to run you'll only have to do it once). If you want to display them as spaces on the page, just do a replace when you render.

Related

Special characters other than delimiter in DelimitedLineTokenizer of FlatFileItemReader

I am trying to read unl file in Spring batch.
Use FlatFileItemReader and delimiter is "|".
001-A472468827" |N|100| The delimiter does not work when encountering this data.
Data cannot be divided by the delimiter if it contains " and spaces or if it contains the # character.
quoteCharacter doesn't seem to work.
In this situation, is there a way to import special characters such as " and # as they are?
#Bean
#StepScope
public FlatFileItemReader unlFileReader() throws MalformedURLException {
return new FlatFileItemReaderBuilder<ExampleDTO>()
.name("unlFileReader")
/*.encoding(StandardCharsets.UTF_8.name())*/
.resource(fileService.inputFileResource(UNZIP_PATH + "example.unl"))
.fieldSetMapper(new BeanWrapperFieldSetMapper<>())
.targetType(ExampleDTO.class)
.delimited().delimiter("|")
.quoteCharacter('#')
.quoteCharacter('"')
.quoteCharacter(DelimitedLineTokenizer.DEFAULT_QUOTE_CHARACTER)
.includedFields(0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,137,138,139,140,141
)
.names(ExampleDTO.getFieldNameArrays())
.build();
}
In this situation, is there a way to import special characters such as " and # as they are?
You are calling quoteCharacter() several times, note that this overrides the previous value and does not add the quote character to a list of quote characters. Only one quote character will be used (the last one added if you chain such calls).
Data cannot be divided by the delimiter if it contains " and spaces or if it contains the # character
This is because " is the default quote character. If the input contains a single ", you need to specify another delimiter (otherwise Spring Batch considers that as a "bug" in your data, which is true as the field is not correctly quoted). Here is a quick test that passes:
#Test
void testPipeDelimiter() {
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
tokenizer.setDelimiter("|");
tokenizer.setQuoteCharacter(' ');
String s = "001-A472468827\"|N|100|";
FieldSet fieldSet = tokenizer.tokenize(s);
Assertions.assertEquals("001-A472468827\"", fieldSet.readString(0));
Assertions.assertEquals("N", fieldSet.readString(1));
Assertions.assertEquals("100", fieldSet.readString(2));
}
This test shows that the " is part of the first field. The same test passes with a # in the input:
#Test
void testPipeDelimiter() {
DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
tokenizer.setDelimiter("|");
tokenizer.setQuoteCharacter(' ');
String s = "001-A472468827#|N|100|";
FieldSet fieldSet = tokenizer.tokenize(s);
Assertions.assertEquals("001-A472468827#", fieldSet.readString(0));
Assertions.assertEquals("N", fieldSet.readString(1));
Assertions.assertEquals("100", fieldSet.readString(2));
}

CwvReader not loading lines starting with #

I'm trying to load a text file (.csv) into a SQL Server database table. Each line in the file is supposed to be loaded into a single column in the table. I find that lines starting with "#" are skipped, with no error. For example, the first two of the following four lines are loaded fine, but the last two are not. Anybody knows why?
ThisLineShouldBeLoaded
This one as well
#ThisIsATestLine
#This is another test line
Here's the segment of my code:
var sqlConn = connection.StoreConnection as SqlConnection;
sqlConn.Open();
CsvReader reader = new CsvReader(new StreamReader(f), false);
using (var bulkCopy = new SqlBulkCopy(sqlConn))
{
bulkCopy.DestinationTableName = "dbo.TestTable";
try
{
reader.SkipEmptyLines = true;
bulkCopy.BulkCopyTimeout = 300;
bulkCopy.WriteToServer(reader);
reader.Dispose();
reader = null;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(ex.Message);
throw;
}
}
# is the default comment character for CsvReader. You can change the comment character by changing the Comment property of the Configuration object. You can disable comment processing altogether by setting the AllowComment property to false, eg:
reader.Configuration.AllowComments=false;
SqlBulkCopy doesn't deal with CSV files at all, it sends any data that's passed to WriteServer to the database. It doesn't care where the data came from or what it contains, as long as the column mappings match
Update
Assuming LumenWorks.Framework.IO.Csv refers to this project the comment character can be specified in the constructor. One could set it to something that wouldn't appear in a normal file, perhaps even the NUL character, the default char value :
CsvReader reader = new CsvReader(new StreamReader(f), false, escape:default);
or
CsvReader reader = new CsvReader(new StreamReader(f), false, escape : '\0');

How to cut a string from the end in UIPATH

I have this string: "C:\Procesos\rrhh\CorteDocumentos\Cortados\10001662-1_20060301_29_1_20190301.pdf" and im trying to get this part : "20190301". The problem is the lenght is not always the same. It would be:
"9001662-1_20060301_4_1_20190301".
I've tried this: item.ToString.Substring(66,8), but it doesn't work sometimes.
What can I do?.
This is a code example of what I said in my comment.
Sub Main()
Dim strFileName As String = ""
Dim di As New DirectoryInfo("C:\Users\Maniac\Desktop\test")
Dim aryFi As FileInfo() = di.GetFiles("*.pdf")
Dim fi As FileInfo
For Each fi In aryFi
Dim arrname() As String
arrname = Split(Path.GetFileNameWithoutExtension(fi.Name), "_")
strFileName = arrname(arrname.Count - 1)
Console.WriteLine(strFileName)
Next
End Sub
You could achieve this using a simple regular expressions, which has the added benefit of including pattern validation.
If you need to get exactly eight numbers from the end of file name (and after an underscore), you can use this pattern:
_(\d{8})\.pdf
And then this VB.NET line:
Regex.Match(fileName, "_(\d{8})\.pdf").Groups(1).Value
It's important to mention that Regex is by default case sensitive, so to prevent from being in a situations where "pdf" is matched and "PDF" is not, the patter can be adjusted like this:
(?i)_(\d{8})\.pdf
You can than use it directly in any expression window:
PS: You should also ensure that System.Text.RegularExpressions reference is in the Imports:
You can achieve it by this way as well :)
Path.GetFileNameWithoutExtension(Str1).Split("_"c).Last
Path.GetFileNameWithoutExtension
Returns the file name of the specified path string without the extension.
so with your String it will return to you - 10001662-1_20060301_29_1_20190301
then Split above String i.e. 10001662-1_20060301_29_1_20190301 based on _ and will return an array of string.
Last
It will return you the last element of an array returned by Split..
Regards..!!
AKsh

New Line Command (\n) Not Working With Firebase Firestore Database Strings

I'm making an app with Swift and I'm using Firebase Firestore. Firestore is a database that has some strings that I put into a UILabel. With some of my strings, I am using the new line command (or \n). So some of my strings look like this:
"This is line one\nThis is line two\nThis is line three"
But, whenever that string is retrieved, it's addetoto the UILabel and appears like this...
This is line one\nThis is line two\nThis is line three
...when it should be like this...
This is line one
This is line two
This is line three
I'm assuming that \n does not work with strings coming from a database? I've tried double escaping with \\n. Does anyone have a fix for this?
Here is the code that I am using...
database.collection("songs").whereField("storyTitle", isEqualTo: "This is the story header").getDocuments { (snapshot, error) in
for document in (snapshot?.documents)! {
self.storyBodyLabel.text = (document.data()["storyBody"] as? String)!
}
}
I got it. I simply just replaced the character "\n" from the string that I was receiving with the newline command.
label.text = stringRecived.replacingOccurrences(of: "\n", with: "\n")
Because I manually typed out my string and gave Firebase a string like
"Line one\nline two\nline three" I am replacing "\n" with "\n" But if you give Firebase a string like
"Line one
Line two
Line three"
Firebase replaces those returns with "\\n" therfore making the code
label.text = stringRecived.replacingOccurrences(of: "\\n", with: "\n")
Hope that helps!
You can use CSS whitespace property for \n, it works for me.
white-space: pre-line;
Solution: Add this to your string and you are done (for Java users):
.replace("\\n", "\n")
Example:
if (dataSnapshot.exists())
{
ArrayList<String> userlogs2 = new ArrayList<String>();
userlogs2.add(dataSnapshot.getValue().toString().replace("\\n", "\n"));
Iterator<String> it2 = userlogs2.iterator();
while (it2.hasNext()) {
appendColoredText(userlogsmessages2, it2.next() + "\n", Color.BLACK);
appendUnderlinedText(userlogsmessages2,"____________" + "\n\n", Color.parseColor("#DB808080"));
}
Firestore doesn't support any escape sequences within string values. If you write "\n" in a string, you're going to get exactly that back when you read it. If you need to store something special, you may want to encode and decode that yourself.
Tried all of the answers suggested but none worked for me. In the end, I fixed it by using "/n" in the Firestore record and, in the Swift client, the following:
label.text = stringReceived.replacingOccurrences(of: "/n", with: "\n")
For me firebase turned all \n to \\\\n , so I just reversed that change with :
theString.replaceAll( "\\\\n", "\n" );
Just posting cause I wasted some time calculating the right number of '\'
I found I could get newlines into a firestore field by using the String.fromCharCode() function. Firestore seems to need special characters in strings to be the actual character ASCII values and does not reinterpret escape characters.
i.e.
"First Line " + String.fromCharCode(13) + "second line"
100% Working
DB.collection(Global.DB_COLLECTION_PATH).document(NEWS_ID).get().addOnCompleteListener(new OnCompleteListener< DocumentSnapshot >() {
#Override
public void onComplete(#NonNull Task< DocumentSnapshot > task) {
if (task.isSuccessful()) {
body1 = task.getResult().getString("newsBody").replace("\n", "\n");
nBody.setText(body1);
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
Log.e("DB FAILED", e.getMessage());
}
});
I hope it's work for you
I noticed that when you add a string with \n to the JSON export and then upload the JSON to the Realtime Database, it acts as a newline. But if you edit that from the firebase console, it gives you back the string with \n and not a newline.
Firestore add this type----Line one\nline two\nline three
get Sting, replace and show with TextView
String sura=modellist.get(position).getSura().replace( "\n", "\n");
Working..

NullReferenceException in ItextSharp

I got the following exception in itextsharp 5.0.6 library when I am trying to parse one PDF file
here is the link of that PDF File
https://backup.filesanywhere.com/fs/v.aspx?v=8c726b8f5a6673b56b6d
try
{
string s = null;
MessageBox.Show("Not-Protected");
PdfReader read = new PdfReader(openFileDialog1.FileName);
//MessageBox.Show(read.NumberOfPages.ToString());
for (int i = 1; i <= read.NumberOfPages; i++)
{
s = PdfTextExtractor.GetTextFromPage(read, i, new SimpleTextExtractionStrategy());
MessageBox.Show(s);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
System.NullReferenceException: Object reference not set to an instance of an object.
at iTextSharp.text.pdf.PdfContentParser.ReadArray()
at iTextSharp.text.pdf.PdfContentParser.ReadPRObject()
at iTextSharp.text.pdf.PdfContentParser.Parse(List`1 ls)
at iTextSharp.text.pdf.parser.PdfContentStreamProcessor.ProcessContent(Byte[] contentBytes, PdfDictionary resources)
at iTextSharp.text.pdf.parser.PdfReaderContentParser.ProcessContent[E](Int32 pageNumber, E renderListener)
at iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(PdfReader reader, Int32 pageNumber, ITextExtractionStrategy strategy)
The content stream of the first page of the PDF contains an array start bracket '[' inside the array operand of a TJ operator. This is not allowed as the array operand of a TJ operator may only contain strings and numbers.
Furthermore there is no matching array end bracket ']' inside that array operand, so the end bracket of the array operand itself closes this (illegal) inner array and the array operand does not have a closing bracket anymore. Thus, iText parses all the remaining content stream into the array and at the end of the content stream runs into the exception.
Adobe Reader is well known to ignore certain errors and try to fix others on the run. Knowing that there are no nested arrays allowed in page content descriptions, it seems to simply ignore the illegal opening bracket. This behavior of Adobe Reader is quite a nuisance because it allows defect PDF creation software to flourish.
PS: The line in question:
[(&)110($,"#'#"0'#.\(1\(2'0',#+345467839':'#.\(1;<"'0',#;345467839':'#.\(1!=.0',#\(345467839':'+.\(1\(2'0',#+7)(5)35(5467834':'+.\(1;<"0',#;7)(5)35(5467834)[(&)110($,"#'#"0'#.\(1\(2'0',#+345467839':'#.\(1;<"'0',#;345467839':'#.\(1!=.0',#\(345467839':'+.\(1\(2'0',#+7)(5)35(5467834':'+.\(1;<"0',#;7)(5)35(5467834)(':'*!>1;<"0',#;385467837)] TJ
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>^