Get a Number from String with no default decimal separator - apache-flex

I have a TextInput where a need to return a Number.
My problem is that entered value is localized to a logged in user and that effects the decimal separator.
I seem to always get a NaN when i try to get a Number from a Polish user but it works great for English users:
Input example:
English: 23.5
Polish: 23,5
Is there a workaround for this? I have the following that doesn't work:
public function get myValue():Number {
var value:Number = new Number(StringUtil.trim(text)); //NaN with Polish
return value;
}
I have also tried the following but it also gives a NaN:
private function myValue(number:Number, precision:Number=2):Number{
var numberFormatter:NumberFormatter = getNumberFormatter(precision);
return new Number(numberFormatter.formatNumber(number));
}
private function getNumberFormatter(precision:Number=2):NumberFormatter{
var iso:String = ClientInfo.instance.language.ISOCode;
var formattedIso:String = iso.substr(0, 2)+'_'+iso.substr(2,2);
var numberFormatter:NumberFormatter = new NumberFormatter(formattedIso);
numberFormatter.fractionalDigits = precision;
numberFormatter.trailingZeros = true;
return numberFormatter;
}
When I debug the code I can see that the NumberFormatter works correctly but its always the call to new Number("23,5") that gives a NaN.

Can't test it now, but I guess it should work:
public function get myValue():Number
{
var value:Number = getNumberFormatter.parseNumber(StringUtil.trim(text));
return value;
}
I think the key is, that you should use parseNumber()!
[Update]
Here is a FlexUnit test for better understanding:
[Test]
public function test(): void
{
var number: Number = new NumberFormatter("de-DE").parseNumber("23,5");
assertEquals(23.5, number);
number = new NumberFormatter("en-US").parseNumber("23.5");
assertEquals(23.5, number);
number = new NumberFormatter("de-DE").parseNumber("1.023,456");
assertEquals(1023.456, number);
number = new NumberFormatter("pl-PL").parseNumber("1023,45");
assertEquals(1023.45, number);
number = new NumberFormatter("pl-PL").parseNumber("1.023,45");
assertTrue(isNaN(number));
number = new NumberFormatter("pl-PL").parseNumber("1 023,45");
assertEquals(1023.45, number);
number = new NumberFormatter("pl-PL").parseNumber(" 10 531 023,45 ");
assertEquals(10531023.45, number);
}
As you can see NumberFormatter handles decimal and thousands separator correctly.
If you want to format it back, then you could use it like this:
var numFmt: NumberFormatter = new NumberFormatter("pl-PL");
assertEquals("23,50", numFmt.formatNumber(numFmt.parseNumber(" 23,5 ")));
numFmt.fractionalDigits = 1;
assertEquals("23,6", numFmt.formatNumber(numFmt.parseNumber(" 23,57 ")));

