add zero to number in wicket - wicket-1.5

I have some problem with format number in Wicket. In textfiled with can only put five digit number-(xxxxx) if I put number less than five digit like 10 it can by automatically change format like 00010 with zero .How can I do it?. Thanks for advice.

public static String leadingZeros(int value, int returnSize){
int size = (int) Math.log10(value)+1;
if (size > returnSize){
return String.valueOf(value).substring(size-returnSize);
}
StringBuilder string = new StringBuilder();
for (int i=returnSize; i>size;i--){
string.append("0");
}
string.append(value);
return string.toString();
}
Example:
System.out.println(leadingZeros(123,5));
--> 00123
System.out.println(leadingZeros(123456789,5));
--> 56789

Related

Generate unique id with 6 of length

I need to generate a unique id with a limit of 6 blocks. That id should contains letters in upper case and number.
How can I do it? I thougth in use the date, but I'm failed.
More details...
That Id just need not repeat, but should be generate alone, whithout base in a last sequence.
I can do this in any language.
I made a blog post to generate a strong SQL Server password. You can adapt this to what you need. For a better format blog post here.
We have the requirement that our passwords have to change every 90 days. I wanted to automate this and it sounded pretty easy to do, but it wasn’t that easy. Why? Because there are a lot of rules for passwords.
First, I have to store it in the web.config. So no XML special characters.
quot "
amp &
apos '
lt <
gt >
Next, If used in an OLE DB or ODBC connection string, a password must not contain the following characters: [] {}() , ; ? * ! #.
Finally, strong passwords must contains characters from at least three of the following categories:
English uppercase characters (A through Z)
English lowercase characters (a through z)
Base 10 digits (0 through 9)
Nonalphabetic characters (for example: !, $, #, %)
So keeping all of these rules in mind I created a simple class. that I can just call
public class PasswordGenerator
{
private static string CHARS_LCASE = "abcdefgijkmnopqrstwxyz";
private static string CHARS_UCASE = "ABCDEFGHJKLMNPQRSTWXYZ";
private static string CHARS_NUMERIC = "23456789";
private static string CHARS_SPECIAL = "*-+_%/";
private static string CHARS_ALL = CHARS_LCASE + CHARS_UCASE + CHARS_NUMERIC + CHARS_SPECIAL;
public static string GeneratePassword(int length)
{
char[] chars = new char[length];
Random rand = new Random();
for (int i = 0; i < length; i++)
{
switch (i)
{
case 0:
chars[i] = CHARS_LCASE[rand.Next(0, CHARS_LCASE.Length)];
break;
case 1:
chars[i] = CHARS_UCASE[rand.Next(0, CHARS_UCASE.Length)];
break;
case 2:
chars[i] = CHARS_NUMERIC[rand.Next(0, CHARS_NUMERIC.Length)];
break;
case 3:
chars[i] = CHARS_SPECIAL[rand.Next(0, CHARS_SPECIAL.Length)];
break;
default:
chars[i] = CHARS_ALL[rand.Next(0, CHARS_ALL.Length)];
break;
}
}
return new string(chars);
}
}
So now I just simply call this for a new password:
PasswordGenerator.GeneratePassword(13)

VB Console - how to get multiple input in the same line, split and store to list

Say i want to get all the numbers a user inputs in the console.
15,30 45
then I want to then split the 'string' of numbers into different substrings and store it into an array of string or list of type string. Also i want to get the max min avg and total.
Should i store the substring in a array or generic list? I prefer to store it in a list so that i can get the avg and total using list.avg and list.sum
In order to get max min avg and sum, should i convert each element into an integer or convert the whole list to another type? If so, how do i convert?
EDIT: Is there any way to let the user edit the numbers if somehow he mixed a letter or symbol?
First, you can also get the avarage or sum if its a int[] instead of List<int> since Enumerable.Sum or Enumerable.Average takes an IEnumerable<T>. So the decision depends on if you need to modify the collection afterwards. Do you want to add or remove items from it later? Then use a generic List<T>.
string input = "15,30 45";
int i = int.MinValue;
List<int> result = input.Split(new[]{' ', ','}, StringSplitOptions.RemoveEmptyEntries)
.Where(str => int.TryParse(str, out i))
.Select(str => i)
.ToList();
double avg = result.Average();
int sum = result.Sum();
You could try with this code
void Main()
{
double temp;
List<double> input = new List<double>();
string line = Console.ReadLine();
string[] parts = line.Split(' ');
foreach(string p in parts)
{
if(double.TryParse(p, out temp))
input.Add(temp);
}
double sum = input.Sum();
Console.WriteLine(sum);
}
Here I get the input from the Console.ReadLine and split the line at the space separator. Every line subpart is converted to a double value (only if it is possible to convert to a double according to your locale settings) and added to a List<double> . At this point is really simple to obtain the information you need (IEnumerable.Sum, IEnumerable.Average, etc..)

How to generate random numbers, strings and select a random choice from a drop down list in Watin?

I have not been able to find the correct syntax to use in this scenario, can anyone help?
For examples of what I would like to do:
ieInUse.TextField(Find.ById("Blah")).TypeText("Zzz"); -- I'd like to replace the 'Zzz' with just a random string.
ieInUse.GoTo("http://randomwebsite/Description/11"); -- Replacing the 11 with a random 2 numbers
I do have some opinions on testing with non deterministic data, but I'll keep them to myself as I don't know the background :)
I don't know of any built-in functionality for that, but you can easily add your own methods to do it;
static string RandomString(int len)
{
var random = new Random();
return new string(Enumerable.Range(1, len)
.Select(_ => (char)(random.Next() % 95 + 33)).ToArray());
}
static string RandomDigits(int len)
{
var random = new Random();
return new string(Enumerable.Range(1, len)
.Select(_ => (char) (random.Next()%10 + '0')).ToArray());
}
Then you can just do;
ieInUse.TextField(Find.ById("Blah")).TypeText(RandomString(7));
ieInUse.GoTo("http://randomwebsite/Description/" + RandomDigits(2));

