Multiple input filter android editText - android-edittext

I am applying input filter on edittext with below conditions
The input of edit text should accept numberDecimal which is defined in xml (working)
first digit of input should not be "." (dot) like ".9" (working)
edit text can have "." after first digit like "1.9" (working)
maximum length is 6 (not working)
but in this case only .(dot) filter is working, not maximum length. Please help how to make it work. I tried reverse filter setting like first dot and then maximum Length, but nothing works!
edt.setFilters(new InputFilter[]{new InputFilter.LengthFilter(6), ignoreFirstDot()});
// ignore first input as dot on edit text
public static InputFilter ignoreFirstDot() {
return new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (source.toString().startsWith(".")) {
if (dstart == 0)
return "";
}
}
return null;
}
};
}
Here is my Edit Text from XML. even though defined in xml as maxLength =6, but still not working
<EditText
android:id="#+id/edt"
android:layout_width="0dp"
android:layout_height="#dimen/margin45"
android:layout_weight=".5"
android:background="#drawable/edit_border_square"
android:inputType="numberDecimal"
android:lines="1"
android:maxLength="6"
android:maxLines="1"
android:padding="5dp"
android:singleLine="true"
android:textColor="#color/black"
android:textCursorDrawable="#drawable/color_cursor"
android:textSize="#dimen/text11" />

Related

Navigating word by word through TWebBrowser control (MSHTML)

I am trying to navigate through MSHTML (TWebBrowser) document word by word for spell checking each word. But I have problems:
1) it selects words oddly - For example "Abc: def" - the selection is "Abc" as first and ":" as second word. Also, if a word ends with space for example "Abc def" it would select "Abc " with the trailing space included. Is there a way to select only what is the word and not the trailing spaces or non-word characters? Or is this the best move can offer and it is up to programmer to filter the words correctly?
2) Is there a way to specify which delimiters it will use for example only to let it use space as a delimiter and not colons, dashes or other characters? (Microsoft docs say - "Word - Moves one or more words. A word is a collection of characters terminated by a space or other white space character. ", but it also uses other delimiters, not just space, tabs and similar)
Current code is:
bool SelectNext(bool firstonly = false)
{
DelphiInterface<IHTMLDocument2> diDoc = WB->Document;
if (diDoc)
{
DelphiInterface<IHTMLSelectionObject> diSel = diDoc->selection;
if (diSel)
{
if (firstonly) diSel->empty();
if (diSel->type_ == "None" || diSel->type_ == "Text")
{
DelphiInterface<IDispatch> diRangeDisp;
if (SUCCEEDED(diSel->createRange(diRangeDisp)) && diRangeDisp)
{
DelphiInterface<IHTMLTxtRange> diRange;
if (SUCCEEDED(diRangeDisp->QueryInterface(IID_IHTMLTxtRange, reinterpret_cast<void**>(&diRange))) && diRange)
{
int Result;
unsigned short Res;
diRange->move("word", 1, Result);
diRange->expand("word", Res);
diRange->select();
return true;
}
}
}
}
}
return false;
}
SelectNext(true); // Select the first "word"
// navigate first 200 words
for (int i = 0; i <= 200; i++)
{
SelectNext();
// do spell checking of selected word here...
}

Barcode4j - Generate check digit in an EAN13 barcode

When yo generate a barcode with Barcode4j as an image, you could obtain the human readable text, too, for instance:
EAN13 barcode example
In this picture we can see that the human readable text is: 1000000012026
In this example the barcode has been generated with the code 100000001202 and the number 6 is the check digit added by Barcode4j generator.
So, my question is: Is possible obtain the check digit of an EAN13 generated barcode with Barcode4j? Because I know how to render this as a image, but I don't know how to obtain the human readable text, as a plain text.
Regards,
Miguel.
Thanks to Barcode4j plugin, you can calculate the checksum with the barcode format you need. In Java 7, you can calculate the checkSum as this way:
private String calculateCodeWithcheckSum(String codigo){
EAN13Bean generator = new EAN13Bean();
UPCEANLogicImpl impl = generator.createLogicImpl();
codigo += impl.calcChecksum(codigo);
return codigo;
}
First, you need the EAN13 barcode format, so you can get the class that the plugin provides you, and call its only method: createLogicImpl().
This method is used to give you a class of type UPCEANLogicImpl.
This is the class you need, because you can find in it the method to calculate the checkSum. So, you only have to call the method calcChecksum giving your code (100000001202), and will give you the checkSum value (6).
You can check it in the next web: http://www.gs1.org/check-digit-calculator
Adding your code and the checkSum value will give you the value you need (1000000012026)
In case you what to compute the check digit without importing a java library here's the code:
public static String ean13CheckDigit(String barcode) {
int s = 0;
for (int i = 0; i < 12; i++) {
int c = Character.getNumericValue(barcode.charAt(i));
s += c * ( i%2 == 0? 1: 3);
}
s = (10 - s % 10) % 10;
barcode += s;
return barcode;
}