Assuming your numbers are not being returned with commas between each 10^3 number group (i.e. 1,000,000 for 1 million), you could just use a replace on the commas.
Number("23,5".replace(",","."); // output Number( "23.5" ) = 23.5
That will replace all commas in the number with a period and should be read as a normal number by the system.

Related

Are Guids unique when using a U-SQL Extractor?

As these questions point out, Guid.NewGuid will return the same value for all rows due to the enforced deterministic nature of U-SQL i.e if it's scaled out if an element (vertex) needs retrying then it should return the same value....
Guid.NewGuid() always return same Guid for all rows
auto_increment in U-SQL
However.... the code example in the officials documentation for a User Defined Extractor purposefully uses Guid.NewGuid().
I'm not querying the validity of the answers for the questions above, as they are from an authoritative source (the programme manager for u-sql, so very authoritative!). However, what I'm wondering if the action of using an Extractor means NewGuid can be used as normal? Is it simply within c# expressions in u-sql and User Defined Functions in which NewGuid is unsafe?
[SqlUserDefinedExtractor(AtomicFileProcessing = true)]
public class FullDescriptionExtractor : IExtractor
{
private Encoding _encoding;
private byte[] _row_delim;
private char _col_delim;
public FullDescriptionExtractor(Encoding encoding, string row_delim = "\r\n", char col_delim = '\t')
{
this._encoding = ((encoding == null) ? Encoding.UTF8 : encoding);
this._row_delim = this._encoding.GetBytes(row_delim);
this._col_delim = col_delim;
}
public override IEnumerable<IRow> Extract(IUnstructuredReader input, IUpdatableRow output)
{
string line;
//Read the input line by line
foreach (Stream current in input.Split(_encoding.GetBytes("\r\n")))
{
using (System.IO.StreamReader streamReader = new StreamReader(current, this._encoding))
{
line = streamReader.ReadToEnd().Trim();
//Split the input by the column delimiter
string[] parts = line.Split(this._col_delim);
int count = 0; // start with first column
foreach (string part in parts)
{
if (count == 0)
{ // for column “guid”, re-generated guid
Guid new_guid = Guid.NewGuid();
output.Set<Guid>(count, new_guid);
}
else if (count == 2)
{
// for column “user”, convert to UPPER case
output.Set<string>(count, part.ToUpper());
}
else
{
// keep the rest of the columns as-is
output.Set<string>(count, part);
}
count += 1;
}
}
yield return output.AsReadOnly();
}
yield break;
}
}
https://learn.microsoft.com/en-us/azure/data-lake-analytics/data-lake-analytics-u-sql-programmability-guide#use-user-defined-extractors

Using while to get 13 digits

I am new to programming, I need to generate 13 random number using loop (while) number + 1 when the number reaches 13, I will like to store that number in text box.
Any help will be welcomed
What you see below is a 'static' class, which needs no initialization. So, with this in your project, you can just call RandomInts.GetRandomInts() and pass it on into your model for the input box to present to your user(s).
public static class RandomInts
{
private static int _x = 0;
public static int GetRandomInts()
{
var i = 0;
var rnd = new Random();
while (i < 13)
{
_x = rnd.Next();
i++;
}
return _x;
}
}
Here is with upper and lower bounds:
var x = random.[Next](minr, maxr)

How to generate a document ID or Report ID of 8 characters in .net

Can someone point me to the preferred method for generating a report or document ID? I have been looking at maybe using a guid that would be reduced down to a shorter length. We have an application that creates an ID for reports that is about 8 characters long. They appear to be using some type of hash code. Probably using a base 36 encoding scheme. But I cant seem to find a way to make the hash code come out to a length of 8 characters since people have to use them to refer to the documents. They would also be used in a disconnected environment, so you couldnt look up the next usable serialized number in the chain. Just wondering what some of you use in applications like this?
The .net Framwork provides RNGCryptoServiceProvider class which Implements a cryptographic Random Number Generator (RNG) using the implementation provided by the cryptographic service provider (CSP). This class is usually used to generate random numbers. Although I can use this class to generate unique number in some sense but it is also not collision less. Moreover while generating key we can make key more complicated by making it as alpha numeric rather than numeric only. So, I used this class along with some character masking to generate unique key of fixed length.
private string GetUniqueKey()
{
int maxSize = 8 ;
int minSize = 5 ;
char[] chars = new char[62];
string a;
a = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
chars = a.ToCharArray();
int size = maxSize ;
byte[] data = new byte[1];
RNGCryptoServiceProvider crypto = new RNGCryptoServiceProvider();
crypto.GetNonZeroBytes(data) ;
size = maxSize ;
data = new byte[size];
crypto.GetNonZeroBytes(data);
StringBuilder result = new StringBuilder(size) ;
foreach(byte b in data )
{ result.Append(chars[__b % (chars.Length - )>); }
<span class="code-keyword">return result.ToString();
}
http://www.codeproject.com/Articles/14403/Generating-Unique-Keys-in-Net
This is what I ended up using. It is a base36 encoding. I borrowed parts of the code from other people, so I cant claim that I wrote it all, but I hope this helps others. This will produce about a 12 digit record ID, or unique ID for databases etc. It uses only the last 2 digits of the year, so it should be good for 100 years.
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace Base36Converter
{
public partial class Form1 : Form
{
private const string CharList = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public Form1()
{
InitializeComponent();
}
//Base 36 number consists of only numbers and uppercase letters only.
private void button1_Click(object sender, EventArgs e)
{
if (textBox2.Text.Length > 0)
{
label3.Text = "";
//Get Date and Time Stamp
string temp1 = GetTimestamp(DateTime.Now);
//Turn it into a long number
long l = Convert.ToInt64(temp1);
//Now encode it as a base36 number.
string s1 = Encode(l);
//Get userID as a number, i.e. 1055 (User's index number) and create as a long type.
long l1 = Convert.ToInt64(textBox2.Text);
//Encode it as a base36 number.
string s2 = Encode(l1);
//Now display it as the encoded user number + datetime encoded number (Concatenated)
textBox1.Text = s2 + s1;
}
else
{
label3.Text = "User Number must be greater than 0. ie 1055";
}
}
public static String Encode(long input)
{
if (input < 0) throw new ArgumentOutOfRangeException("input", input, "input cannot be negative");
char[] clistarr = CharList.ToCharArray();
var result = new Stack<char>();
while (input != 0)
{
result.Push(clistarr[input % 36]);
input /= 36;
}
return new string(result.ToArray());
}
public static String GetTimestamp(DateTime value)
{
return value.ToString("yyMMddHHmmssffff");
}
private void Form1_Load(object sender, EventArgs e)
{
label3.Text = "";
}
}
}

How to generate random unique 16 digit number in asp.net without collision

how can i generate 16 digit unique random numbers without any repetition in c# asp.net, as i have read the concept of GUID which generate characters along with numbers but i don't want characters
kindly suggest is there any way to acheive it
You can create a random number using the Random class:
private static Random RNG = new Random();
public string Create16DigitString()
{
var builder = new StringBuilder();
while (builder.Length < 16)
{
builder.Append(RNG.Next(10).ToString());
}
return builder.ToString();
}
Ensuring that there are no collisions requires you to track all results that you have previously returned, which is in effect a memory leak (NB I do not recommend that you use this - keeping track of all previous results is a bad idea, rely on the entropy of a random string of up to 16 characters, if you want more uniqueness, increase the entropy, but I shall include it to show how it could be done):
private static HashSet<string> Results = new HashSet<string>();
public string CreateUnique16DigitString()
{
var result = Create16DigitString();
while (!Results.Add(result))
{
result = Create16DigitString();
}
return result;
}

verifying drop down values using WebDriver

I need to verify drop down values using WebDriver. i have expected values in a String array
String[] exp = {"--Title--","Mr","Mrs","Miss","Ms","Dr","Prof"};
I need to write a function that return all the values from drop down and i need to assert with expected values, Below is the code that i have written to print the values from drop down, but i need to assert those values with expected ones:-
WebElement dropdown = driver.findElement(By.id("ddlNights"));
Select select = new Select(dropdown);
List<WebElement> options = select.getOptions();
for(WebElement we:options)
{
System.out.println(we.getText());
}
Can anyone help me in writing a method that returns String array of drop down values, so that we can reuse the method for validating values in every drop down using
Assert.assertTrue(Arrays.equals(Expected,Actual))
Thanks in Advance!!!
Try this
String[] exp = {"--Title--","Mr","Mrs","Miss","Ms","Dr","Prof"};
WebElement dropdown = driver.findElement(By.id("ddlNights"));
Select select = new Select(dropdown);
List<WebElement> options = select.getOptions();
for(WebElement we:options)
{
boolean match = false;
for (int i=0; i<exp.length(); i++){
if (we.getText().equals(exp[i]){
match = true;
}
}
Assert.assertTrue(match);
}
It should compare each element with every possibility in the expected Strings. The Match will be true only in "found" state. You can play around with the message with the Assert, because it can fail anytime. So you can do something like
Assert.assertTrue(match, we.getText());
Which should write you on which webElement it did not find any match - I am not 100% sure with that line - i dont have any IDE running to verify it.
WebElement element= driver.findElement(By.xpath("//select[#class='ui-selectonemenu']"));
ArrayList<String> array = new ArrayList();
array.add("Select Tool");
array.add("Selenium");
array.add("Playwright");
Select dropdown = new Select(element);
System.out.println("Before dropdwon selection");
List<WebElement> options = dropdown.getOptions();
for(WebElement we:options)
{
int i;
boolean flag=false;
System.out.println("getting text"+we.getText());
for (i=0; i<array.size(); i++){
if (we.getText().equals(array.get(i))){
//System.out.println("string text is available in dropdown"+array.get(i)+"\n");
array.remove(i);
flag = true;
}
}
System.out.println("flag value"+flag);
if(flag==true)
{
System.out.println("flag is true"+we.getText()+"\n");
}
else
{
System.out.println("flag is false"+we.getText()+"\n");
}
}

Resources