Making a list of integers more human friendly

This is a bit of a side project I have taken on to solve a no-fix issue for work. Our system outputs a code to represent a combination of things on another thing. Some example codes are:
9-9-0-4-4-5-4-0-2-0-0-0-2-0-0-0-0-0-2-1-2-1-2-2-2-4
9-5-0-7-4-3-5-7-4-0-5-1-4-2-1-5-5-4-6-3-7-9-72
9-15-0-9-1-6-2-1-2-0-0-1-6-0-7
The max number in one of the slots I've seen so far is about 150 but they will likely go higher.
When the system was designed there was no requirement for what this code would look like. But now the client wants to be able to type it in by hand from a sheet of paper, something the code above isn't suited for. We've said we won't do anything about it, but it seems like a fun challenge to take on.
My question is where is a good place to start loss-less compressing this code? Obvious solutions such as store this code with a shorter key are not an option; our database is read only. I need to build a two way method to make this code more human friendly.
1) I agree that you definately need a checksum - data entry errors are very common, unless you have really well trained staff and independent duplicate keying with automatic crosss-checking.
2) I suggest http://en.wikipedia.org/wiki/Huffman_coding to turn your list of numbers into a stream of bits. To get the probabilities required for this, you need a decent sized sample of real data, so you can make a count, setting Ni to the number of times number i appears in the data. Then I suggest setting Pi = (Ni + 1) / (Sum_i (Ni + 1)) - which smooths the probabilities a bit. Also, with this method, if you see e.g. numbers 0-150 you could add a bit of slack by entering numbers 151-255 and setting them to Ni = 0. Another way round rare large numbers would be to add some sort of escape sequence.
3) Finding a way for people to type the resulting sequence of bits is really an applied psychology problem but here are some suggestions of ideas to pinch.
3a) Software licences - just encode six bits per character in some 64-character alphabet, but group characters in a way that makes it easier for people to keep place e.g. BC017-06777-14871-160C4
3b) UK car license plates. Use a change of alphabet to show people how to group characters e.g. ABCD0123EFGH4567IJKL...
3c) A really large alphabet - get yourself a list of 2^n words for some decent sized n and encode n bits as a word e.g. GREEN ENCHANTED LOGICIAN... -
i worried about this problem a while back. it turns out that you can't do much better than base64 - trying to squeeze a few more bits per character isn't really worth the effort (once you get into "strange" numbers of bits encoding and decoding becomes more complex). but at the same time, you end up with something that's likely to have errors when entered (confusing a 0 with an O etc). one option is to choose a modified set of characters and letters (so it's still base 64, but, say, you substitute ">" for "0". another is to add a checksum. again, for simplicity of implementation, i felt the checksum approach was better.
unfortunately i never got any further - things changed direction - so i can't offer code or a particular checksum choice.
ps i realised there's a missing step i didn't explain: i was going to compress the text into some binary form before encoding (using some standard compression algorithm). so to summarize: compress, add checksum, base64 encode; base 64 decode, check checksum, decompress.
This is similar to what I have used in the past. There are certainly better ways of doing this, but I used this method because it was easy to mirror in Transact-SQL which was a requirement at the time. You could certainly modify this to incorporate Huffman encoding if the distribution of your id's is non-random, but it's probably unnecessary.
You didn't specify language, so this is in c#, but it should be very easy to transition to any language. In the lookup you'll see commonly confused characters are omitted. This should speed up entry. I also had the requirement to have a fixed length, but it would be easy for you to modify this.
static public class CodeGenerator
{
static Dictionary<int, char> _lookupTable = new Dictionary<int, char>();
static CodeGenerator()
{
PrepLookupTable();
}
private static void PrepLookupTable()
{
_lookupTable.Add(0,'3');
_lookupTable.Add(1,'2');
_lookupTable.Add(2,'5');
_lookupTable.Add(3,'4');
_lookupTable.Add(4,'7');
_lookupTable.Add(5,'6');
_lookupTable.Add(6,'9');
_lookupTable.Add(7,'8');
_lookupTable.Add(8,'W');
_lookupTable.Add(9,'Q');
_lookupTable.Add(10,'E');
_lookupTable.Add(11,'T');
_lookupTable.Add(12,'R');
_lookupTable.Add(13,'Y');
_lookupTable.Add(14,'U');
_lookupTable.Add(15,'A');
_lookupTable.Add(16,'P');
_lookupTable.Add(17,'D');
_lookupTable.Add(18,'S');
_lookupTable.Add(19,'G');
_lookupTable.Add(20,'F');
_lookupTable.Add(21,'J');
_lookupTable.Add(22,'H');
_lookupTable.Add(23,'K');
_lookupTable.Add(24,'L');
_lookupTable.Add(25,'Z');
_lookupTable.Add(26,'X');
_lookupTable.Add(27,'V');
_lookupTable.Add(28,'C');
_lookupTable.Add(29,'N');
_lookupTable.Add(30,'B');
}
public static bool TryPCodeDecrypt(string iPCode, out Int64 oDecryptedInt)
{
//Prep the result so we can exit without having to fiddle with it if we hit an error.
oDecryptedInt = 0;
if (iPCode.Length > 3)
{
Char[] Bits = iPCode.ToCharArray(0,iPCode.Length-2);
int CheckInt7 = 0;
int CheckInt3 = 0;
if (!int.TryParse(iPCode[iPCode.Length-1].ToString(),out CheckInt7) ||
!int.TryParse(iPCode[iPCode.Length-2].ToString(),out CheckInt3))
{
//Unsuccessful -- the last check ints are not integers.
return false;
}
//Adjust the CheckInts to the right values.
CheckInt3 -= 2;
CheckInt7 -= 2;
int COffset = iPCode.LastIndexOf('M')+1;
Int64 tempResult = 0;
int cBPos = 0;
while ((cBPos + COffset) < Bits.Length)
{
//Calculate the current position.
int cNum = 0;
foreach (int cKey in _lookupTable.Keys)
{
if (_lookupTable[cKey] == Bits[cBPos + COffset])
{
cNum = cKey;
}
}
tempResult += cNum * (Int64)Math.Pow((double)31, (double)(Bits.Length - (cBPos + COffset + 1)));
cBPos += 1;
}
if (tempResult % 7 == CheckInt7 && tempResult % 3 == CheckInt3)
{
oDecryptedInt = tempResult;
return true;
}
return false;
}
else
{
//Unsuccessful -- too short.
return false;
}
}
public static string PCodeEncrypt(int iIntToEncrypt, int iMinLength)
{
int Check7 = (iIntToEncrypt % 7) + 2;
int Check3 = (iIntToEncrypt % 3) + 2;
StringBuilder result = new StringBuilder();
result.Insert(0, Check7);
result.Insert(0, Check3);
int workingNum = iIntToEncrypt;
while (workingNum > 0)
{
result.Insert(0, _lookupTable[workingNum % 31]);
workingNum /= 31;
}
if (result.Length < iMinLength)
{
for (int i = result.Length + 1; i <= iMinLength; i++)
{
result.Insert(0, 'M');
}
}
return result.ToString();
}
}