SQL CLR User Defined Function (C#) adds null character (\0) in between every existing character in String being returned

This one has kept me stumped for a couple of days now.
It's my first dabble with CLR & UDF ...
I have created a user defined function that takes a multiline String as input, scans it and replaces a certain line in the string with an alternative if found. If it is not found, it simply appends the desired line at the end. (See code)
The problem, it seems, comes when the final String (or Stringbuilder) is converted to an SqlString or SqlChars. The converted, returned String always contains the Nul character as every second character (viewing via console output, they are displayed as spaces).
I'm probably missing something fundamental on UDF and/or CLR.
Please Help!!
Code (I leave in the commented Stringbuilder which was my initial attempt... changed to normal String in a desperate attempt to find the issue):
[Microsoft.SqlServer.Server.SqlFunction]
[return: SqlFacet(MaxSize = -1, IsFixedLength = false)]
//public static SqlString udf_OmaChangeJob(String omaIn, SqlInt32 jobNumber) {
public static SqlChars udf_OmaChangeJob(String omaIn, SqlInt32 jobNumber) {
if (omaIn == null || omaIn.ToString().Length <= 0) return new SqlChars("");
String[] lines = Regex.Split(omaIn.ToString(), "\r\n");
Regex JobTag = new Regex(#"^JOB=.+$");
//StringBuilder buffer = new StringBuilder();
String buffer = String.Empty;
bool matched = false;
foreach (var line in lines) {
if (!JobTag.IsMatch(line))
//buffer.AppendLine(line);
buffer += line + "\r\n";
else {
//buffer.AppendLine("JOB=" + jobNumber);
buffer += ("JOB=" + jobNumber + "\r\n");
matched = true;
}
}
if (!matched) //buffer.AppendLine("JOB=" + jobNumber);
buffer += ("JOB=" + jobNumber) + "\r\n";
//return new SqlString(buffer.ToString().Replace("\0",String.Empty)) + "blablabla";
// buffer = buffer.Replace("\0", "|");
return new SqlChars(buffer + "\r\nTheEnd");
}
I know in my experiences, the omaIn parameter should be of type SqlString and when you go to collect its value/process it, set a local variable:
string omaString = omaIn != SqlString.Null ? omaIn.Value : string.empty;
Then when you return on any code path, to rewrap the string in C#, you'd need to set
return omaString == string.empty ? new SqlString.Null : new SqlString(omaString);
I have had some fun wrestling matches learning the intricate hand-off between local and outbound types, especially with CLR TVFs.
Hope that can help!

set maxlength in textarea

I want to set maxlength in textarea. I have defined maxlength property in textarea but it seems to be of no use. Pls help. My code:
<html:textarea styleClass="textarea" maxlength="2100" cols="60" rows="3">
Try this javascript function:
$(function(){
$("#id").keypress(function() {
var maxlen = 100; //length as you desire
if ($(this).val().length > maxlen) {
return false;
}
})
});
You have to write code for two events, keyup and copy paste so try this:
onKeyPress = "return ( this.value.length < 2100 );", onPaste = "return onTextAreaPaste(this,2100)"
Here is Js:
function onTextAreaPaste(textArea,size) {
var length = textArea.value.length;
if(window.clipboardData!=undefined)
length = textArea.value.length + window.clipboardData.getData('Text').length;
return length < size;
}
I recently came across a problem with textarea maxlength attribute because the newlines where considered as 1 in Firefox, and 2 in IE and Chrome. So I decide to go for JavaScript for handling this.
Here is how I handle the max length, its a jquery plugin, very easy to set and there's no problem with the different behaviors of browsers, plus give you a feedback of the characters used.

ANTLR best way to include meta-data in lexing/parsing (custom objects, kind of annotation)

I plan to include text metadata (like bold, font-size, etc.) in the process of parsing to achieve better recognition.
For instance, I have a given structure, where a word on its own line word/r/n which is bold and sized 24px, is the title for some article. In order to get better recognition results, I want to take the characters as well as the metadata in account. In terms of ANTRL I'm not sure how this could be done best. I'd like to do something like:
Wrap each character of the original text into a custom object with fields for the metadata and pass that to ANTLR.
Preprocess the text and insert at specific places annotations for the metadata which is considered by the grammer.
I really like to take option 1. but I'm not sure which part from ANTLR I need to subclass etc. Do I have to start at the ANTLRInputStream-Object, in order to get a proper stream for a subclassed Lexer to get custom Tokens for a subclassed Parser etc. Is there a more elegant way, especially in querying the tokens while parsing with actions in a {} block ?
If anyone has some hints and/or experiences this would be great!
EDIT:
Here is a more specific simple example: I have a file wich includes the encoding of metadata which I parse forehand. the actual text including newline look like the following:
entryOne
Here is some content one.
entryTwo
Here is some content two.
Where the titlesentryOneand entryTwo are originally font-size of 24px and the content is font-size of 12px (as exemplary given values). Char by char I create a new instance of a custom object encapsulating the character as String and the font-size.
I initialize respective objects for each of the characters with fields of the font-size, e.g for the first letter of entryOne like
MyChar aTitelChar = new MyChar("e", 24);
For the content, like the second line Here is some content one. I create instances of MyChar like:
MyChar aContentChar= new MyChar("H", 12);
All characters of the texts are wrapped in instances of the below MyChar-Class and added to a List<MyChar> in order to produce a new input for ANTLR.
below is the Java Class for the characters:
public class MyChar {
private int fontSizePx;
private String text;
public MyChar(String text, int fontSizePx) {
this.text = text;
this.fontSizePx = fontSizePx;
}
public int getFontSizePx() {
return fontSizePx;
}
public String getText() {
return text;
}
}
I want that my grammar matches the above two entries (or more formatted this way) which in turn consist each of a title and a content which is terminated with a fullstop. This grammar could look like this:
rule: entry+ NEWLINE
;
entry:
title
content
;
title:
letters NEWLINE
;
content:
(letters)+ '.' NEWLINE
;
letters:
LETTERS
;
LETTERS:
('a'..'z' | 'A'..'Z')+
;
WS:
(' ' | '\t' | 'f' ) + {$channel = HIDDEN;};
NEWLINE:'\r'? '\n';
Now, for instance, what I want to do is to find out if it's really a title of an entry by checking the font-size of all letters encompassing the title-token before titel-rule returns. In case the input conforms to the grammar but is actually some kind of mistake (the original metadata-encoded file starts with something that conforms to the title-rule but its actually the content) the author of the grammar could sort that out if he knows that the original font-size for titles is 24 and check this. If one of the letter-tokens doesn't equal to font-size 24 throw an exception/don't return/do smthg. appropriate.
The thing I'm pondering on is where to plug in the List<MyChar> to provide this functionality (to query kinds of metadata while parsing in context of ANTLR). I'm experimenting with ANTLR's Classes but as I'm new to ANTLR I thought probably some of the experienced users can point me in the right direction, like where would be a good insertion points for custom objects? should I start by implenting CharStream and override some methods? Probably there is something which ANTLR provides which I haven't found yet?
Here's one way to accomplish what I think you're going for, using the parser to manage matching input to metadata. Note that I made whitespace significant because it's part of the content and can't be skipped. I also made periods part of content to simplify the example, rather than using them as a marker.
SysEx.g
grammar SysEx;
#header {
import java.util.List;
}
#parser::members {
private List<MyChar> metadata;
private int curpos;
private boolean isTitleInput(String input) {
return isFontSizeInput(input, 24);
}
private boolean isContentInput(String input){
return isFontSizeInput(input, 12);
}
private boolean isFontSizeInput(String input, int fontSize){
List<MyChar> sublist = metadata.subList(curpos, curpos + input.length());
System.out.println(String.format("Testing metadata for input=\%s, font-size=\%d", input, fontSize));
int start = curpos;
//move our metadata pointer forward.
skipInput(input);
for (int i = 0, count = input.length(); i < count; ++i){
MyChar chardata = sublist.get(i);
char c = input.charAt(i);
if (chardata.getText().charAt(0) != c){
//This character doesn't match the metadata (ERROR!)
System.out.println(String.format("Content mismatch at metadata position \%d: metadata=(\%s,\%d); input=\%c", start + i, chardata.getText(), chardata.getFontSizePx(), c));
return false;
} else if (chardata.getFontSizePx() != fontSize){
//The font is wrong.
System.out.println(String.format("Format mismatch at metadata position \%d: metadata=(\%s,\%d); input=\%c", start + i, chardata.getText(), chardata.getFontSizePx(), c));
return false;
}
}
//All characters check out.
return true;
}
private void skipInput(String str){
curpos += str.length();
System.out.println("\t\tMoving metadata pointer ahead by " + str.length() + " to " + curpos);
}
}
rule[List<MyChar> metadata]
#init {
this.metadata = metadata;
}
: entry+ EOF
;
entry
: title content
{System.out.println("Finished reading entry.");}
;
title
: line {isTitleInput($line.text)}? newline {System.out.println("Finished reading title " + $line.text);}
;
content
: line {isContentInput($line.text)}? newline {System.out.println("Finished reading content " + $line.text);}
;
newline
: (NEWLINE{skipInput($NEWLINE.text);})+
;
line returns [String text]
#init {
StringBuilder builder = new StringBuilder();
}
#after {
$text = builder.toString();
}
: (ANY{builder.append($ANY.text);})+
;
NEWLINE:'\r'? '\n';
ANY: .; //whitespace can't be skipped because it's content.
A title is a line that matches the title metadata (size 24 font) followed by one or more newline characters.
A content is a line that matches the content metadata (size 12 font) followed by one or more newline characters. As mentioned above, I removed the check for a period for simplification.
A line is a sequence of characters that does not include newline characters.
A validating semantic predicate (the {...}? after line) is used to validate that the line matches the metadata.
Here is the code I used to test the grammar (minus imports, for brevity):
SysExGrammar.java
public class SysExGrammar {
public static void main(String[] args) throws Exception {
//Create some metadata that matches our input.
List<MyChar> matchingMetadata = new ArrayList<MyChar>();
appendMetadata(matchingMetadata, "entryOne\r\n", 24);
appendMetadata(matchingMetadata, "Here is some content one.\r\n", 12);
appendMetadata(matchingMetadata, "entryTwo\r\n", 24);
appendMetadata(matchingMetadata, "Here is some content two.\r\n", 12);
parseInput(matchingMetadata);
System.out.println("Finished example #1");
//Create some metadata that doesn't match our input (negative test).
List<MyChar> mismatchingMetadata = new ArrayList<MyChar>();
appendMetadata(mismatchingMetadata, "entryOne\r\n", 24);
appendMetadata(mismatchingMetadata, "Here is some content one.\r\n", 12);
appendMetadata(mismatchingMetadata, "entryTwo\r\n", 12); //content font size!
appendMetadata(mismatchingMetadata, "Here is some content two.\r\n", 12);
parseInput(mismatchingMetadata);
System.out.println("Finished example #2");
}
private static void parseInput(List<MyChar> metadata) throws Exception {
//Test setup
InputStream resource = SysExGrammar.class.getResourceAsStream("SysExTest.txt");
CharStream input = new ANTLRInputStream(resource);
resource.close();
SysExLexer lexer = new SysExLexer(input);
CommonTokenStream tokens = new CommonTokenStream(lexer);
SysExParser parser = new SysExParser(tokens);
parser.rule(metadata);
System.out.println("Parsing encountered " + parser.getNumberOfSyntaxErrors() + " syntax errors");
}
private static void appendMetadata(List<MyChar> metadata, String string,
int fontSize) {
for (int i = 0, count = string.length(); i < count; ++i){
metadata.add(new MyChar(string.charAt(i) + "", fontSize));
}
}
}
SysExTest.txt (note this uses Windows newlines (\r\n)
entryOne
Here is some content one.
entryTwo
Here is some content two.
Test output (trimmed; the second example has deliberately-mismatched metadata):
Parsing encountered 0 syntax errors
Finished example #1
Parsing encountered 2 syntax errors
Finished example #2
This solution requires that each MyChar corresponds to a character in the input (including newline characters, although you can remove that limitation if you like -- I would remove it if I didn't already have this answer written up ;) ).
As you can see, it's possible to tie the metadata to the parser and everything works as expected. I hope this helps.

Resources