Is there email validator code for Java ME or BlackBerry? - validation

Is there some standard email validator code sample for Java ME or BlackBerry?

public static boolean validateEmailID(String email) {
email = email.trim();
String reverse = new StringBuffer(email).reverse().toString();
if (email == null || email.length() == 0 || email.indexOf("#") == -1) {
return false;
}
int emailLength = email.length();
int atPosition = email.indexOf("#");
int atDot = reverse.indexOf(".");
String beforeAt = email.substring(0, atPosition);
String afterAt = email.substring(atPosition + 1, emailLength);
if (beforeAt.length() == 0 || afterAt.length() == 0) {
return false;
}
for (int i = 0; email.length() - 1 > i; i++) {
char i1 = email.charAt(i);
char i2 = email.charAt(i + 1);
if (i1 == '.' && i2 == '.') {
return false;
}
}
if (email.charAt(atPosition - 1) == '.' || email.charAt(0) == '.' || email.charAt(atPosition + 1) == '.' || afterAt.indexOf("#") != -1 || atDot < 2) {
return false;
}
return true;
}

Use this code for checking the given email id is valid or not,
private static boolean validateEmailID(String email) {
if (email == null || email.length() == 0 || email.indexOf("#") == -1 || email.indexOf(" ") != -1) {
return false;
}
int emailLenght = email.length();
int atPosition = email.indexOf("#");
String beforeAt = email.substring(0, atPosition);
String afterAt = email.substring(atPosition + 1, emailLenght);
if (beforeAt.length() == 0 || afterAt.length() == 0) {
return false;
}
if (email.charAt(atPosition - 1) == '.') {
return false;
}
if (email.charAt(atPosition + 1) == '.') {
return false;
}
if (afterAt.indexOf(".") == -1) {
return false;
}
char dotCh = 0;
for (int i = 0; i < afterAt.length(); i++) {
char ch = afterAt.charAt(i);
if ((ch == 0x2e) && (ch == dotCh)) {
return false;
}
dotCh = ch;
}
if (afterAt.indexOf("#") != -1) {
return false;
}
int ind = 0;
do {
int newInd = afterAt.indexOf(".", ind + 1);
if (newInd == ind || newInd == -1) {
String prefix = afterAt.substring(ind + 1);
if (prefix.length() > 1 && prefix.length() < 6) {
break;
} else {
return false;
}
} else {
ind = newInd;
}
} while (true);
dotCh = 0;
for (int i = 0; i < beforeAt.length(); i++) {
char ch = beforeAt.charAt(i);
if (!((ch >= 0x30 && ch <= 0x39) || (ch >= 0x41 && ch <= 0x5a) || (ch >= 0x61 && ch <= 0x7a)
|| (ch == 0x2e) || (ch == 0x2d) || (ch == 0x5f))) {
return false;
}
if ((ch == 0x2e) && (ch == dotCh)) {
return false;
}
dotCh = ch;
}
return true;
}

You can simply google around for email validation regex pattern. Thats the easiest and efficient way to check email string format. see the link below.
http://www.zparacha.com/ultimate-java-regular-expression-to-validate-email-address/
http://leshazlewood.com/2006/02/04/java-email-address-validation-the-right-way-regular-expression/
You will find many other examples for regex. For Regex, check the following link.
http://www.regular-expressions.info/java.html

Related

minmax algorithm with tictactoe, wrong decision