Converting non-decimal numbers to another non-decimal

Not that it's a lot of work, but the only way I know to convert a non-decimal to another non-decimal is by converting the number to decimal first, then take a second step to convert it to a new base. For example, to convert 456 (in base 7) to 567 (in base 8), I would calculate the decimal value of 456, then convert that value into base 8...
Is there a better way to go directly from 7 to 8? or any base to any other base for that matter?
Here's what I have:
//source_lang and target_lang are just the numeric symbols, they would be "0123456789" if they were decimal, and "0123456789abcdef" if hex.
private string translate(string num, string source_lang, string target_lang)
{
int b10 = 0;
string rv = "";
for (int i=num.Length-1; i>=0; i--){
b10 += source_lang.IndexOf( num[i] ) * ((int)Math.Pow(source_lang.Length, num.Length -1 - i));
}
while (b10 > 0) {
rv = target_lang[b10 % target_lang.Length] + rv;
b10 /= target_lang.Length;
}
return rv;
}
You're not really converting into base 10. You're converting it into a numeric data type instead of a string representation. If anything, you're converting it into binary :) It's worth distinguishing between "an integer" (which doesn't intrinsically have a base) and "the textual representation of an integer" (which does).
That seems like a sensible way to go, IMO. However, your conversion routines certainly aren't particularly efficient. I would separate out your code into Parse and Format methods, then the Convert method can be something like:
public static string Convert(string text, int sourceBase, int targetBase)
{
int number = Parse(text, sourceBase);
return Format(number, targetBase);
}
(You can use a string to represent the different bases if you want, of course. If you really need that sort of flexibility though, I'd be tempted to create a new class to represent a "numeric representation". That class should probably be the one to have Parse, Format and Convert in it.)

Resources