Ejemplo n.º 1
0
        private static void RunNumberParserDemo()
        {
            // We can set up custom parser by specifying the thousands and decimal separators
            IFormatProvider format = new NumberFormatInfo { NumberGroupSeparator = ".", NumberDecimalSeparator = "," };
            NumberParser parser = new NumberParser(format);
            double result = parser.ParseDouble("5.300.199,20"); // converts to 5300199.20

            // Alternatively we can use predefined parsers which support the common European and American number formats
            double result2 = NumberParser.European.ParseDouble("5.300.199,20"); // converts to 5300199.20
            double result3 = NumberParser.American.ParseDouble("5,300,199.20"); // converts to 5300199.20
        }
        public void Parse_withStringWithNoHashNumber_ShouldReurnEmptyList()
        {
            //setup
            var parser = new NumberParser();
            string input = "This is my comment.";

            //execute
            List<int> actual = parser.Parse(input);

            //asert
            Assert.IsTrue(actual.Count == 0);
        }
        public void Parse_withNullString_ShouldReurnEmptyList()
        {
            //setup
            var parser = new NumberParser();
            string input = null;

            //execute
            List<int> actual = parser.Parse(input);

            //asert
            Assert.IsTrue(actual.Count == 0);
        }
        public void Parse_withStringWithHash3NumberSpace_ShouldReurnNumberInList()
        {
            //setup
            var parser = new NumberParser();
            List<int> expected = new List<int>() { 453 };
            string input = "Work on item #453 and updated version number.";

            //execute
            List<int> actual = parser.Parse(input);

            //asert
            CollectionAssert.AreEquivalent(expected, actual);
        }
Ejemplo n.º 5
0
        private void TestShort(string input, short expected, NumberParser parser)
        {
            short actual = parser.ParseShort(input);

            Assert.AreEqual(actual, expected);
        }
Ejemplo n.º 6
0
        private void TestDouble(string input, double expected, NumberParser parser)
        {
            double actual = parser.ParseDouble(input);

            Assert.AreEqual(actual, expected, delta);
        }
Ejemplo n.º 7
0
 public void Setup()
 {
     _parser = new NumberParser();
 }
Ejemplo n.º 8
0
 public NumberParserTests()
 {
     _numberParser = new NumberParser();
 }
 public void ctor()
 {
     var parser = new NumberParser();
     Assert.IsInstanceOfType(parser, typeof(NumberParser));
 }
Ejemplo n.º 10
0
 public void Initialize()
 {
     this.americanParser = NumberParser.American;
     this.europeanParser = NumberParser.European;
 }
Ejemplo n.º 11
0
 public Calculator(NumberParser parser)
 {
     this.parser = parser;
 }
Ejemplo n.º 12
0
 public void GetOnesDigitString_Should_Return_Correctly(byte value, bool specialCase, bool includeZero, string expected)
 {
     NumberParser.GetOnesDigitString(value, specialCase, includeZero).Should().Be(expected);
 }
Ejemplo n.º 13
0
 public void GetGroupString_Should_Return_Correctly(int value, DigitGroupEnum group, bool includeZero, bool includeAnd, string expected)
 {
     NumberParser.GetGroupString(value, group, includeZero, includeAnd).Should().Be(expected);
 }
        public void Parse_withStringWithMultipleHashNumbers_ShouldReurnNumbersInList()
        {
            //setup
            var parser = new NumberParser();
            List<int> expected = new List<int>() { 12, 453 };
            string input = "Work on item #453 and #12.";

            //execute
            List<int> actual = parser.Parse(input);

            //asert
            CollectionAssert.AreEquivalent(expected, actual);
        }
Ejemplo n.º 15
0
        private void TestLong(string input, long expected, NumberParser parser)
        {
            long actual = parser.ParseLong(input);

            Assert.AreEqual(actual, expected);
        }
Ejemplo n.º 16
0
 public override void writeValue(decimal value, JsonWriter writer)
 {
     writer.WriteValue(NumberParser.ToString(value));
 }
 /// <summary>
 /// Determines if value can be parsed to the underlying type.
 /// </summary>
 /// <param name="value"></param>
 /// <returns>True if the String can be parsed correctly.</returns>
 public override bool canParseString(string value)
 {
     double tryVal;
     return NumberParser.TryParse(value, out tryVal);
 }
Ejemplo n.º 18
0
 private void TestLong(string input, long expected, NumberParser parser)
 {
     long actual = parser.ParseLong(input);
     Assert.AreEqual(actual, expected);
 }