I have this code written in Dart that implements the minmax algorithm, With a tic-tac-toe, the computer is playing as "O" and trying to maximize the score, but I get some wrong decision like this, it says (look at the top, the first is the move coordinate and the second is the score) that I have to move in (0,2). But this is not the right decision.
This is my code:
class Ai {
play(state) {
return max_Value(state);
}
// the action parameter holds the move that got as to this state
List max_Value(List state, {action}) {
List v = [null, double.negativeInfinity];
if (terminal(state)) {
return [action, utility(state)];
}
for (var action in actions(state)) {
if (v[1] == 1) return v;
v = max(v, min_Value(result(state, action), action: action));
}
return v;
}
List min_Value(List state, {action}) {
List v = [null, double.infinity];
if (terminal(state)) {
return [action, utility(state)];
}
for (var action in actions(state)) {
if (v[1] == -1) return v;
v = min(v, max_Value(result(state, action), action: action));
}
return v;
}
List min(List prv, List curr) {
return prv[1] < curr[1] ? prv : curr;
}
List max(List prv, List curr) {
return prv[1] > curr[1] ? prv : curr;
}
bool terminal(List state) {
if (state[0][0] == state[0][1] &&
state[0][0] == state[0][2] &&
state[0][0] != "") {
return true;
}
if (state[1][0] == state[1][1] &&
state[1][0] == state[1][2] &&
state[1][0] != "") {
return true;
}
if (state[2][0] == state[2][1] &&
state[2][0] == state[2][2] &&
state[2][0] != "") {
return true;
}
// vertical
if (state[0][0] == state[1][0] &&
state[0][0] == state[2][0] &&
state[0][0] != "") {
return true;
}
if (state[0][1] == state[1][1] &&
state[0][1] == state[2][1] &&
state[0][1] != "") {
return true;
}
if (state[0][2] == state[1][2] &&
state[0][2] == state[2][2] &&
state[0][2] != "") {
return true;
}
// diagonal
if (state[0][0] == state[1][1] &&
state[2][2] == state[0][0] &&
state[0][0] != "") {
return true;
}
if (state[2][0] == state[1][1] &&
state[2][0] == state[0][2] &&
state[2][0] != "") {
return true;
}
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (state[i][j] == "") {
return false;
}
}
}
return true;
}
double utility(List state) {
String winner = "";
// horizontal
if (state[0][0] == state[0][1] && state[0][0] == state[0][2]) {
winner = state[0][0];
}
if (state[1][0] == state[1][1] && state[1][0] == state[1][2]) {
winner = state[1][0];
}
if (state[2][0] == state[2][1] && state[2][0] == state[2][2]) {
winner = state[2][0];
}
// vertical
if (state[0][0] == state[1][0] && state[0][0] == state[2][0]) {
winner = state[0][0];
}
if (state[0][1] == state[1][1] && state[0][1] == state[2][1]) {
winner = state[0][1];
}
if (state[0][2] == state[1][2] && state[0][2] == state[2][2]) {
winner = state[0][2];
}
// diagonal
if (state[0][0] == state[1][1] && state[2][2] == state[0][0]) {
winner = state[0][0];
}
if (state[2][0] == state[1][1] && state[2][0] == state[0][2]) {
winner = state[2][0];
}
if (winner == "O") {
return 1;
} else if (winner == "X") {
return -1;
} else {
return 0;
}
}
List actions(List state) {
List acs = [];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (state[i][j] == "") {
acs.add([i, j]);
}
}
}
return acs;
}
List result(List state, List action) {
List newState = [
["", "", ""],
["", "", ""],
["", "", ""]
];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
newState[i][j] = state[i][j];
}
}
newState[action[0]][action[1]] = player(state);
return newState;
}
player(List state) {
int xnum = 0;
int onum = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (state[i][j] == "X") {
xnum++;
} else if (state[i][j] == "O") {
onum++;
}
}
}
if (xnum > onum) {
return "O";
} else {
return "X";
}
}
}
Some mistakes:
This needs to depend on the player to move whether you return max or min:
play(state) {
return max_Value(state);
}
Here (and same for min) v might become an action done later and not the actual action that was performed and lead to the better value.
v = max(v, min_Value(result(state, action), action: action));
Possible improvements:
With a little modification terminal could return the evaluation too and then you don't need the utility function.
You constantly evaluate player with the function. You should have to do that at most once (see first mistake). min and max know whether they are playing X or O. Everything could be simplified a lot and the number of functions reduced without increasing their complexity.

Test case neither passes nor fails in VS

