fastest hash calculation from any language to 20 chars - android

I am looking for a conversion function in android from a string of 1-20 chars in any language (e.g. Hebrew, English, Chinese) to about 20 chars e.g. from hello world to HGWSIg2YYYqZ12OrgUjk
The hash result should be:
always the same assuming same String input
as close as possible to true-uniqueness i.e. avoiding as much as possible different strings resulting same hash string.
as fast as possible (since will be used a lot while making the UI)
The purpose is to convert a description field in firestore database to its document id, thus preventing duplicates of description automatically, with minimum overhead
I am currently using the next code which seems to work, but i am not sure that is the best approach
public static String getHash(String input)
{
try {
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
digest.update(input.getBytes());
byte[] messageDigest = digest.digest();
// Create Hex String
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) hexString.append( Integer.toHexString( 0xFF & b ) );
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
The source code is from here

If you want to add each and every char in Hashset of strings to avoid duplicate chars, as I understood:
String chars="HGWSIg2YYYqZ12OrgUjk"
Hashset<String> string=new Hashset<String>();
for(i=0;i<chars.length,i++){
string.add(chars.charAt(i));
}
when it finished you will have Hashset contains each char as element and prevent duplicates

Related

TfLite Android: Garbage values when running inference for multiple output model

I have a model that predicts the age and gender of the input image of size 160X160. I am creating a byte buffer to input the image to the model and everything works just fine when using a model with only one output.
But when I am using the tflite.runForMultipleInputsOutputs(), I am getting garbage values which are of the form -> [[F#e233 etc.
I have followed the documentation and the sample apps to the detail and have been stuck at this for almost 2 days. Please help.
I am posting my code below for reference.
The model has 2 outputs:
Edit:
age -> float32 [1, 101]
gender -> float32 [1,2]
P.S - I am not doing anything with the output as of now. I just want to see the result of the model.
String classifyImage(Bitmap bitmap){
try{
ByteBuffer byteBuffer = convertBitmaptoByteBuffer(bitmap);
float[][] out_gender = new float[1][2];
float[][] out_age = new float[1][101];
Object[] input = {byteBuffer};
Map<Integer, Object> outputs = new HashMap();
outputs.put(0, out_age);
outputs.put(1, out_gender);
interpreter.runForMultipleInputsOutputs(input, outputs);
}catch (Exception e){
e.printStackTrace();
}
return "";
}
First, I would suggest that you double-check that the outputs from your model match your output map. It seems strange to me that the gender would be a 101-dimensional array and the age a 2-dimensional one. Have you by any chance mixed those up?
Secondly, I think you are calling toString() on the float arrays. Consider using e.g. System.out.println(Arrays.deepToString(out_age)); to present the result.

Special chars like Umlaute are not saved correctly in android sqlite database

I can't save special characters like umlaute (e.g. Ä,Ü,ö, etc.) using sqlite in Android. Typing "ä" results in "\u00E4".
I've already tried following code to save a string in database, but didn't help:
ContentValues values = new ContentValues();
String content = comment.getContent().toString();
byte[] chars = content.getBytes("UTF-8");
String utf8Content = new String(chars, "UTF-8");
values.put(DBHandler.CONTENT,utf8Content);
As I know values.put accepts those characters like "ä". For some reason It can be saved in SQLite after converting that into Unicode character like "\u00E4". Simply in such case Save it in SQLite as it is and convert "\u00E4" again into "ä" when retrieving that data. Here is the method that returns those characters converting from Unicode characters.
public String getCharacterFromUnicode (String unicodeChar){
String returnString = null
try {
byte[] utf8 = unicodeChar.getBytes("UTF-8");
returnString = new String(utf8, "UTF-8");
}catch (Exception ex){
}
return returnString;
}
Which returns your "\u00E4" to "ä".
UPDATE :
If you are not sure which parts is converted to Unicode then use Apache commons-lang library to escape those,
myString = org.apache.commons.lang.StringEscapeUtils.unescapeJava(myString);
Try this
SQLiteDatabase.execSQL("PRAGMA ENCODING=UTF-8;");
or equivalent encoding you required

Convert String to Character Array? and Retrieve

How do I create a character array from a string? for example, say I have the string "Hello World"
How would I convert it to a character array?
Once converted, how do I retrieve each individual letter one by one?
My code:
public Character[] toCharacterArray(String s) {
if (s == null) {
return null;
}
Character[] array = new Character[s.length()];
for (int i = 0; i < s.length(); i++) {
array[i] = new Character(s.charAt(i));
}
return array;
}
Now if the above was implemented, how would I retrieve the returned character and how would I output it in an edit text box? using outputBox.setText(); maybe?
you can convert a String to Char array simply using toCharArray() method...
char[] charArray = string.toCharArray();
So, your updated method should be as follows...
public char[] toCharacterArray(String s) {
char[] array = s.toCharArray();
return array;
}
This appears to be a homework question, so I'm only going to give hints.
1) How would I convert it to a charterer array?
You've already done that!! However:
it would possibly be better if either you used a char[] instead of a Character[], and
if you do continue to use a Character, then it is better to use Character.valueOf(...) instead of new Character(...).
2) once converted how do I retrieve each and individual letter 1 by 1?
Use a for loop. It is one of the standard Java statements. Refer to your Java textbook, tutorial, lecture notes ...
... how would i output it in an edit text box... using outputbox.setText(????)
Use static Character.toString(char), or Character.toString() to create a String, depending on the type you have used. You can then pass that as an argument to setText ...
For details of the methods I mentioned above, read the javadocs.
Convert the string to a simple char array like this:
String test = "hello";
char[] chars = test.toCharArray();
Then you can output any particular char in the array like this:
outputbox.setText(String.valueOf(chars[i]);

Allow all characters in Android app

I am helping to develop an app for Android that uses special characters from different parts of the world at times, specifically when listing the names of people. So, a good example would be a Spanish or Swedish accent on a name. The app is not rendering these correctly. What do I need to add to web services so that these accent marks show correctly? They show correctly in my database, but not in the app.
Here is an example:
http://docs.oracle.com/javase/tutorial/i18n/text/string.html
String original;
original = new String("A" + "\u00ea" + "\u00f1" + "\u00fc" + "C");
When printed, the String named original appears as:
AêñüC
To convert the String object to UTF-8, invoke the getBytes
method and specify the appropriate encoding as a parameter.
The getBytes method returns an array of bytes in UTF-8 format. To
create a String object from an array of non-Unicode bytes, invoke the
String constructor with the encoding parameter. The code that makes
these calls is enclosed in a try block, in case the specified encoding
is unsupported:
try {
byte[] utf8Bytes = original.getBytes("UTF8");
byte[] defaultBytes = original.getBytes();
String roundTrip = new String(utf8Bytes, "UTF8");
System.out.println("roundTrip = " + roundTrip);
System.out.println();
printBytes(utf8Bytes, "utf8Bytes");
System.out.println();
printBytes(defaultBytes, "defaultBytes");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
The StringConverter program prints out the values in the utf8Bytes and defaultBytes arrays to demonstrate an
important point: The length of the converted text might not be the
same as the length of the source text. Some Unicode characters
translate into single bytes, others into pairs or triplets of bytes.

Android String Array Manipulation

I have a lengthy string in my Android program.
What I need is, I need to split each word of that string and copy that each word to a new String Array.
For eg: If the string is "I did android program" and the string array is named my_array then each index should contain values like:
my_array[0] = I
my_array[1] = did
my_array[2] = Android
my_array[3] = Program
A part of program which I did looks like this:
StringTokenizer st = new StringTokenizer(result,"|");
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
while(st.hasMoreTokens())
{
String n = (String)st.nextToken();
services1[i] = n;
Toast.makeText(appointment.this, st.nextToken(), Toast.LENGTH_SHORT).show();
}
Can any one please suggest some ideas..
Why not use String.split() ?
You can simply do
String[] my_array = myStr.split("\\s+");
Since '|' is a special character in regular expression, we need to escape it.
for(String token : result.split("\\|"))
{
Toast.makeText(appointment.this, token, Toast.LENGTH_SHORT).show();
}
You can use String.split or Android's TextUtils.split if you need to return [] when the string to split is empty.
From the StringTokenizer API docs:
StringTokenizer is a legacy class that
is retained for compatibility reasons
although its use is discouraged in new
code. It is recommended that anyone
seeking this functionality use the
split method of String or the
java.util.regex package instead.
Since String is a final class, it is by default immutable, which means you cannot make changes to your strings. If you try, a new object will be created, not the same object modified. Therefore if you know in advance that you are going to need to manipulate a String, it is wise to start with a StringBuilder class. There is also StringBuffer for handling threads. Within StringBuilder there are methods like substring():
substring(int start)
Returns a new String that contains a subsequence of characters currently contained in this character sequence.
or getChars():
getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Characters are copied from this sequence into the destination character array dst.
or delete():
delete(int start, int end)
Removes the characters in a substring of this sequence.
Then if you really need it to be a String in the end, use the String constructor(s)
String(StringBuilder builder)
Allocates a new string that contains the sequence of characters currently contained in the string builder argument.
or
String(StringBuffer buffer)
Allocates a new string that contains the sequence of characters currently contained in the string buffer argument.
Although to understand when to use String methods and when to use StringBuilder, this link or this might help. (StringBuilder comes in handy with saving on memory).

Categories

Resources