Ejemplo n.º 19
0
 public NumberParserTests()
 {
     _sut = new NumberParser(_parsingConfig);
 }
Ejemplo n.º 20
0
 private void TestFloat(string input, float expected, NumberParser parser)
 {
     float actual = parser.ParseFloat(input);
     Assert.AreEqual(actual, expected, delta);
 }
Ejemplo n.º 21
0
 public void Setup()
 {
     _numberParserSUT = new NumberParser();
 }
Ejemplo n.º 22
0
 public override ulong parseValue(JsonReader xmlReader)
 {
     return(NumberParser.ParseUlong(xmlReader.ReadAsString()));
 }
Ejemplo n.º 23
0
 public override string valueToString(sbyte value)
 {
     return(NumberParser.ToString(value));
 }
Ejemplo n.º 24
0
 /// <summary>
 /// Set the value of this type as a string.
 /// </summary>
 /// <param name="value">The string to set as the value.</param>
 public override void setValueString(string value)
 {
     setValue(NumberParser.ParseUint(value));
 }
Ejemplo n.º 25
0
 public override sbyte parseValue(XmlReader xmlReader)
 {
     return(NumberParser.ParseSbyte(xmlReader.ReadElementContentAsString()));
 }
Ejemplo n.º 26
0
        private void TestFloat(string input, float expected, NumberParser parser)
        {
            float actual = parser.ParseFloat(input);

            Assert.AreEqual(actual, expected, delta);
        }
Ejemplo n.º 27
0
 public override string valueToString(ushort value)
 {
     return(NumberParser.ToString(value));
 }
Ejemplo n.º 28
0
 public void Initialize()
 {
     this.americanParser = NumberParser.American;
     this.europeanParser = NumberParser.European;
 }
Ejemplo n.º 29
0
 public override ushort parseValue(XmlReader xmlReader)
 {
     return(NumberParser.ParseUshort(xmlReader.ReadElementContentAsString()));
 }
Ejemplo n.º 30
0
        private void TestInteger(string input, int expected, NumberParser parser)
        {
            int actual = parser.ParseInteger(input);

            Assert.AreEqual(actual, expected);
        }
Ejemplo n.º 31
0
        //Format { "Saveable": "Id" }

        public override void readValue(LoadControl loadControl, String name, JsonReader xmlReader)
        {
            loadControl.addObjectValue(name, NumberParser.ParseLong(xmlReader.ReadAsString()));
        }