In VS Express 2013, I run the following program against certain test cases written in a spec file. The code and a portion of the spec file is as follows:
struct DOB {
int date;
int month;
int year;
};
int stringToValue(char* temp) {
int num = 0;
while (*temp != '-' && *temp != '\0') {
if (((*temp) >= '0') && ((*temp) <= '9')) {
num = num * 10 + ((*temp) - '0');
++temp;
}
}
return num;
}
int isValidFormat(char* dob) {
int length = 0;
for (int i = 0; dob[i] != '\0'; ++i) {
if (!((dob[i] >= '0' && dob[i] <= '9' || dob[i] == '-')))
return 0;
++length;
}
return length;
}
int function(int value1, int value2) {
if (value1>value2) {
return 2;
}
else if (value1<value2) {
return 1;
}
else
return 0;
}
int isLeap(int year) {
if ((year % 4 == 0) && !(year % 100)) {
return 1;
}
else {
if (year % 400 == 0)
return 1;
else
return 0;
}
}
int isValid(struct DOB d) {
if (d.year>0) {
if (d.month>0 && d.month <= 12) {
if (d.month == 2 && isLeap(d.year) == 1) {
if (d.date>0 && d.date <= 29) {
return 1;
}
else if (d.date > 0 && d.date <= 28) {
return 1;
}
else
return 0;
}
else if (d.date == 1 || d.date == 3 || d.date == 5 || d.date == 7 || d.date == 8 || d.date == 10 || d.date == 12){
if (d.date > 0 && d.date <= 31) {
return 1;
}
else
return 0;
}
else {
if (d.date > 0 && d.date <= 30) {
return 1;
}
else
return 0;
}
}
else {
return 0;
}
}
else {
return 0;
}
}
int isOlder(char* dob1, char* dob2) {
struct DOB d1, d2;
if (isValidFormat(dob1)!= 10 && isValidFormat(dob2) != 10)
return -1;
d1.date = stringToValue(dob1);
d2.date = stringToValue(dob2);
d1.month = stringToValue(dob1 + 3);
d2.month = stringToValue(dob2 + 3);
d1.year = stringToValue(dob1 + 6);
d2.year = stringToValue(dob2 + 6);
if (isValid(d1) == 1 && isValid(d2) == 1) {
if (function(d1.year, d2.year) != 0)
return function(d1.year, d2.year);
else if (function(d1.month, d2.month) != 0)
return function(d1.month, d2.month);
else
return function(d1.date, d2.date);
}
else {
return -1;
}
}
In the spec file containing test cases:
TEST_METHOD(isOlderinvalid)
{
Assert::AreEqual(-1, isOlder("1000", "15-07-2000"), L"isOlder: invalid input case failed", LINE_INFO());
Assert::AreEqual(-1, isOlder("15-07-2000", "000"), L"isOlder: invalid input case failed", LINE_INFO());
Assert::AreEqual(-1, isOlder("15-0A-2000", "15-07-2000"), L"isOlder: invalid input case failed", LINE_INFO());
Assert::AreEqual(-1, isOlder("15-13-2000", "15-07-2000"), L"isOlder: invalid input case failed", LINE_INFO());
Assert::AreEqual(-1, isOlder("29-02-2001", "15-07-2000"), L"isOlder: invalid input case failed", LINE_INFO());
}
When I run the following test cases on my local compiler, I get the expected output. But when I run the tests on the above code, I neither pass nor fail the above test cases. I'm honestly not sure what's wrong. It seems like a VS-specific problem rather than a problem with my code.
Wrong error condition
// if (isValidFormat(dob1)!= 10 && isValidFormat(dob2) != 10)
if (isValidFormat(dob1)!= 10 || isValidFormat(dob2) != 10)
return -1;
When only 1 format was invalid, code called weak function stringToValue() which has an infinite loop with invalid input.
int stringToValue(char* temp) {
int num = 0;
while (*temp != '-' && *temp != '\0') {
if (((*temp) >= '0') && ((*temp) <= '9')) {
num = num * 10 + ((*temp) - '0');
++temp; // Move this to outside `if()` test
}
}
return num;
}
Perhaps additional problems.
Unclear how code "worked" on OP's local compiler. Maybe Assert() was not active.

check if tree if complete binary search tree