Ejemplo n.º 32
0
        public EbnfGrammar(EbnfStyle style)
            : base("ebnf")
        {
            Style = style;
            DefineCommonNonTerminals = true;
            GenerateSpecialSequences();

            // terminals
            var comment         = style.HasFlag(EbnfStyle.BracketComments) ? new GroupParser("(*", "*)") : new GroupParser("/*", "*/");
            var ows             = -(Terminals.WhiteSpace | comment);
            var rws             = +(Terminals.WhiteSpace | comment);
            var hex_character   = ("#x" & +Terminals.HexDigit);
            var character       = (("\\" & Terminals.AnyChar) | hex_character | Terminals.AnyChar.Except("]")).WithName("character");
            var character_range = (character & "-" & character).WithName("character range");
            var character_set   = ("[" & ~(Parser)"^" & +(character_range | character) & "]").WithName("character set");
            var terminal_string = new StringParser {
                QuoteCharacters = new [] { '\"', '\'', '’' }, Name = "terminal string"
            };
            var special_sequence         = ("?" & (+Terminals.AnyChar).Until("?").WithName("name") & "?").WithName("special sequence");
            var meta_identifier_terminal = Terminals.Letter & -(Terminals.LetterOrDigit | '_');
            var integer = new NumberParser().WithName("integer");

            // nonterminals
            var    definition_list   = new RepeatParser(0).WithName("definition list");
            var    single_definition = new RepeatParser(1).WithName("single definition");
            var    term            = new SequenceParser().WithName("term");
            var    primary         = new AlternativeParser().WithName("primary");
            var    exception       = new UnaryParser("exception");
            var    factor          = new SequenceParser().WithName("factor");
            var    meta_identifier = new RepeatParser(1).WithName("meta identifier");
            var    syntax_rule     = new SequenceParser().WithName("syntax rule");
            var    rule_equals     = new AlternativeParser().WithName("equals");
            Parser meta_reference  = meta_identifier;

            Parser grouped_sequence = ("(" & ows & definition_list & ows & ")").WithName("grouped sequence");

            if (style.HasFlag(EbnfStyle.SquareBracketAsOptional))
            {
                primary.Add(("[" & ows & definition_list & ows & "]").WithName("optional sequence"));
            }

            if (!style.HasFlag(EbnfStyle.CardinalityFlags))
            {
                var repeated_sequence = ("{" & ows & definition_list & ows & "}").WithName("repeated sequence");
                primary.Add(repeated_sequence);
            }

            // rules
            meta_identifier.Inner     = meta_identifier_terminal;
            meta_identifier.Separator = +(Terminals.SingleLineWhiteSpace);
            if (!style.HasFlag(EbnfStyle.CommaSeparator))
            {
                // w3c identifiers must be a single word
                meta_identifier.Maximum = 1;
                meta_reference          = meta_reference.NotFollowedBy(ows & rule_equals);
            }
            primary.Add(grouped_sequence, meta_reference, terminal_string, special_sequence);
            if (style.HasFlag(EbnfStyle.CharacterSets) && !style.HasFlag(EbnfStyle.SquareBracketAsOptional))
            {
                // w3c supports character sets
                primary.Add(hex_character.Named("hex character"));
                primary.Add(character_set);
            }
            if (style.HasFlag(EbnfStyle.NumericCardinality))
            {
                factor.Add(~(integer & ows & "*" & ows));
            }
            factor.Add(primary);
            if (style.HasFlag(EbnfStyle.CardinalityFlags))
            {
                // w3c defines cardinality at the end of a factor
                var flags = style.HasFlag(EbnfStyle.SquareBracketAsOptional) ? "*+" : "?*+";
                factor.Add(~(ows & Terminals.Set(flags).WithName("cardinality")));
            }
            term.Add(factor, ~(ows & "-" & ows & exception));
            exception.Inner             = term;
            single_definition.Inner     = term;
            single_definition.Separator = style.HasFlag(EbnfStyle.CommaSeparator) ? (Parser)(ows & "," & ows) : ows;
            definition_list.Inner       = single_definition;
            definition_list.Separator   = ows & "|" & ows;
            rule_equals.Add(style.HasFlag(EbnfStyle.DoubleColonEquals) ? "::=" : "=", ":=");
            syntax_rule.Add(meta_identifier, ows, rule_equals, ows, definition_list);
            if (style.HasFlag(EbnfStyle.SemicolonTerminator))
            {
                syntax_rule.Add(ows, ";");                 // iso rules are terminated by a semicolon
            }
            var syntax_rules = +syntax_rule;

            syntax_rules.Separator = style.HasFlag(EbnfStyle.SemicolonTerminator) ? ows : rws;

            Inner = ows & syntax_rules & ows;

            AttachEvents();
        }
Ejemplo n.º 33
0
 public static double ParseFloat(string input)
 {
     return(NumberParser.ParseFloat(input));
 }
Ejemplo n.º 34
0
 public override decimal parseValue(JsonReader xmlReader)
 {
     return(NumberParser.ParseDecimal(xmlReader.ReadAsString()));
 }
Ejemplo n.º 35
0
        public void Parse_ReturnsNumberAsString()
        {
            var numberParser = new NumberParser();

            Assert.AreEqual("10", numberParser.Parse(10));
        }
Ejemplo n.º 36
0
 private void TestInteger(string input, int expected, NumberParser parser)
 {
     int actual = parser.ParseInteger(input);
     Assert.AreEqual(actual, expected);
 }
Ejemplo n.º 37
0
        /// <summary>
        /// Read a rotation from the XML stream.
        /// </summary>
        /// <param name="xmlReader"></param>
        /// <returns></returns>
        private Quaternion readRotation(XmlReader xmlReader)
        {
            Quaternion rotation = new Quaternion();

            xmlReader.Read();
            String[] rots = xmlReader.Value.Split(SEPS);
            //Euler angles
            if (rots.Length == 3)
            {
                rotation.setEuler(NumberParser.ParseFloat(rots[0]) * DEG_TO_RAD, NumberParser.ParseFloat(rots[1]) * DEG_TO_RAD, NumberParser.ParseFloat(rots[2]) * DEG_TO_RAD);
            }
            else
            {
                Log.Default.sendMessage("Error loading rotation does not contain 3 numbers value: {0}.", LogLevel.Warning, "ShapeLoading", xmlReader.Value);
                rotation = Quaternion.Identity;
            }
            return(rotation);
        }