I'am learning about trees. I just completed problem to check if tree is complete BST or not. I'd like to know if i did it right.
Basically i just have to look for a node which has only one child, for the whole tree.
EDIT: I had definition of both complete and full binary search tree wrong as Mooing Duck pointed out. I finished coding it now, is this the solution?
int heightBST(Node* root)
{
if (root == NULL)
{
return -1;
}
int lHeight = heightBST(root->left);
int rHeight = heightBST(root->right);
return lHeight > rHeight ? 1 + lHeight : 1 + rHeight;
}
int isFullBST(Node* root)
{
if (root == NULL)
{
return 1;
}
int lHeight = heightBST(root->left);
int rHeight = heightBST(root->right);
if (lHeight != rHeight)
{
return -1;
}
if ((root->left == NULL && root->right != NULL) || (root->left != NULL && root->right == NULL))
{
return 0;
}
if (isCompleteBST(root->left) == 0 || isCompleteBST(root->right) == 0)
{
return 0;
}
return 1;
}
int isCompleteBST(Node* root)
{
if (root == NULL)
{
return 1;
}
int lHeight = heightBST(root->left);
int rHeight = heightBST(root->right);
if (lHeight - rHeight != 0 || lHeight - rHeight != 1)
{
return 0;
}
if ((root->left == NULL && root->right != NULL) || (root->left != NULL && root->right == NULL))
{
return 0;
}
if (isCompleteST(root->left) == 0 || isCompleteBST(root->right) == 0)
{
return 0;
}
return 1;
}

Kimoto Gravity Well Issue?

Can anybody explain what this code actually do and how it is re targeted the difficulty. I want my difficulty to be re targeted every 60 seconds, searching on internet find that this function will re targeted the difficulty.
I am working on Logos LGS coin.
unsigned int static KimotoGravityWell(const CBlockIndex* pindexLast, const CBlockHeader *pblock, uint64 TargetBlocksSpacingSeconds, uint64 PastBlocksMin, uint64 PastBlocksMax) {
/* current difficulty formula - kimoto gravity well */
const CBlockIndex *BlockLastSolved = pindexLast;
const CBlockIndex *BlockReading = pindexLast;
const CBlockHeader *BlockCreating = pblock;
BlockCreating = BlockCreating;
uint64 PastBlocksMass = 0;
int64 PastRateActualSeconds = 0;
int64 PastRateTargetSeconds = 0;
double PastRateAdjustmentRatio = double(1);
CBigNum PastDifficultyAverage;
CBigNum PastDifficultyAveragePrev;
double EventHorizonDeviation;
double EventHorizonDeviationFast;
double EventHorizonDeviationSlow;
if (BlockLastSolved == NULL || BlockLastSolved->nHeight == 0 || (uint64)BlockLastSolved->nHeight < PastBlocksMin) { return bnProofOfWorkLimit.GetCompact(); }
for (unsigned int i = 1; BlockReading && BlockReading->nHeight > 0; i++) {
if (PastBlocksMax > 0 && i > PastBlocksMax) { break; }
PastBlocksMass++;
if (i == 1) { PastDifficultyAverage.SetCompact(BlockReading->nBits); }
else { PastDifficultyAverage = ((CBigNum().SetCompact(BlockReading->nBits) - PastDifficultyAveragePrev) / i) + PastDifficultyAveragePrev; }
PastDifficultyAveragePrev = PastDifficultyAverage;
PastRateActualSeconds = BlockLastSolved->GetBlockTime() - BlockReading->GetBlockTime();
PastRateTargetSeconds = TargetBlocksSpacingSeconds * PastBlocksMass;
PastRateAdjustmentRatio = double(1);
if (PastRateActualSeconds < 0) { PastRateActualSeconds = 0; }
if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
PastRateAdjustmentRatio = double(PastRateTargetSeconds) / double(PastRateActualSeconds);
}
EventHorizonDeviation = 1 + (0.7084 * pow((double(PastBlocksMass)/double(144)), -1.228));
EventHorizonDeviationFast = EventHorizonDeviation;
EventHorizonDeviationSlow = 1 / EventHorizonDeviation;
if (PastBlocksMass >= PastBlocksMin) {
if ((PastRateAdjustmentRatio <= EventHorizonDeviationSlow) || (PastRateAdjustmentRatio >= EventHorizonDeviationFast)) { assert(BlockReading); break; }
}
if (BlockReading->pprev == NULL) { assert(BlockReading); break; }
BlockReading = BlockReading->pprev;
}
CBigNum bnNew(PastDifficultyAverage);
if (PastRateActualSeconds != 0 && PastRateTargetSeconds != 0) {
bnNew *= PastRateActualSeconds;
bnNew /= PastRateTargetSeconds;
}
if (bnNew > bnProofOfWorkLimit) { bnNew = bnProofOfWorkLimit; }
return bnNew.GetCompact();
}

String Encoding Umlaute

I want to send a string with a webclient and i have problems with german umlaute.
Checking with Fiddler, I see that the following conversion for the post parameter is made:
ä to %E4 (which is iso-8859-1 according to online encoder tool)
Do you know how i can achive this for WP7?
I tried already:
string urlstring = HttpUtility.UrlEncode("ä");
RESULT: %c3%a4
string urlstring1 = HttpUtility.HtmlEncode("ä");
RESULT: ä
Encoding isoenc = Encoding.GetEncoding("ISO-8859-1");
byte[] utf8characters = Encoding.UTF8.GetBytes("ä");
byte[] isoArray = Encoding.Convert(Encoding.UTF8, Encoding.GetEncoding("ISO-8859-1"),utf8characters);
string finalString = isoenc.GetString(isoArray,0, isoArray.Length);
RESULT: ä
I also checked this silverlight tool where you can create custom encoding.. without success.
I'm getting really crazy about this issue, if anyone has an idea please let me know.
Thanks,
Ralf
The solution provided by nwellnhof is good, but the HttpUtility.UrlEncode overload that takes an encoding as parameter isn't available on Windows Phone. Fortunately, by decompiling the framework assemblies, it's easy to modify it to use the encoding you want:
public class HttpUtilityEx
{
public static string UrlEncode(string url, Encoding encoding)
{
if (url == null)
{
return null;
}
byte[] bytes = encoding.GetBytes(url);
int num = 0;
int num1 = 0;
int length = (int)bytes.Length;
for (int i = 0; i < length; i++)
{
char chr = (char)bytes[i];
if (chr == ' ')
{
num++;
}
else if (!IsSafe(chr))
{
num1++;
}
}
if ((num != 0 ? true : num1 != 0))
{
byte[] hex = new byte[length + num1 * 2];
int num2 = 0;
for (int j = 0; j < length; j++)
{
byte num3 = bytes[j];
char chr1 = (char)num3;
if (IsSafe(chr1))
{
int num4 = num2;
num2 = num4 + 1;
hex[num4] = num3;
}
else if (chr1 != ' ')
{
int num5 = num2;
num2 = num5 + 1;
hex[num5] = 37;
int num6 = num2;
num2 = num6 + 1;
hex[num6] = (byte)IntToHex(num3 >> 4 & 15);
int num7 = num2;
num2 = num7 + 1;
hex[num7] = (byte)IntToHex(num3 & 15);
}
else
{
int num8 = num2;
num2 = num8 + 1;
hex[num8] = 43;
}
}
bytes = hex;
}
return encoding.GetString(bytes, 0, (int)bytes.Length);
}
private static bool IsSafe(char ch)
{
if (ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z' || ch >= '0' && ch <= '9')
{
return true;
}
char chr = ch;
if (chr != '!')
{
switch (chr)
{
case '\'':
case '(':
case ')':
case '*':
case '-':
case '.':
{
break;
}
case '+':
case ',':
{
return false;
}
default:
{
if (chr != '\u005F')
{
return false;
}
else
{
break;
}
}
}
}
return true;
}
internal static char IntToHex(int n)
{
if (n <= 9)
{
return (char)(n + 48);
}
return (char)(n - 10 + 97);
}
}
From there, you just need to call it like you would for HttpUtility:
var result = HttpUtilityEx.UrlEncode("ä", Encoding.GetEncoding("ISO-8859-1"));
HttpUtility.UrlEncode has an optional second parameter which specifies the encoding. The following should work:
Encoding isoenc = Encoding.GetEncoding("ISO-8859-1");
String urlstring = HttpUtility.UrlEncode("ä", isoenc);

Resources