Ejemplo n.º 38
0
 private void TestShort(string input, short expected, NumberParser parser)
 {
     short actual = parser.ParseShort(input);
     Assert.AreEqual(actual, expected);
 }
Ejemplo n.º 39
0
        /// <summary>
        /// Read Text Message from memory
        /// </summary>
        /// <param name="Memory">"ME" for GM862 storage, "SM" for SIM storage</param>
        /// <param name="Location">Location number</param>
        /// <param name="Message">Message</param>
        /// <returns>True when message is read succesfully</returns>
        public bool ReadTextMessage(String Memory, int Location, out TextMessage Message)
        {
            // Check if Text Messaging was initialized correctly
            if (!_textmessage_initialized)
            {
                throw new GM862Exception(GM862Exception.WRONGARGUMENT);
            }

            // Check Memory, must be "ME" or "SM"
            if (Memory.ToUpper() == "ME")
            {
                Memory = "\"ME\"";
            }
            if (Memory.ToUpper() == "SM")
            {
                Memory = "\"SM\"";
            }

            // String used to store response body when executing functions
            string responseBody;

            // Select memory location
            if (_device.ExecuteCommand("AT+CPMS=" + Memory, out responseBody, 10000) != AT_Interface.ResponseCodes.OK)
            {
                // Error
                Message = null;
                return(false);
            }

            // Read Message from Location
            if (_device.ExecuteCommand("AT+CMGR=" + Location.ToString(), out responseBody, 10000) != AT_Interface.ResponseCodes.OK)
            {
                // Error
                Message = null;
                return(false);
            }

            // Check response
            if ((responseBody.IndexOf("\r\n+CMGR: ") != 0) | (responseBody.LastIndexOf("\r\n") < 2))
            {
                throw new GM862Exception(GM862Exception.BAD_RESPONSEBODY);
            }

            // Variables used to read message text
            int messageStart = 0;

            // Variables used to decode message header
            System.Collections.ArrayList header = new System.Collections.ArrayList();
            String headerPart  = "";
            bool   withinQuote = false;
            bool   ignoreRest  = false;
            bool   exitLoop    = false;

            // Try reading header parts
            foreach (char c in responseBody.Substring(9))
            {
                exitLoop = false;
                switch (c)
                {
                case '"':
                    if (withinQuote)
                    {
                        withinQuote = false; ignoreRest = true; break;
                    }
                    if (!withinQuote)
                    {
                        headerPart = ""; withinQuote = true; break;
                    }
                    break;

                case ',':
                    if (!withinQuote)
                    {
                        ignoreRest = false; header.Add(headerPart); headerPart = ""; break;
                    }
                    break;

                case '\r':
                    header.Add(headerPart); headerPart = "";
                    exitLoop = true;
                    break;

                default:
                    if (!ignoreRest)
                    {
                        headerPart += c;
                    }
                    break;
                }
                if (exitLoop)
                {
                    break;
                }
            }

            // Header should now contain:
            // [0] Status
            // [1] Originator
            // [2]
            // [3] Arrival Time
            // [Length-1] Data length

            // Exit on wrong header
            if (header.Count < 7)
            {
                Message = null;
                return(false);
            }

            // Get Message Start
            messageStart = responseBody.IndexOf("\r\n", 9) + 2;

            // Build new TextMessage
            Message = new TextMessage(
                Memory,
                Location,
                (String)header[0],
                (String)header[1],
                (String)header[3],
                responseBody.Substring(messageStart, NumberParser.StringToInt((String)header[header.Count - 1]))
                );

            // Return succes
            return(true);
        }
Ejemplo n.º 40
0
 private void TestDouble(string input, double expected, NumberParser parser)
 {
     double actual = parser.ParseDouble(input);
     Assert.AreEqual(actual, expected, delta);
 }
Ejemplo n.º 41
0
        /// <summary>
        /// List all text messages from a memory location
        /// </summary>
        /// <param name="Memory">Memory location to read from</param>
        /// <param name="Group">Group of messages to read</param>
        /// <param name="Messages">Array of read messages</param>
        /// <returns>Number of read messages</returns>
        public int ListTextMessages(String Memory, ListGroups Group, out TextMessage[] Messages)
        {
            // Check if Text Messaging was initialized correctly
            if (!_textmessage_initialized)
            {
                throw new GM862Exception(GM862Exception.WRONGARGUMENT);
            }

            // Check Memory, must be "ME" or "SM"
            if (Memory.ToUpper() == "ME")
            {
                Memory = "\"ME\"";
            }
            if (Memory.ToUpper() == "SM")
            {
                Memory = "\"SM\"";
            }

            // String used to store response body when executing functions
            string responseBody;

            // Get group as string
            string groupString;

            // Get group as string
            switch (Group)
            {
            case ListGroups.ALL:
                groupString = "ALL";
                break;

            case ListGroups.REC_READ:
                groupString = "REC READ";
                break;

            case ListGroups.REC_UNREAD:
                groupString = "REC UNREAD";
                break;

            case ListGroups.STO_SEND:
                groupString = "STO SEND";
                break;

            case ListGroups.STO_UNSEND:
                groupString = "STO UNSEND";
                break;

            default:
                groupString = "ALL";
                break;
            }

            // ArrayList to store read messages
            System.Collections.ArrayList readMessages = new System.Collections.ArrayList();

            // Select memory location
            if (_device.ExecuteCommand("AT+CPMS=" + Memory, out responseBody, 10000) != AT_Interface.ResponseCodes.OK)
            {
                // Error
                Messages = null;
                return(0);
            }

            // Read Message from Location
            if (_device.ExecuteCommand("AT+CMGL=\"" + groupString + "\"", out responseBody, 10000) != AT_Interface.ResponseCodes.OK)
            {
                // Error
                Messages = null;
                return(0);
            }

            // Variables used to read message text
            int messageStart = 0;

            // Variables used to decode message header
            System.Collections.ArrayList header = new System.Collections.ArrayList();
            String headerPart  = "";
            bool   withinQuote = false;
            bool   ignoreRest  = false;
            bool   exitLoop    = false;

            // Keep reading while we have valid listing entries
            while (responseBody.IndexOf("\r\n+CMGL: ") == 0)
            {
                // Start of clean
                header.Clear();
                headerPart  = "";
                withinQuote = false;
                ignoreRest  = false;

                // Try reading header parts
                foreach (char c in responseBody.Substring(9))
                {
                    exitLoop = false;
                    switch (c)
                    {
                    case '"':
                        if (withinQuote)
                        {
                            withinQuote = false; ignoreRest = true; break;
                        }
                        if (!withinQuote)
                        {
                            headerPart = ""; withinQuote = true;  break;
                        }
                        break;

                    case ',':
                        if (!withinQuote)
                        {
                            ignoreRest = false; header.Add(headerPart); headerPart = ""; break;
                        }
                        break;

                    case '\r':
                        header.Add(headerPart); headerPart = "";
                        exitLoop = true;
                        break;

                    default:
                        if (!ignoreRest)
                        {
                            headerPart += c;
                        }
                        break;
                    }
                    if (exitLoop)
                    {
                        break;
                    }
                }

                // Header should now contain:
                // [0] Index
                // [1] Status
                // [2] Originator
                // [3] Arrival Time
                // [4]
                // [5] Originator Type
                // [6] Data length

                // Exit on wrong header
                if (header.Count < 7)
                {
                    break;
                }

                // Get Message Start
                messageStart = responseBody.IndexOf("\r\n", 9) + 2;

                // Build new TextMessage
                TextMessage newMessage = new TextMessage(
                    Memory,
                    NumberParser.StringToInt((String)header[0]),
                    (String)header[1],
                    (String)header[2],
                    (String)header[3],
                    responseBody.Substring(messageStart, NumberParser.StringToInt((String)header[6]))
                    );

                // And add it to the array
                readMessages.Add(newMessage);

                // Ok, Next Message
                responseBody = responseBody.Substring(messageStart + NumberParser.StringToInt((String)header[6]));
            }



            // Return read messages
            Messages = (TextMessage[])readMessages.ToArray(typeof(TextMessage));
            return(Messages.Length);
        }
Ejemplo n.º 42
0
        /// <summary>
        /// Determines if value can be parsed to the underlying type.
        /// </summary>
        /// <param name="value"></param>
        /// <returns>True if the String can be parsed correctly.</returns>
        public override bool canParseString(string value)
        {
            ushort test;

            return(NumberParser.TryParse(value, out test));
        }
 private List<int> ConvertToNumbers(IEnumerable<string> tokens)
 {
     NumberParser parser = new NumberParser();
     return parser.Parse(tokens);
 }