char.IsDigit(char)

Here are the examples of the csharp api char.IsDigit(char) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1092 Examples 7

19 Source : StringHelper.cs
with MIT License
from 0x1000000

public static string DeSnake(string input)
        {
            if (string.IsNullOrEmpty(input))
            {
                return input;
            }

            char[]? result = null;
            int nextResultIndex = 0;

            bool afterSymbol = true;

            for (int i = 0; i < input.Length; i++)
            {
                var ch = input[i];

                if (!char.IsLetterOrDigit(ch))
                {
                    afterSymbol = true;
                    EnsureResult(i);
                }
                else
                {
                    if (afterSymbol && char.IsLower(ch))
                    {
                        OutResult(i, char.ToUpper(ch), true);
                    }
                    else
                    {
                        OutResult(i, ch, false);
                    }
                    afterSymbol = false;
                }

                if (result == null)
                {
                    nextResultIndex = i;
                }
            }

            return result == null ? input : new string(result, 0, nextResultIndex);

            void EnsureResult(int index)
            {
                if (result == null)
                {
                    result = new char[input.Length + 1];
                    input.CopyTo(0, result, 0, input.Length);
                    nextResultIndex = index;
                }
            }

            void OutResult(int index, char ch, bool changed)
            {
                var isFirstDigit = nextResultIndex == 0 && char.IsDigit(ch);
                if (result == null)
                {
                    if (!changed && !isFirstDigit)
                    {
                        return;
                    }

                    EnsureResult(index);
                }

                if (isFirstDigit)
                {
                    result![nextResultIndex++] = 'D';
                }

                result![nextResultIndex++] = ch;
            }
        }

19 Source : MethodJitter.cs
with MIT License
from 0xd4d

static string MakeClrmdTypeName(string name) {
			if (name.Length > 0 && char.IsDigit(name[name.Length - 1])) {
				int index = name.LastIndexOf('`');
				if (index >= 0)
					return name.Substring(0, index);
			}
			return name;
		}

19 Source : JSONParser.cs
with MIT License
from 5minlab

static object ParseAnonymousValue(string json) {
            if (json.Length == 0)
                return null;
            if (json[0] == '{' && json[json.Length - 1] == '}') {
                List<string> elems = Split(json);
                if (elems.Count % 2 != 0)
                    return null;
                var dict = new Dictionary<string, object>(elems.Count / 2);
                for (int i = 0; i < elems.Count; i += 2)
                    dict.Add(elems[i].Substring(1, elems[i].Length - 2), ParseAnonymousValue(elems[i + 1]));
                return dict;
            }
            if (json[0] == '[' && json[json.Length - 1] == ']') {
                List<string> items = Split(json);
                var finalList = new List<object>(items.Count);
                for (int i = 0; i < items.Count; i++)
                    finalList.Add(ParseAnonymousValue(items[i]));
                return finalList;
            }
            if (json[0] == '\"' && json[json.Length - 1] == '\"') {
                string str = json.Substring(1, json.Length - 2);
                return str.Replace("\\", string.Empty);
            }
            if (char.IsDigit(json[0]) || json[0] == '-') {
                if (json.Contains(".")) {
                    double result;
                    double.TryParse(json, out result);
                    return result;
                } else {
                    int result;
                    int.TryParse(json, out result);
                    return result;
                }
            }
            if (json == "true")
                return true;
            if (json == "false")
                return false;
            // handles json == "null" as well as invalid JSON
            return null;
        }

19 Source : Repository.cs
with Apache License 2.0
from AantCoder

public static bool CheckIsBanIP(string IP)
        {
            if ((DateTime.UtcNow - BlockipUpdate).TotalSeconds > 30)
            {
                var fileName = Loger.PathLog + "blockip.txt";

                BlockipUpdate = DateTime.UtcNow;
                if (!File.Exists(fileName)) Blockip = new HashSet<string>();
                else
                    try
                    {
                        var listBlock = File.ReadAllLines(fileName, Encoding.UTF8);
                        if (listBlock.Any(b => b.Contains("/")))
                        {
                            listBlock = listBlock
                                .SelectMany(b =>
                                {
                                    var bb = b.Trim();
                                    var comment = "";
                                    var ic = bb.IndexOf(" ");
                                    if (ic > 0)
                                    {
                                        comment = bb.Substring(ic);
                                        bb = bb.Substring(0, ic);
                                    }
                                    if (bb.Any(c => !char.IsDigit(c) && c != '.' && c != '/')) return new List<string>();
                                    var ls = bb.LastIndexOf("/");
                                    if (ls < 0) return new List<string>() { bb + comment };
                                    var lp = bb.LastIndexOf(".");
                                    if (lp <= 0) return new List<string>();
                                    var ib = int.Parse(bb.Substring(lp + 1, ls - (lp + 1)));
                                    var ie = int.Parse(bb.Substring(ls + 1));
                                    var res = new List<string>();
                                    var s = bb.Substring(0, lp + 1);
                                    for (int i = ib; i <= ie; i++)
                                        res.Add(s + i.ToString() + comment);
                                    return res;
                                })
                                .ToArray();
                            File.WriteAllLines(fileName, listBlock, Encoding.Default);
                        }
                        Blockip = new HashSet<string>(listBlock
                            .Select(b => b.Contains(" ") ? b.Substring(0, b.IndexOf(" ")) : b));
                    }
                    catch (Exception exp)
                    {
                        Loger.Log("CheckIsBanIP error " + exp.Message);
                        Blockip = new HashSet<string>();
                        return false;
                    }

            }

            return Blockip.Contains(IP.Trim());
        }

19 Source : PhoneGenerator.cs
with MIT License
from abock

static char Translate(char c)
        {
            c = char.ToLowerInvariant(c);
            switch (c)
            {
                case 'a':
                case 'b':
                case 'c':
                    return '2';
                case 'd':
                case 'e':
                case 'f':
                    return '3';
                case 'g':
                case 'h':
                case 'i':
                    return '4';
                case 'j':
                case 'k':
                case 'l':
                    return '5';
                case 'm':
                case 'n':
                case 'o':
                    return '6';
                case 'p':
                case 'q':
                case 'r':
                case 's':
                    return '7';
                case 't':
                case 'u':
                case 'v':
                    return '8';
                case 'w':
                case 'x':
                case 'y':
                case 'z':
                    return '9';
                default:
                    return char.IsDigit(c) ? c : '*';
            }
        }

19 Source : Format.cs
with MIT License
from actions

private Boolean ReadArgIndex(
            String str,
            Int32 startIndex,
            out Byte result,
            out Int32 endIndex)
        {
            // Count the number of digits
            var length = 0;
            while (Char.IsDigit(SafeCharAt(str, startIndex + length)))
            {
                length++;
            }

            // Validate at least one digit
            if (length < 1)
            {
                result = default;
                endIndex = default;
                return false;
            }

            // Parse the number
            endIndex = startIndex + length - 1;
            return Byte.TryParse(str.Substring(startIndex, length), NumberStyles.None, CultureInfo.InvariantCulture, out result);
        }

19 Source : GenerateSourceOnlyPackageNuspecsTask.cs
with MIT License
from adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            if (PartNuspecFiles == null)
            {
                Log.LogMessage("No source-only packages found");
                return true; //nothing to process
            }

            //process the source files
            foreach (var sourceFile in PartNuspecFiles)
            {
                var partNuspecFileNameFull = sourceFile.GetMetadata("FullPath");

                //Get the partial (partnuspec) file
                var ns = XNamespace.Get("http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd");
                var outFile = partNuspecFileNameFull + ".tmp.nuspec";
                Log.LogMessage($"Loading {partNuspecFileNameFull}");
                var partNuspecFileContent = File.ReadAllText(partNuspecFileNameFull);
                partNuspecFileContent = partNuspecFileContent.Replace("%%CURRENT_VERSION%%", PackageVersionFull);
                var outXDoc = XDoreplacedent.Parse(partNuspecFileContent);
                var packageXElement = GetOrCreateElement(outXDoc, "package", ns);
                var metadataXElement = GetOrCreateElement(packageXElement, "metadata", ns);

                //Check package ID
                var packageId = metadataXElement.Element(ns + "id")?.Value;
                if (packageId == null) throw new Exception($"Can't find the package ID for {partNuspecFileNameFull}");

                //Process version - global version from solution of base version from partial file
                var versionOriginal = GetOrCreateElement(metadataXElement, "version", ns)?.Value;
                var version = PackageVersionFull;
                if (!string.IsNullOrEmpty(versionOriginal))
                {
                    //base version set in NuProp
                    //get ext version from PackageVersionFull
                    //0.1.0-dev.441.181206212308+53.master.37f08fc-dirty
                    //0.1.0+442.181206212418.master.37f08fc-dirty
                    var idx = 0;
                    while (char.IsDigit(PackageVersionFull[idx]) || PackageVersionFull[idx] == '.')
                    {
                        idx++;
                    }

                    version = versionOriginal + PackageVersionFull.Substring(idx);
                }

                //Enrich the NuSpec
                SetOrCreateElement(metadataXElement, "version", ns, version);
                SetOrCreateElement(metadataXElement, "authors", ns, Authors);
                SetOrCreateElement(metadataXElement, "replacedle", ns, packageId);
                SetOrCreateElement(metadataXElement, "owners", ns, Authors);
                SetOrCreateElement(metadataXElement, "description", ns, $"Source only package {packageId}", false); //don't override if exists
                SetOrCreateElement(metadataXElement, "requireLicenseAcceptance", ns, PackageRequireLicenseAcceptance);
                if (!string.IsNullOrEmpty(PackageLicense))
                {
                    SetOrCreateElement(metadataXElement, "license", ns, PackageLicense).
                        Add(new XAttribute("type","expression"));
                }
                else
                {
                    SetOrCreateElement(metadataXElement, "licenseUrl", ns, PackageLicenseUrl);
                }
                SetOrCreateElement(metadataXElement, "projectUrl", ns, PackageProjectUrl);
                SetOrCreateElement(metadataXElement, "iconUrl", ns, PackageIconUrl);
                SetOrCreateElement(metadataXElement, "copyright", ns, Copyright);
                SetOrCreateElement(metadataXElement, "developmentDependency", ns, "true");
                GetEmptyOrCreateElement(metadataXElement, "repository", ns).
                                    Add(new XAttribute("url", RepositoryUrl),
                                        new XAttribute("type", "git"),
                                        new XAttribute("branch", GitBranch),
                                        new XAttribute("commit", GitCommit));

                //Save the temporary NuSpec file
                var outXDocStr = outXDoc.ToString();
                File.WriteAllText(outFile, outXDocStr);
                Log.LogMessage($"Generated source only nuspec file {outFile}");
            }

            return true;
        }

19 Source : StringFunctions.cs
with MIT License
from adamped

public static bool IsXDigit(char character)
	{
		if (char.IsDigit(character))
			return true;
		else if ("ABCDEFabcdef".IndexOf(character) > -1)
			return true;
		else
			return false;
	}

19 Source : POParser.cs
with MIT License
from adams85

private bool TryReadPluralIndex(out int? result)
        {
            var lineLength = _line.Length;

            if (_columnIndex >= lineLength || _line[_columnIndex] != '[')
            {
                result = null;
                return true;
            }

            var startIndex = ++_columnIndex;
            char c;
            for (; _columnIndex < lineLength; _columnIndex++)
                if ((c = _line[_columnIndex]) == ']')
                {
                    var endIndex = _columnIndex++;
                    if (!int.TryParse(_line.Substring(startIndex, endIndex - startIndex), NumberStyles.Integer, CultureInfo.InvariantCulture, out int indexValue))
                    {
                        AddError(DiagnosticCodes.InvalidPluralIndex, new TextLocation(_lineIndex, startIndex - 1));
                        result = null;
                        return false;
                    }
                    result = indexValue;
                    return true;
                }
                else if (!char.IsDigit(c))
                {
                    var diagnosticCode = GetUnexpectedCharDiagnosticCode(DiagnosticCodes.InvalidPluralIndex);
                    AddError(diagnosticCode, new TextLocation(_lineIndex, diagnosticCode == DiagnosticCodes.InvalidPluralIndex ? startIndex - 1 : _columnIndex));
                    result = null;
                    return false;
                }

            AddError(DiagnosticCodes.ExpectedToken, new TextLocation(_lineIndex, lineLength), ']');
            result = null;
            return false;
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void applyupdate()
        {
            statuslabel.Content = "Merging NCA's...";

            string curdir = AppDomain.CurrentDomain.BaseDirectory;
            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";
            string upddir = AppDomain.CurrentDomain.BaseDirectory + "\\upd";
            string nspudir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string basenca = tmpdir + "\\NCAID_PLAIN.nca";

            var di = new DirectoryInfo(upddir);
            var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
            var larupdnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();

            string updnca = String.Join(" ", larupdnca);

            string replacedlkeyp = updreplacedlkyinput.Text;
            string upgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());

            string arg1 = @"-k keys.txt " + "--replacedlekey=" + upgtk + " --basenca=" + basenca + " --section1=" + curdir + "\\romfs.bin" + " --exefsdir=";
            string arg2 = tmpdir + "\\exefs " + updnca;
            string arg = arg1 + arg2; 

            Process aplupd = new Process();
            aplupd.StartInfo.FileName = nspudir;
            aplupd.StartInfo.Arguments = arg;
            aplupd.StartInfo.CreateNoWindow = true;
            aplupd.StartInfo.UseShellExecute = false;
            aplupd.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            aplupd.EnableRaisingEvents = true;

            aplupd.Start();

            await Task.Run(() => aplupd.WaitForExit());

            aplupd.Close();

            stopbar();

            statuslabel.Content = "";

            Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\tmp", true);
            Directory.Delete(AppDomain.CurrentDomain.BaseDirectory + @"\\upd", true);

            onbtn();

            System.Windows.MessageBox.Show("Update applyment finished.\nYou can now use your updated romFS via fs-mitm.");
        }

19 Source : MainWindow.xaml.cs
with GNU General Public License v2.0
from adrifcastr

public async void decryptbsgnca()
        {
            offbtn();

            startbar();

            statuslabel.Content = "Decrypting Base Game NCA...";

            string tmpdir = AppDomain.CurrentDomain.BaseDirectory + "\\tmp";

            var di = new DirectoryInfo(tmpdir);
            var result = di.GetFiles().OrderByDescending(x => x.Length).Take(1).ToList();
            var larbnca = di.GetFiles().OrderByDescending(x => x.Length).Take(1).Select(x => x.FullName).ToList();

            string basenca = String.Join(" ", larbnca);

            string nspddir = AppDomain.CurrentDomain.BaseDirectory + "\\hactool.exe";
            string replacedlkeyp = bsgreplacedlkyinput.Text;
            string bsgtk = new string(replacedlkeyp.Where(c => char.IsLetter(c) || char.IsDigit(c)).ToArray());
            string arg1 = @"-k keys.txt " + "--replacedlekey=" + bsgtk + " " + basenca;
            string arg2 = " --plaintext=" + tmpdir + "\\NCAID_PLAIN.nca";
            string arg = arg1 + arg2;
          
            Process decrnca = new Process();
            decrnca.StartInfo.FileName = nspddir;
            decrnca.StartInfo.Arguments = arg;
            decrnca.StartInfo.CreateNoWindow = true;
            decrnca.StartInfo.UseShellExecute = false;
            decrnca.StartInfo.WorkingDirectory = Directory.GetCurrentDirectory();
            decrnca.EnableRaisingEvents = true;

            decrnca.Start();

            await Task.Run(() => decrnca.WaitForExit());

            decrnca.Close();

            extractncau();
        }

19 Source : utils.cs
with GNU General Public License v3.0
from Aeroblast

public static UInt64 DecodeBase32(string s)
        {
            UInt64 r = 0;
            foreach (char c in s)
            {
                uint v;
                if (char.IsDigit(c))
                {
                    v = (uint)c - (uint)'0';
                }
                else
                {
                    v = (uint)c - (uint)'A' + 10;
                }
                r = (r * 32) + v;

            }
            return r;
        }

19 Source : LanguageModule.cs
with MIT License
from AgathokakologicalBit

static string GetLeadingInt(string input)
            => new string(input.Trim().TakeWhile((c) => Char.IsDigit(c)).ToArray());

19 Source : JPath.cs
with MIT License
from akaskela

private PathFilter ParseArrayIndexer(char indexerCloseChar)
        {
            int start = _currentIndex;
            int? end = null;
            List<int> indexes = null;
            int colonCount = 0;
            int? startIndex = null;
            int? endIndex = null;
            int? step = null;

            while (_currentIndex < _expression.Length)
            {
                char currentCharacter = _expression[_currentIndex];

                if (currentCharacter == ' ')
                {
                    end = _currentIndex;
                    EatWhitespace();
                    continue;
                }

                if (currentCharacter == indexerCloseChar)
                {
                    int length = (end ?? _currentIndex) - start;

                    if (indexes != null)
                    {
                        if (length == 0)
                        {
                            throw new JsonException("Array index expected.");
                        }

                        string indexer = _expression.Substring(start, length);
                        int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture);

                        indexes.Add(index);
                        return new ArrayMultipleIndexFilter { Indexes = indexes };
                    }
                    else if (colonCount > 0)
                    {
                        if (length > 0)
                        {
                            string indexer = _expression.Substring(start, length);
                            int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture);

                            if (colonCount == 1)
                            {
                                endIndex = index;
                            }
                            else
                            {
                                step = index;
                            }
                        }

                        return new ArraySliceFilter { Start = startIndex, End = endIndex, Step = step };
                    }
                    else
                    {
                        if (length == 0)
                        {
                            throw new JsonException("Array index expected.");
                        }

                        string indexer = _expression.Substring(start, length);
                        int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture);

                        return new ArrayIndexFilter { Index = index };
                    }
                }
                else if (currentCharacter == ',')
                {
                    int length = (end ?? _currentIndex) - start;

                    if (length == 0)
                    {
                        throw new JsonException("Array index expected.");
                    }

                    if (indexes == null)
                    {
                        indexes = new List<int>();
                    }

                    string indexer = _expression.Substring(start, length);
                    indexes.Add(Convert.ToInt32(indexer, CultureInfo.InvariantCulture));

                    _currentIndex++;

                    EatWhitespace();

                    start = _currentIndex;
                    end = null;
                }
                else if (currentCharacter == '*')
                {
                    _currentIndex++;
                    EnsureLength("Path ended with open indexer.");
                    EatWhitespace();

                    if (_expression[_currentIndex] != indexerCloseChar)
                    {
                        throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter);
                    }

                    return new ArrayIndexFilter();
                }
                else if (currentCharacter == ':')
                {
                    int length = (end ?? _currentIndex) - start;

                    if (length > 0)
                    {
                        string indexer = _expression.Substring(start, length);
                        int index = Convert.ToInt32(indexer, CultureInfo.InvariantCulture);

                        if (colonCount == 0)
                        {
                            startIndex = index;
                        }
                        else if (colonCount == 1)
                        {
                            endIndex = index;
                        }
                        else
                        {
                            step = index;
                        }
                    }

                    colonCount++;

                    _currentIndex++;

                    EatWhitespace();

                    start = _currentIndex;
                    end = null;
                }
                else if (!char.IsDigit(currentCharacter) && currentCharacter != '-')
                {
                    throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter);
                }
                else
                {
                    if (end != null)
                    {
                        throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter);
                    }

                    _currentIndex++;
                }
            }

            throw new JsonException("Path ended with open indexer.");
        }

19 Source : DateTimeUtils.cs
with MIT License
from akaskela

internal static bool TryParseDateTimeOffset(string s, string dateFormatString, CultureInfo culture, out DateTimeOffset dt)
        {
            if (s.Length > 0)
            {
                if (s[0] == '/')
                {
                    if (s.Length >= 9 && s.StartsWith("/Date(", StringComparison.Ordinal) && s.EndsWith(")/", StringComparison.Ordinal))
                    {
                        if (TryParseDateTimeOffsetMicrosoft(new StringReference(s.ToCharArray(), 0, s.Length), out dt))
                        {
                            return true;
                        }
                    }
                }
                else if (s.Length >= 19 && s.Length <= 40 && char.IsDigit(s[0]) && s[10] == 'T')
                {
                    if (DateTimeOffset.TryParseExact(s, IsoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dt))
                    {
                        if (TryParseDateTimeOffsetIso(new StringReference(s.ToCharArray(), 0, s.Length), out dt))
                        {
                            return true;
                        }
                    }
                }

                if (!string.IsNullOrEmpty(dateFormatString))
                {
                    if (TryParseDateTimeOffsetExact(s, dateFormatString, culture, out dt))
                    {
                        return true;
                    }
                }
            }

            dt = default(DateTimeOffset);
            return false;
        }

19 Source : JsonTextReader.cs
with MIT License
from akaskela

private void ParseNumber(ReadType readType)
        {
            ShiftBufferIfNeeded();

            char firstChar = _chars[_charPos];
            int initialPosition = _charPos;

            ReadNumberIntoBuffer();

            // set state to PostValue now so that if there is an error parsing the number then the reader can continue
            SetPostValueState(true);

            _stringReference = new StringReference(_chars, initialPosition, _charPos - initialPosition);

            object numberValue;
            JsonToken numberType;

            bool singleDigit = (char.IsDigit(firstChar) && _stringReference.Length == 1);
            bool nonBase10 = (firstChar == '0' && _stringReference.Length > 1 && _stringReference.Chars[_stringReference.StartIndex + 1] != '.' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'e' && _stringReference.Chars[_stringReference.StartIndex + 1] != 'E');

            if (readType == ReadType.Readreplacedtring)
            {
                string number = _stringReference.ToString();

                // validate that the string is a valid number
                if (nonBase10)
                {
                    try
                    {
                        if (number.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
                        {
                            Convert.ToInt64(number, 16);
                        }
                        else
                        {
                            Convert.ToInt64(number, 8);
                        }
                    }
                    catch (Exception ex)
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number), ex);
                    }
                }
                else
                {
                    double value;
                    if (!double.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
                    }
                }

                numberType = JsonToken.String;
                numberValue = number;
            }
            else if (readType == ReadType.ReadAsInt32)
            {
                if (singleDigit)
                {
                    // digit char values start at 48
                    numberValue = firstChar - 48;
                }
                else if (nonBase10)
                {
                    string number = _stringReference.ToString();

                    try
                    {
                        int integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt32(number, 16) : Convert.ToInt32(number, 8);

                        numberValue = integer;
                    }
                    catch (Exception ex)
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, number), ex);
                    }
                }
                else
                {
                    int value;
                    ParseResult parseResult = ConvertUtils.Int32TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
                    if (parseResult == ParseResult.Success)
                    {
                        numberValue = value;
                    }
                    else if (parseResult == ParseResult.Overflow)
                    {
                        throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int32.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
                    }
                    else
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid integer.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
                    }
                }

                numberType = JsonToken.Integer;
            }
            else if (readType == ReadType.ReadAsDecimal)
            {
                if (singleDigit)
                {
                    // digit char values start at 48
                    numberValue = (decimal)firstChar - 48;
                }
                else if (nonBase10)
                {
                    string number = _stringReference.ToString();

                    try
                    {
                        // decimal.Parse doesn't support parsing hexadecimal values
                        long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8);

                        numberValue = Convert.ToDecimal(integer);
                    }
                    catch (Exception ex)
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number), ex);
                    }
                }
                else
                {
                    string number = _stringReference.ToString();

                    decimal value;
                    if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out value))
                    {
                        numberValue = value;
                    }
                    else
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
                    }
                }

                numberType = JsonToken.Float;
            }
            else if (readType == ReadType.ReadAsDouble)
            {
                if (singleDigit)
                {
                    // digit char values start at 48
                    numberValue = (double)firstChar - 48;
                }
                else if (nonBase10)
                {
                    string number = _stringReference.ToString();

                    try
                    {
                        // double.Parse doesn't support parsing hexadecimal values
                        long integer = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8);

                        numberValue = Convert.ToDouble(integer);
                    }
                    catch (Exception ex)
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid double.".FormatWith(CultureInfo.InvariantCulture, number), ex);
                    }
                }
                else
                {
                    string number = _stringReference.ToString();

                    double value;
                    if (double.TryParse(number, NumberStyles.Float, CultureInfo.InvariantCulture, out value))
                    {
                        numberValue = value;
                    }
                    else
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid double.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
                    }
                }

                numberType = JsonToken.Float;
            }
            else
            {
                if (singleDigit)
                {
                    // digit char values start at 48
                    numberValue = (long)firstChar - 48;
                    numberType = JsonToken.Integer;
                }
                else if (nonBase10)
                {
                    string number = _stringReference.ToString();

                    try
                    {
                        numberValue = number.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? Convert.ToInt64(number, 16) : Convert.ToInt64(number, 8);
                    }
                    catch (Exception ex)
                    {
                        throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number), ex);
                    }

                    numberType = JsonToken.Integer;
                }
                else
                {
                    long value;
                    ParseResult parseResult = ConvertUtils.Int64TryParse(_stringReference.Chars, _stringReference.StartIndex, _stringReference.Length, out value);
                    if (parseResult == ParseResult.Success)
                    {
                        numberValue = value;
                        numberType = JsonToken.Integer;
                    }
                    else if (parseResult == ParseResult.Overflow)
                    {
#if !(NET20 || NET35 || PORTABLE40 || PORTABLE)
                        string number = _stringReference.ToString();

                        if (number.Length > MaximumJavascriptIntegerCharacterLength)
                        {
                            throw JsonReaderException.Create(this, "JSON integer {0} is too large to parse.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
                        }

                        numberValue = BigIntegerParse(number, CultureInfo.InvariantCulture);
                        numberType = JsonToken.Integer;
#else
                        throw JsonReaderException.Create(this, "JSON integer {0} is too large or small for an Int64.".FormatWith(CultureInfo.InvariantCulture, _stringReference.ToString()));
#endif
                    }
                    else
                    {
                        string number = _stringReference.ToString();

                        if (_floatParseHandling == FloatParseHandling.Decimal)
                        {
                            decimal d;
                            if (decimal.TryParse(number, NumberStyles.Number | NumberStyles.AllowExponent, CultureInfo.InvariantCulture, out d))
                            {
                                numberValue = d;
                            }
                            else
                            {
                                throw JsonReaderException.Create(this, "Input string '{0}' is not a valid decimal.".FormatWith(CultureInfo.InvariantCulture, number));
                            }
                        }
                        else
                        {
                            double d;
                            if (double.TryParse(number, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
                            {
                                numberValue = d;
                            }
                            else
                            {
                                throw JsonReaderException.Create(this, "Input string '{0}' is not a valid number.".FormatWith(CultureInfo.InvariantCulture, number));
                            }
                        }

                        numberType = JsonToken.Float;
                    }
                }
            }

            ClearRecentString();

            // index has already been updated
            SetToken(numberType, numberValue, false);
        }

19 Source : JPath.cs
with MIT License
from akaskela

private object ParseValue()
        {
            char currentChar = _expression[_currentIndex];
            if (currentChar == '\'')
            {
                return ReadQuotedString();
            }
            else if (char.IsDigit(currentChar) || currentChar == '-')
            {
                StringBuilder sb = new StringBuilder();
                sb.Append(currentChar);

                _currentIndex++;
                while (_currentIndex < _expression.Length)
                {
                    currentChar = _expression[_currentIndex];
                    if (currentChar == ' ' || currentChar == ')')
                    {
                        string numberText = sb.ToString();

                        if (numberText.IndexOfAny(new char[] { '.', 'E', 'e' }) != -1)
                        {
                            double d;
                            if (double.TryParse(numberText, NumberStyles.Float | NumberStyles.AllowThousands, CultureInfo.InvariantCulture, out d))
                            {
                                return d;
                            }
                            else
                            {
                                throw new JsonException("Could not read query value.");
                            }
                        }
                        else
                        {
                            long l;
                            if (long.TryParse(numberText, NumberStyles.Integer, CultureInfo.InvariantCulture, out l))
                            {
                                return l;
                            }
                            else
                            {
                                throw new JsonException("Could not read query value.");
                            }
                        }
                    }
                    else
                    {
                        sb.Append(currentChar);
                        _currentIndex++;
                    }
                }
            }
            else if (currentChar == 't')
            {
                if (Match("true"))
                {
                    return true;
                }
            }
            else if (currentChar == 'f')
            {
                if (Match("false"))
                {
                    return false;
                }
            }
            else if (currentChar == 'n')
            {
                if (Match("null"))
                {
                    return null;
                }
            }

            throw new JsonException("Could not read query value.");
        }

19 Source : DateTimeUtils.cs
with MIT License
from akaskela

internal static bool TryParseDateTime(string s, DateTimeZoneHandling dateTimeZoneHandling, string dateFormatString, CultureInfo culture, out DateTime dt)
        {
            if (s.Length > 0)
            {
                if (s[0] == '/')
                {
                    if (s.Length >= 9 && s.StartsWith("/Date(", StringComparison.Ordinal) && s.EndsWith(")/", StringComparison.Ordinal))
                    {
                        if (TryParseDateTimeMicrosoft(new StringReference(s.ToCharArray(), 0, s.Length), dateTimeZoneHandling, out dt))
                        {
                            return true;
                        }
                    }
                }
                else if (s.Length >= 19 && s.Length <= 40 && char.IsDigit(s[0]) && s[10] == 'T')
                {
                    if (DateTime.TryParseExact(s, IsoDateFormat, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out dt))
                    {
                        dt = EnsureDateTime(dt, dateTimeZoneHandling);
                        return true;
                    }
                }

                if (!string.IsNullOrEmpty(dateFormatString))
                {
                    if (TryParseDateTimeExact(s, dateTimeZoneHandling, dateFormatString, culture, out dt))
                    {
                        return true;
                    }
                }
            }

            dt = default(DateTime);
            return false;
        }

19 Source : HtmlLexicalAnalyzer.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private void GetNextCharacter()
        {
            if (_nextCharacterCode == -1)
            {
                throw new InvalidOperationException("GetNextCharacter method called at the end of a stream");
            }

            _previousCharacter = _nextCharacter;

            _nextCharacter = _lookAheadCharacter;
            _nextCharacterCode = _lookAheadCharacterCode;
            // next character not an enreplacedy as of now
            _isNextCharacterEnreplacedy = false;

            this.ReadLookAheadCharacter();

            if (_nextCharacter == '&')
            {
                if (_lookAheadCharacter == '#')
                {
                    // numeric enreplacedy - parse digits - &#DDDDD;
                    int enreplacedyCode;
                    enreplacedyCode = 0;
                    this.ReadLookAheadCharacter();

                    // largest numeric enreplacedy is 7 characters
                    for (int i = 0; i < 7 && Char.IsDigit(_lookAheadCharacter); i++)
                    {
                        enreplacedyCode = 10 * enreplacedyCode + (_lookAheadCharacterCode - (int)'0');
                        this.ReadLookAheadCharacter();
                    }
                    if (_lookAheadCharacter == ';')
                    {
                        // correct format - advance
                        this.ReadLookAheadCharacter();
                        _nextCharacterCode = enreplacedyCode;

                        // if this is out of range it will set the character to '?'
                        _nextCharacter = (char)_nextCharacterCode;

                        // as far as we are concerned, this is an enreplacedy
                        _isNextCharacterEnreplacedy = true;
                    }
                    else
                    {
                        // not an enreplacedy, set next character to the current lookahread character
                        // we would have eaten up some digits
                        _nextCharacter = _lookAheadCharacter;
                        _nextCharacterCode = _lookAheadCharacterCode;
                        this.ReadLookAheadCharacter();
                        _isNextCharacterEnreplacedy = false;
                    }
                }
                else if (Char.IsLetter(_lookAheadCharacter))
                {
                    // enreplacedy is written as a string
                    string enreplacedy = "";

                    // maximum length of string enreplacedies is 10 characters
                    for (int i = 0; i < 10 && (Char.IsLetter(_lookAheadCharacter) || Char.IsDigit(_lookAheadCharacter)); i++)
                    {
                        enreplacedy += _lookAheadCharacter;
                        this.ReadLookAheadCharacter();
                    }
                    if (_lookAheadCharacter == ';')
                    {
                        // advance
                        this.ReadLookAheadCharacter();

                        if (HtmlSchema.IsEnreplacedy(enreplacedy))
                        {
                            _nextCharacter = HtmlSchema.EnreplacedyCharacterValue(enreplacedy);
                            _nextCharacterCode = (int)_nextCharacter;
                            _isNextCharacterEnreplacedy = true;
                        }
                        else
                        {
                            // just skip the whole thing - invalid enreplacedy
                            // move on to the next character
                            _nextCharacter = _lookAheadCharacter;
                            _nextCharacterCode = _lookAheadCharacterCode;
                            this.ReadLookAheadCharacter();

                            // not an enreplacedy
                            _isNextCharacterEnreplacedy = false;
                        }
                    }
                    else
                    {
                        // skip whatever we read after the ampersand
                        // set next character and move on
                        _nextCharacter = _lookAheadCharacter;
                        this.ReadLookAheadCharacter();
                        _isNextCharacterEnreplacedy = false;
                    }
                }
            }
        }

19 Source : HtmlLexicalAnalyzer.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private static bool IsGoodForName(char character)
        {
            // we are not concerned with escaped characters in names
            // we replacedume that character enreplacedies are allowed as part of a name
            return 
                HtmlLexicalreplacedyzer.IsGoodForNameStart(character) || 
                character == '.' || 
                character == '-' || 
                character == ':' ||
                Char.IsDigit(character) || 
                IsCombiningCharacter(character) || 
                IsExtender(character);
        }

19 Source : HtmlCssParser.cs
with GNU Affero General Public License v3.0
from akshinmustafayev

private static string ParseCssSize(string styleValue, ref int nextIndex, bool mustBeNonNegative)
        {
            ParseWhiteSpace(styleValue, ref nextIndex);

            int startIndex = nextIndex;

            // Parse optional munis sign
            if (nextIndex < styleValue.Length && styleValue[nextIndex] == '-')
            {
                nextIndex++;
            }

            if (nextIndex < styleValue.Length && Char.IsDigit(styleValue[nextIndex]))
            {
                while (nextIndex < styleValue.Length && (Char.IsDigit(styleValue[nextIndex]) || styleValue[nextIndex] == '.'))
                {
                    nextIndex++;
                }

                string number = styleValue.Substring(startIndex, nextIndex - startIndex);

                string unit = ParseWordEnumeration(_fontSizeUnits, styleValue, ref nextIndex);
                if (unit == null)
                {
                    unit = "px"; // replaceduming pixels by default
                }

                if (mustBeNonNegative && styleValue[startIndex] == '-')
                {
                    return "0";
                }
                else
                {
                    return number + unit;
                }
            }

            return null;
        }

19 Source : Scanner.cs
with Apache License 2.0
from alaatm

private void ReadNumber()
        {
            while (char.IsDigit(Peek()))
            {
                Advance();
            }

            if (Peek() == '.' && char.IsDigit(PeekNext()))
            {
                // Consume the "."
                Advance();

                while (char.IsDigit(Peek()))
                {
                    Advance();
                }
            }

            var value = _source.Substring(_start, _current - _start);
            AddToken(TokenType.Number, decimal.Parse(value));
        }

19 Source : Scanner.cs
with Apache License 2.0
from alaatm

private void ScanToken()
        {
            var c = Advance();
            switch (c)
            {
                case '(':
                    AddToken(TokenType.OpenParenthesis);
                    break;
                case ')':
                    AddToken(TokenType.CloseParenthesis);
                    break;
                case '=':
                    AddToken(TokenType.Equal);
                    break;
                case '!':
                    if (Match('='))
                    {
                        AddToken(TokenType.NotEqual);
                    }
                    else
                    {
                        throw new QueryEngineException($"Unexpected character at position '{_current}'.");
                    }
                    break;
                case '\'':
                    ReadString();
                    break;
                case ' ':
                case '\t':
                case '\r':
                case '\n':
                    break;
                default:
                    if (char.IsDigit(c))
                    {
                        ReadNumber();
                    }
                    else if (char.IsLetter(c))
                    {
                        ReadIdentifier();
                    }
                    else
                    {
                        throw new QueryEngineException($"Unexpected character at position '{_current}'.");
                    }
                    break;
            }
        }

19 Source : Program.cs
with MIT License
from Alan-FGR

public static string IncrementGeneric(string str, int amount)
    {
        var newStr = "";
        foreach (char c in str)
            if (char.IsDigit(c))
                newStr += char.GetNumericValue(c) + amount;
            else
                newStr += c;
        return newStr;
    }

19 Source : JsonHelper.cs
with MIT License
from AlenToma

public static object CreateDateTimeOffset(string value)
        {
            //                   0123456789012345678 9012 9/3 0/4  1/5
            // datetime format = yyyy-MM-ddTHH:mm:ss .nnn  _   +   00:00

            // ISO8601 roundtrip formats have 7 digits for ticks, and no space before the '+'
            // datetime format = yyyy-MM-ddTHH:mm:ss .nnnnnnn  +   00:00  
            // datetime format = yyyy-MM-ddTHH:mm:ss .nnnnnnn  Z  

            int year;
            int month;
            int day;
            int hour;
            int min;
            int sec;
            int ms = 0;
            int usTicks = 0; // ticks for xxx.x microseconds
            int th = 0;
            int tm = 0;

            year = CreateInteger(value, 0, 4);
            month = CreateInteger(value, 5, 2);
            day = CreateInteger(value, 8, 2);
            hour = CreateInteger(value, 11, 2);
            min = CreateInteger(value, 14, 2);
            sec = CreateInteger(value, 17, 2);

            int p = 20;

            if (value.Length > 21 && value[19] == '.')
            {
                ms = CreateInteger(value, p, 3);
                p = 23;

                // handle 7 digit case
                if (value.Length > 25 && char.IsDigit(value[p]))
                {
                    usTicks = CreateInteger(value, p, 4);
                    p = 27;
                }
            }

            if (value[p] == 'Z')
                // UTC
                return CreateDateTimeOffset(year, month, day, hour, min, sec, ms, usTicks, TimeSpan.Zero);

            if (value[p] == ' ')
                ++p;

            // +00:00
            th = CreateInteger(value, p + 1, 2);
            tm = CreateInteger(value, p + 1 + 2 + 1, 2);

            if (value[p] == '-')
                th = -th;

            return CreateDateTimeOffset(year, month, day, hour, min, sec, ms, usTicks, new TimeSpan(th, tm, 0));
        }

19 Source : StrongPasswordChecker.cs
with MIT License
from AlexChesser

public List<int> BuildListOfRepeats(string preplacedword) {
        repeats = new List<int>();
        char current;
        char previous = '\0';
        int number_repeated = 1;
        for (int i = 0; i < preplacedword.Length; i++) {
            current = preplacedword[i];
            if (current == previous) {
                number_repeated++;
                continue;
            }
            if (number_repeated >= MAX_REPEATS) {
                repeats.Add(number_repeated);
            }
            number_repeated = 1;
            if (char.IsDigit(current)) { digit = 0; }
            if (char.IsLower(current)) { lower = 0; }
            if (char.IsUpper(current)) { upper = 0; }
            previous = current;
        }
        if (number_repeated >= MAX_REPEATS) {
            repeats.Add(number_repeated);
        }
        return repeats;
    }

19 Source : NumericTextBox.cs
with MIT License
from AlexGyver

private bool invalidNumeric(char key)
		{
			bool handled = false;

			NumberFormatInfo numberFormatInfo = CultureInfo.CurrentCulture.NumberFormat;
			string decimalSeparator = numberFormatInfo.NumberDecimalSeparator;
			string negativeSign = numberFormatInfo.NegativeSign;

			string keyString = key.ToString();

			if (Char.IsDigit(key))
			{
				// Digits are OK
			}
			else if (AllowDecimalSeparator && keyString.Equals(decimalSeparator))
			{
				if (Text.IndexOf(decimalSeparator) >= 0)
				{
					handled = true;
				}
			}
			else if (AllowNegativeSign && keyString.Equals(negativeSign))
			{
				if (Text.IndexOf(negativeSign) >= 0)
				{
					handled = true;
				}
			}
			else if (key == '\b')
			{
				// Backspace key is OK
			}
			else if ((ModifierKeys & (Keys.Control)) != 0)
			{
				// Let the edit control handle control and alt key combinations
			}
			else
			{
				// Swallow this invalid key and beep
				handled = true;
			}
			return handled;
		}

19 Source : StringHelper.cs
with MIT License
from AlexGyver

public static string Format(IFormatProvider provider, string formatString, object item, params object[] values)
        {
            // Replace items on the format {Property[:Formatstring]}
            var s = FormattingExpression.Replace(
                formatString,
                delegate(Match match)
                    {
                        var property = match.Groups["Property"].Value;
                        if (property.Length > 0 && char.IsDigit(property[0]))
                        {
                            return match.Value;
                        }

                        var pi = item.GetType().GetProperty(property);
                        if (pi == null)
                        {
                            return string.Empty;
                        }

                        var v = pi.GetValue(item, null);
                        var format = match.Groups["Format"].Value;

                        var fs = "{0" + format + "}";
                        return string.Format(provider, fs, v);
                    });

            // Also apply the standard formatting
            s = string.Format(provider, s, values);
            return s;
        }

19 Source : NewSecurityUi.xaml.cs
with Apache License 2.0
from AlexWan

private void SearchSecurity(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Back)
            {
                _startSearch = DateTime.Now;
                _searchString = "";
                LabelSearchString.Content = "";
                return;
            }

            if (!char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                return;
            }

            int freshnessTime = 3; // seconds

            if (_startSearch == null || DateTime.Now.Subtract(_startSearch).Seconds > freshnessTime)
            {
                _startSearch = DateTime.Now;
                _searchString = e.KeyChar.ToString();
                RefreshSearchLabel(freshnessTime);
            }
            else
            {
                _searchString += e.KeyChar.ToString();
                RefreshSearchLabel(freshnessTime);
            }

            char[] charsToTrim = { '*', ' ', '\'', '\"', '+', '=', '-', '!', '#', '%', '.', ',' };

            for (int c = 0; c < _grid.Columns.Count; c++)
            {
                for (int r = 0; r < _grid.Rows.Count; r++)
                {
                    if (_grid.Rows[r].Cells[c].Value.ToString().Trim(charsToTrim)
                        .StartsWith(_searchString, true, CultureInfo.InvariantCulture))
                    {
                        _grid.Rows[r].Cells[c].Selected = true;
                        return; // stop looping
                    }
                }
            }
        }

19 Source : LicenseManagerWindow.cs
with Apache License 2.0
from Algoryx

private void ActivateLicenseGUI()
    {
      GUILayout.Label( GUI.MakeLabel( "Activate license", true ), InspectorEditor.Skin.Label );
      var selectLicenseRect    = GUILayoutUtility.GetLastRect();
      selectLicenseRect.x     += selectLicenseRect.width;
      selectLicenseRect.width  = 28;
      selectLicenseRect.x     -= selectLicenseRect.width;
      selectLicenseRect.y     -= EditorGUIUtility.standardVerticalSpacing;
      var selectLicensePressed = InspectorGUI.Button( selectLicenseRect,
                                                      MiscIcon.Locate,
                                                      UnityEngine.GUI.enabled,
                                                      "Select license file on this computer",
                                                      1.25f );
      if ( selectLicensePressed ) {
        var sourceLicense = EditorUtility.OpenFilePanel( "Copy AGX Dynamics license file",
                                                         ".",
                                                         $"{AGXUnity.LicenseManager.GetLicenseExtension( AGXUnity.LicenseInfo.LicenseType.Service ).Remove( 0, 1 )}," +
                                                         $"{AGXUnity.LicenseManager.GetLicenseExtension( AGXUnity.LicenseInfo.LicenseType.Legacy ).Remove( 0, 1 )}" );
        if ( !string.IsNullOrEmpty( sourceLicense ) ) {
          var targetLicense = AGXUnity.IO.Environment.FindUniqueFilename( $"{LicenseDirectory}/{Path.GetFileName( sourceLicense )}" ).PrettyPath();
          if ( EditorUtility.DisplayDialog( "Copy AGX Dynamics license",
                                          $"Copy \"{sourceLicense}\" to \"{targetLicense}\"?",
                                          "Yes",
                                          "Cancel" ) ) {
            try {
              File.Copy( sourceLicense, targetLicense, false );
              StartUpdateLicenseInformation();
              GUIUtility.ExitGUI();
            }
            catch ( ExitGUIException ) {
              throw;
            }            
            catch ( System.Exception e ) {
              Debug.LogException( e );
            }
          }
        }
      }

      using ( InspectorGUI.IndentScope.Single ) {
        m_licenseActivateData.Id = EditorGUILayout.TextField( GUI.MakeLabel( "License Id" ),
                                                              m_licenseActivateData.Id,
                                                              InspectorEditor.Skin.TextField );
        if ( m_licenseActivateData.Id.Any( c => !char.IsDigit( c ) ) )
          m_licenseActivateData.Id = new string( m_licenseActivateData.Id.Where( c => char.IsDigit( c ) ).ToArray() );
        m_licenseActivateData.Preplacedword = EditorGUILayout.PreplacedwordField( GUI.MakeLabel( "Activation Code" ),
                                                                        m_licenseActivateData.Preplacedword );

        InspectorGUI.SelectFolder( GUI.MakeLabel( "License File Directory" ),
                                   LicenseDirectory,
                                   "License file directory",
                                   newDirectory =>
                                   {
                                     newDirectory = newDirectory.PrettyPath();

                                     if ( string.IsNullOrEmpty( newDirectory ) )
                                       newDirectory = "replacedets";

                                     if ( !Directory.Exists( newDirectory ) ) {
                                       Debug.LogWarning( $"Invalid license directory: {newDirectory} - directory doesn't exist." );
                                       return;
                                     }
                                     else if ( !IO.Utils.IsValidProjectFolder( newDirectory ) ) {
                                       Debug.LogWarning( $"Invalid license directory: {newDirectory} - directory has to be in the project." );
                                       return;
                                     }
                                     LicenseDirectory = newDirectory;
                                   } );

        using ( new GUI.EnabledBlock( UnityEngine.GUI.enabled &&
                                      m_licenseActivateData.Id.Length > 0 &&
                                      m_licenseActivateData.Preplacedword.Length > 0 ) ) {
          // It isn't possible to press this button during activation.
          if ( UnityEngine.GUI.Button( EditorGUI.IndentedRect( EditorGUILayout.GetControlRect() ),
                                       GUI.MakeLabel( AGXUnity.LicenseManager.IsBusy ?
                                                        "Activating..." :
                                                        "Activate" ),
                                                      InspectorEditor.Skin.Button ) ) {
            AGXUnity.LicenseManager.ActivateAsync( System.Convert.ToInt32( m_licenseActivateData.Id ),
                                                   m_licenseActivateData.Preplacedword,
                                                   LicenseDirectory,
                                                   success =>
                                                   {
                                                     if ( success )
                                                       m_licenseActivateData = IdPreplacedword.Empty();
                                                     else
                                                       Debug.LogError( "License Error: ".Color( Color.red ) + AGXUnity.LicenseManager.LicenseInfo.Status );

                                                     StartUpdateLicenseInformation();

                                                     UnityEngine.GUI.FocusControl( "" );
                                                   } );
          }
        }
      }
    }

19 Source : Lexer.cs
with MIT License
from alirezanet

public SyntaxToken NextToken()
      {
         if (_position >= _text.Length) return new SyntaxToken(SyntaxKind.End, _position, "\0");

         var peek = Peek(1);
         switch (Current)
         {
            case '(':
               return new SyntaxToken(SyntaxKind.OpenParenthesisToken, _position++, "(");
            case ')':
               return new SyntaxToken(SyntaxKind.CloseParenthesis, _position++, ")");
            case ',':
               return new SyntaxToken(SyntaxKind.And, _position++, ",");
            case '|':
               return new SyntaxToken(SyntaxKind.Or, _position++, "|");
            case '^':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.StartsWith, _position++, "^");
            }
            case '$':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.EndsWith, _position++, "$");
            }
            case '!' when peek == '^':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.NotStartsWith, _position += 2, "!^");
            }
            case '!' when peek == '$':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.NotEndsWith, _position += 2, "!$");
            }
            case '=' when peek == '*':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.Like, _position += 2, "=*");
            }
            case '=':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.Equal, _position ++ , "=");
            }
            case '!' when peek == '=':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.NotEqual, _position += 2, "!=");
            }
            case '!' when peek == '*':
            {
               _waitingForValue = true;
               return new SyntaxToken(SyntaxKind.NotLike, _position += 2, "!*");
            }
            case '/' when peek == 'i':
               return new SyntaxToken(SyntaxKind.CaseInsensitive, _position += 2, "/i");
            case '<':
            {
               _waitingForValue = true;
               return peek == '=' ? new SyntaxToken(SyntaxKind.LessOrEqualThan, _position += 2, "<=") :
                  new SyntaxToken(SyntaxKind.LessThan, _position++, "<");
            }
            case '>':
            {
               _waitingForValue = true;
               return peek == '=' ? new SyntaxToken(SyntaxKind.GreaterOrEqualThan, _position += 2, ">=") : 
                  new SyntaxToken(SyntaxKind.GreaterThan, _position++, ">");
            }
         }

         if (Current == '[')
         {
            Next();
            var start = _position; 
            while (char.IsDigit(Current))  
               Next();
      
            var length = _position - start;
            var text = _text.Substring(start, length);

            if (Current == ']')
            {
               _position++;
               return new SyntaxToken(SyntaxKind.FieldIndexToken, start, text);
            }
            
            _diagnostics.Add($"bad character input: '{peek.ToString()}' at {_position++.ToString()}. expected ']' ");
            return new SyntaxToken(SyntaxKind.BadToken, _position, Current.ToString());

         }

         if (char.IsLetter(Current) && !_waitingForValue)
         {
            var start = _position;

            while (char.IsLetterOrDigit(Current) || Current is '_')  
               Next();

            var length = _position - start;
            var text = _text.Substring(start, length);
            
            return new SyntaxToken(SyntaxKind.FieldToken, start, text);
         }
         

         if (char.IsWhiteSpace(Current))
         {
            var start = _position;

            // skipper
            while (char.IsWhiteSpace(Current))
               Next();

            var length = _position - start;
            var text = _text.Substring(start, length);

            return new SyntaxToken(SyntaxKind.WhiteSpace, start, text);
         }

         if (_waitingForValue)
         {
            var start = _position;

            var exitCharacters = new[] {'(', ')', ',', '|'};
            var lastChar = '\0';
            while ((!exitCharacters.Contains(Current) || exitCharacters.Contains(Current) && lastChar == '\\') &&
                   _position < _text.Length &&
                   (!(Current == '/' && Peek(1) == 'i') || (Current == '/' && Peek(1) == 'i') && lastChar == '\\')) // exit on case-insensitive operator
            {
               lastChar = Current;
               Next();
            }

            var text = new StringBuilder();
            for (var i = start; i < _position; i++)
            {
               var current = _text[i];

               if (current != '\\') // ignore escape character
                  text.Append(current);
               else if (current == '\\' && i > 0) // escape escape character
                  if (_text[i - 1] == '\\')
                     text.Append(current);
            }

            _waitingForValue = false;
            return new SyntaxToken(SyntaxKind.ValueToken, start, text.ToString());
         }

         _diagnostics.Add($"bad character input: '{Current.ToString()}' at {_position.ToString()}");
         return new SyntaxToken(SyntaxKind.BadToken, _position++, string.Empty);
      }

19 Source : CharExtension.cs
with MIT License
from AlphaYu

public static bool IsDigit(this char c)
        {
            return char.IsDigit(c);
        }

19 Source : Lexer.cs
with MIT License
from Alprog

public IEnumerator<Token> Tokenize(string line)
        {
            var token = new Token(TokenType.Invalid, 0, line.Length);
            int i = 0;
            while (i < line.Length)
            {
                var c = line[i];
                if (Char.IsWhiteSpace(c))
                {
                    // WhiteSpace
                    i++;
                    continue;
                }
                else if (Char.IsLetter(c) || c.Equals('_'))
                {
                    // Identifier or Keyword
                    int si = i; i++;
                    while (i < line.Length)
                    {
                        c = line[i];
                        if (Char.IsLetterOrDigit(c) || c.Equals('_'))
                        {
                            i++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    var tokenText = line.Substring(si, i - si);
                    if (tokenText.ToLower() == "true")
                    {
                        token = ValueToken(si, i - si, true);
                    }
                    else if (tokenText.ToLower() == "false")
                    {
                        token = ValueToken(si, i - si, false);
                    }
                    else if (tokenText.ToLower() == "null")
                    {
                        token = ValueToken(si, i - si, null);
                    }
                    else
                    {
                        if (i < line.Length && line[i].Equals('…'))
                        {
                            token = new Token(TokenType.Autocomplete, si, i - si, tokenText);
                            i++;
                        }
                        else
                        {
                            token = new Token(TokenType.Identifier, si, i - si, tokenText);
                        }
                    }
                }
                else if (c.Equals('\"'))
                {
                    // String
                    int si = i; i++;
                    bool ended = false;
                    while (i < line.Length)
                    {
                        c = line[i];
                        if (!c.Equals('\"'))
                        {
                            i++;
                        }
                        else
                        {
                            ended = true;
                            i++;
                            break;
                        }
                    }
                    if (ended)
                    {
                        var text = line.Substring(si + 1, i - si - 2);
                        token = ValueToken(si, i - si, text);
                    }
                    else
                    {
                        token = new Token(TokenType.Invalid, si, i - si);
                    }
                }
                else if (Char.IsDigit(c) || c.Equals('-'))
                {
                    // Minus or digit
                    if (c.Equals('-'))
                    {
                        if (token.Type == TokenType.Value ||
                            token.Type == TokenType.Identifier ||
                            token.Type == TokenType.ClosedBracket)
                        {
                            // force minus operator
                            i++;
                            token = new Token(TokenType.Operator, i, 1, Operator.Get("-"));
                            yield return token;
                            continue;
                        }
                    }

                    int si = i; i++;
                    while (i < line.Length)
                    {
                        c = line[i];
                        if (Char.IsDigit(c) || c.Equals('.'))
                        {
                            i++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    var tokenText = line.Substring(si, i - si);
                    if (tokenText == "-")
                    {
                        token = new Token(TokenType.Operator, si, i - si, Operator.Get(tokenText));
                        i++;
                    }
                    else
                    {
                        float number;
                        if (Single.TryParse(tokenText, NumberStyles.Any, CultureInfo.InvariantCulture, out number))
                        {
                            token = ValueToken(si, i - si, number);
                        }
                        else
                        {
                            token = new Token(TokenType.Invalid, si, i - si);
                        }
                    }
                }
                else if (operators.Contains(c.ToString()))
                {
                    // Operator
                    int si = i; i++;
                    while (i < line.Length)
                    {
                        c = line[i];
                        if (operators.Contains(c.ToString()))
                        {
                            i++;
                        }
                        else
                        {
                            break;
                        }
                    }
                    var tokenText = line.Substring(si, i - si);
                    if (tokenText == "=")
                    {
                        token = new Token(TokenType.replacedignmentOperator, si, i - si);
                    }
                    else
                    {
                        token = new Token(TokenType.Operator, si, i - si, Operator.Get(tokenText));
                    }
                }
                else if (c.Equals('.'))
                {
                    token = new Token(TokenType.Dot, i, 1);
                    i++;
                }
                else if (c.Equals('('))
                {
                    token = new Token(TokenType.OpenBracket, i, 1);
                    i++;
                }
                else if (c.Equals(')'))
                {
                    token = new Token(TokenType.ClosedBracket, i, 1);
                    i++;
                }
                else if (c.Equals(','))
                {
                    token = new Token(TokenType.Comma, i, 1);
                    i++;
                }
                else if (c.Equals('…'))
                {
                    token = new Token(TokenType.Autocomplete, i, 1, String.Empty);
                    i++;
                }
                else
                {
                    token = new Token(TokenType.Invalid, i, 1);
                    i++;
                }

                yield return token;
            }

            yield return new Token(TokenType.EndOfLine, i, 0);
        }

19 Source : StringExtension.cs
with MIT License
from AlturosDestinations

public static int GetFirstNumber(this string text)
        {
            var tempNumber = new string(
                text.SkipWhile(c => !char.IsDigit(c)).
                TakeWhile(c => char.IsDigit(c)).
                ToArray());

            int.TryParse(tempNumber, out var number);

            return number;
        }

19 Source : CreditCardValidation.cs
with MIT License
from andrebaltieri

public Contract<T> IsCreditCard(string val, string key, string message)
        {
            val = Regex.Replace(val, FluntRegexPatterns.OnlyNumbersPattern, "");

            if (string.IsNullOrWhiteSpace(val))
            {
                AddNotification(key, message);
                return this;
            }

            var even = false;
            var checksum = 0;

            foreach (var digit in val.ToCharArray().Reverse())
            {
                if (!char.IsDigit(digit))
                {
                    AddNotification(val, message);
                    return this;
                }

                var value = (digit - '0') * (even ? 2 : 1);
                even = !even;

                while (value > 0)
                {
                    checksum += value % 10;
                    value /= 10;
                }
            }

            if (checksum % 10 != 0)
                AddNotification(key, message);

            return this;
        }

19 Source : EnumTransformer.cs
with MIT License
from AndresTraks

private static string[] GetNameParts(string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                return new string[0];
            }

            var parts = name.Split('_');

            for (int i = 0; i < parts.Length; i++)
            {
                string part = parts[i];
                if (part.Length > 0 && part.All(c => char.IsUpper(c) || char.IsDigit(c)))
                {
                    parts[i] = part[0] + part.Substring(1).ToLower();
                }
            }

            return parts;
        }

19 Source : Threshold.cs
with MIT License
from AndreyAkinshin

public static bool TryParse(string input, NumberStyles numberStyle, IFormatProvider formatProvider, out Threshold parsed)
        {
            if (string.IsNullOrWhiteSpace(input))
            {
                parsed = default;
                return false;
            }

            var trimmed = input.Trim().ToLowerInvariant();
            var number = new string(trimmed.TakeWhile(c => char.IsDigit(c) || c == '.' || c == ',').ToArray());
            var unit = new string(trimmed.SkipWhile(c => char.IsDigit(c) || c == '.' || c == ',' || char.IsWhiteSpace(c)).ToArray());

            if (!double.TryParse(number, numberStyle, formatProvider, out var parsedValue)
                || !ThresholdUnitExtensions.ShortNameToUnit.TryGetValue(unit, out var parsedUnit))
            {
                parsed = default;
                return false;
            }

            parsed = parsedUnit == ThresholdUnit.Ratio ? Create(ThresholdUnit.Ratio, parsedValue / 100.0) : Create(parsedUnit, parsedValue);

            return true;
        }

19 Source : KeywordEditor.cs
with MIT License
from AngeloCresta

private void KeywordEditor_Load(object sender, System.EventArgs e)
		{
			// Set restriction on the Y Value index editor
			if(this._maxYValueIndex >= 0 && this._maxYValueIndex < 10)
			{
				this._numericUpDownYValue.Maximum = this._maxYValueIndex;
			}
			this._numericUpDownYValue.Enabled = this._maxYValueIndex > 0;
			this._labelYValue.Enabled = this._maxYValueIndex > 0;

			// Set tooltip for custom format
            this._toolTip.SetToolTip(this._textBoxCustomFormat, SR.DescriptionToolTipCustomFormatCharacters);

			// Select format None
			this._comboBoxFormat.SelectedIndex = 0;

			// Fill list of applicable keywords
			if(this._applicableKeywords != null)
			{
				foreach(KeywordInfo keywordInfo in this._applicableKeywords)
				{
					this._listBoxKeywords.Items.Add(keywordInfo);
				}
			}

			// Check if keyword for editing was specified
			if(this.Keyword.Length == 0)
			{
				this._listBoxKeywords.SelectedIndex = 0;
				this._comboBoxFormat.SelectedIndex = 0;
			}
			else
			{
				// Iterate through all keywords and find a match
				bool itemFound = false;
				foreach(KeywordInfo keywordInfo in this._applicableKeywords)
				{
					// Iterate through all possible keyword names
					string[] keywordNames = keywordInfo.GetKeywords();
					foreach(string keywordName in keywordNames)
					{
						if(this.Keyword.StartsWith(keywordName, StringComparison.Ordinal))
						{
							// Select keyword in the list
							this._listBoxKeywords.SelectedItem = keywordInfo;
							int keywordLength = keywordName.Length;

							// Check if keyword support multiple Y values
							if(keywordInfo.SupportsValueIndex)
							{
								if(this.Keyword.Length > keywordLength &&
									this.Keyword[keywordLength] == 'Y')
								{
									++keywordLength;
									if(this.Keyword.Length > (keywordLength) &&
										char.IsDigit(this.Keyword[keywordLength]))
									{
										int yValueIndex = int.Parse(this.Keyword.Substring(keywordLength, 1), CultureInfo.InvariantCulture);
										if(yValueIndex < 0 || yValueIndex > this._maxYValueIndex)
										{
											yValueIndex = 0;
										}
										_numericUpDownYValue.Value = yValueIndex;
										++keywordLength;
									}
								}
							}

							// Check if keyword support format string
							if(keywordInfo.SupportsFormatting)
							{
								if(this.Keyword.Length > keywordLength &&
									this.Keyword[keywordLength] == '{' &&
									this.Keyword.EndsWith("}", StringComparison.Ordinal))
								{
									// Get format string
									string format = this.Keyword.Substring(keywordLength + 1, this.Keyword.Length - keywordLength - 2);

									if(format.Length == 0)
									{
										// Select format None
										this._comboBoxFormat.SelectedIndex = 0;
									}
									else
									{
										// Check if format string is custom
										if(format.Length == 1 ||
											(format.Length == 2 && char.IsDigit(format[1])) ||
											(format.Length == 3 && char.IsDigit(format[2])) )
										{
											if(format[0] == 'C')
											{
												this._comboBoxFormat.SelectedIndex = 1;
											}
											else if(format[0] == 'D')
											{
												this._comboBoxFormat.SelectedIndex = 2;
											}
											else if(format[0] == 'E')
											{
												this._comboBoxFormat.SelectedIndex = 3;
											}
											else if(format[0] == 'F')
											{
												this._comboBoxFormat.SelectedIndex = 4;
											}
											else if(format[0] == 'G')
											{
												this._comboBoxFormat.SelectedIndex = 5;
											}
											else if(format[0] == 'N')
											{
												this._comboBoxFormat.SelectedIndex = 6;
											}
											else if(format[0] == 'P')
											{
												this._comboBoxFormat.SelectedIndex = 7;
											}
											else
											{
												// Custom format
												this._comboBoxFormat.SelectedIndex = 8;
												this._textBoxCustomFormat.Text = format;
											}

											// Get precision
											if(this._comboBoxFormat.SelectedIndex != 8 && format.Length > 0)
											{
												this._textBoxPrecision.Text = format.Substring(1);
											}
										}
										else
										{
											// Custom format
											this._comboBoxFormat.SelectedIndex = 8;
											this._textBoxCustomFormat.Text = format;
										}
									}
								}
							}

							// Stop iteration
							itemFound = true;
							break;
						}
					}

					// Break from the keywords loop
					if(itemFound)
					{
						break;
					}
				}
			}
		}

19 Source : KeywordsStringEditor.cs
with MIT License
from AngeloCresta

private string GetColorHilightedRtfText(string originalText)
		{
			string resultText = originalText;
			string selectedKeyword = string.Empty;

			// Reset selected keyword position
			this._selectedKeywordStart = -1;
			this._selectedKeywordLength = 0;

			// Current selection position that will be adjusted when formatting 
			// characters are added infron of it.
			int selectionStart = this._richTextBox.SelectionStart;

			// Replace special new line character sequence "\n"
			resultText = resultText.Replace("\\n", "\r\n");

			// Replace special RTF Character '\'
			int slashCountre = 0;
			for(int index = 0; index < resultText.Length && index < selectionStart; index ++)
			{
				if(resultText[index] == '\\')
				{
					++slashCountre;
				}
			}
			selectionStart += slashCountre;
			resultText = resultText.Replace(@"\", @"\\");

			// Iterate through all keywords 
			foreach(KeywordInfo keywordInfo in this.applicableKeywords)
			{
				// Fill array of possible names for that keyword
				string[] keywordNames = keywordInfo.GetKeywords();

				// Iterate through all possible names
				foreach(string keywordNameWithSpaces in keywordNames)
				{
					int startIndex = 0;

					// Trim spaces
					string keywordName = keywordNameWithSpaces.Trim();

					// Skip empty strings
					if(keywordName.Length > 0)
					{
						// Try finding the keyword in the string
						while( (startIndex = resultText.IndexOf(keywordName, startIndex, StringComparison.Ordinal)) >= 0)
						{
							int keywordLength = keywordName.Length;

							// Check if Y value index can be part of the keyword
							if(keywordInfo.SupportsValueIndex)
							{
								if(resultText.Length > (startIndex + keywordLength) &&
									resultText[startIndex + keywordLength] == 'Y')
								{
									++keywordLength;
									if(resultText.Length > (startIndex + keywordLength) && 
										char.IsDigit(resultText[startIndex + keywordLength]))
									{
										++keywordLength;
									}
								}
							}

							// Check if format string can be part of the keyword
							if(keywordInfo.SupportsFormatting)
							{
								if(resultText.Length > (startIndex + keywordLength) &&
									resultText[startIndex + keywordLength] == '{')
								{
									++keywordLength;
									int formatEndBracket = resultText.IndexOf("}", startIndex + keywordLength, StringComparison.Ordinal);
									if(formatEndBracket >= 0)
									{
										keywordLength += formatEndBracket - startIndex - keywordLength + 1;
									}
								}
							}

							// Check if cursor currently located inside the keyword
							bool isKeywordSelected = (selectionStart > (startIndex) && 
								selectionStart <= (startIndex + keywordLength) );

							// Show Keyword with different color
							string tempText = resultText.Substring(0, startIndex);
							string formattedKeyword = string.Empty;
							formattedKeyword += @"\cf1";
							if(isKeywordSelected)
							{
								// Remember selected keyword by name and position
								selectedKeyword = keywordInfo.Name;
								selectedKeyword += "__" + startIndex.ToString(CultureInfo.InvariantCulture);
								this._selectedKeywordStart = startIndex;
								this._selectedKeywordStart -= selectionStart - this._richTextBox.SelectionStart;
 								this._selectedKeywordLength = keywordLength;

								formattedKeyword += @"\b";
							}
							formattedKeyword += @"\ul";
							// Replace keyword start symbol '#' with "#_" to avoid duplicate processing
							formattedKeyword += "#_";		
                            formattedKeyword += resultText.Substring(startIndex + 1, keywordLength - 1);
							formattedKeyword += @"\cf0";
							if(isKeywordSelected)
							{
								formattedKeyword += @"\b0";
							}
							formattedKeyword += @"\ul0 ";
							tempText += formattedKeyword;
							tempText += resultText.Substring(startIndex + keywordLength);
							resultText = tempText;

							// Adjust selection position
							if(startIndex < selectionStart)
							{
								selectionStart += formattedKeyword.Length - keywordLength;
							}

							// Increase search start index by the length of the keyword
							startIndex += formattedKeyword.Length;
						}
					}
				}
			}
		
			// Set currenly selected keyword name
			this._selectedKeywordName = selectedKeyword;

			// Update Edit button
			if(this._selectedKeywordName.Length > 0)
			{
				// Enable Edit button and set it text
				this._buttonEdit.Enabled = true;
			}
			else
			{
				this._buttonEdit.Enabled = false;
			}

			// Replace all the "\n" strings with new line objectTag "\par"
			resultText = resultText.Replace("\r\n", @"\par ");
			resultText = resultText.Replace("\n", @"\par ");
			resultText = resultText.Replace("\\n", @"\par ");

			// Replace special RTF Characters '{' and '}'
			// Has to be done after all processing because this character is 
			// used in keywords formatting.
			resultText = resultText.Replace(@"{", @"\{");
			resultText = resultText.Replace(@"}", @"\}");

			// Replace the "#_" string with keyword start symbol.
			// This  was previously chnaged to avoid duplicate processing.
			return resultText.Replace("#_", "#");
		}

19 Source : Functions.cs
with MIT License
from ansel86castro

[ParserFunction]
        public static string Pascal(this string s)
        {
            var sections = s.Split('_');
            StringBuilder sb = new StringBuilder();
            foreach (var part in sections)
            {

                for (int i = 0; i < part.Length; i++)
                {
                    var c = part[i];
                    if (i == 0)
                    {
                        sb.Append(char.ToUpperInvariant(c));
                    }
                    else if (i < part.Length - 1 && char.IsLower(part[i - 1]) && char.IsUpper(c))
                    {
                        sb.Append(c);
                    }
                    else
                    {
                        sb.Append(char.ToLowerInvariant(c));
                    }

                }             
            }

            var result = sb.ToString();
            if(result.All(x => char.IsDigit(x)))
            {
                result = "_" + result;
            }

            return result;
        }

19 Source : QueryLexicalAnalizer.cs
with MIT License
from ansel86castro

protected Token GetNextTokenFromStream()
        {
            SkipSpaces();
            int simbol = Peek();

            if (simbol == -1)
                return null;

            String value;

            TokenType tokenType = IsSymbol(simbol);

            if (tokenType != TokenType.UNKNOW)
            {
                value = _string.Substring(index, simbolWidth);
                Skip(simbolWidth);
                return new Token(tokenType, value);
            }

            if (simbol == '\'')
            {
                value = ReadString();
                return new Token(TokenType.STRING, value);

            }
            else if (char.IsDigit((char)simbol))
            {
                value = ReadInteger();
                simbol = Peek();
                if (simbol == -1 || IsWhiteSpace(simbol))
                    return new Token(TokenType.INT, value);

                TokenType token = IsSymbol(simbol);
                if (token == TokenType.DOT)
                {
                    Read();
                    return new Token(TokenType.DOUBLE, value + "." + ReadInteger());
                }
                else if (token != TokenType.UNKNOW)
                {
                    return new Token(TokenType.INT, value);
                }
                else
                    throw new TokenMismatchException(String.Format("expecting number at COL: {0} ROW: {1}", Col, Row));

            }
            else if (simbol == '_' || Char.IsLetter((char)simbol))
            {
                value = ReadWord(simbol);
                TokenType keyword = GetKeyword(value);
                if (keyword != TokenType.UNKNOW)
                {
                    return new Token(keyword, value);
                }
                return new Token(TokenType.ID, value);
            }

            return null;

        }

19 Source : QueryLexicalAnalizer.cs
with MIT License
from ansel86castro

private String ReadInteger()
        {
            StringBuilder sb = new StringBuilder();
            int c = Peek();

            while (c > 0)
            {
                c = Peek();
                if (c == -1)
                    break;
                if (IsWhiteSpace(c) || IsSymbol(c) != TokenType.UNKNOW || c == '\'')
                {
                    break;
                }
                else if (!Char.IsDigit((char)c))
                {
                    throw new TokenMismatchException(String.Format("Expecting Integer '{0}' at COL:{1} ROW: {2}", sb.ToString(), Col, Row));
                }

                sb.Append((char)c);
                Read();
            }
            return sb.ToString();
        }

19 Source : CybtansModelBinder.cs
with MIT License
from ansel86castro

public static string Pascal(string s)
        {
            var sections = s.Split('_');
            StringBuilder sb = new StringBuilder();
            foreach (var part in sections)
            {

                for (int i = 0; i < part.Length; i++)
                {
                    var c = part[i];
                    if (i == 0)
                    {
                        sb.Append(char.ToUpperInvariant(c));
                    }
                    else if (i < part.Length - 1 && char.IsLower(part[i - 1]) && char.IsUpper(c))
                    {
                        sb.Append(c);
                    }
                    else
                    {
                        sb.Append(char.ToLowerInvariant(c));
                    }

                }
            }

            var result = sb.ToString();
            if (result.All(x => char.IsDigit(x)))
            {
                result = "_" + result;
            }

            return result;
        }

19 Source : Functions.cs
with MIT License
from ansel86castro

[ParserFunction]
        public static string Camel(this string s)
        {
            StringBuilder sb = new StringBuilder();
            var sections = s.Split('_');

            if (sections.Length > 0)
            {
                foreach (var part in sections)
                {
                    for (int i = 0; i < part.Length; i++)
                    {
                        var c = part[i];
                        if (i == 0)
                        {
                            sb.Append(char.ToLowerInvariant(c));
                        }
                        else if (i < part.Length - 1 && char.IsLower(part[i - 1]) && char.IsUpper(c))
                        {
                            sb.Append(c);
                        }
                        else
                        {
                            sb.Append(char.ToLowerInvariant(c));
                        }

                    }
                }
            }

            var result = sb.ToString();
            if (result.All(x => char.IsDigit(x)))
            {
                result = "_" + result;
            }

            return result;
        }

19 Source : TypeNameParser.cs
with GNU General Public License v3.0
from anydream

IList<TSpec> ReadTSpecs() {
			var tspecs = new List<TSpec>();
			while (true) {
				SkipWhite();
				switch (PeekChar()) {
				case '[':	// SZArray, Array, or GenericInst
					ReadChar();
					SkipWhite();
					var peeked = PeekChar();
					if (peeked == ']') {
						// SZ array
						Verify(ReadChar() == ']', "Expected ']'");
						tspecs.Add(SZArraySpec.Instance);
					}
					else if (peeked == '*' || peeked == ',' || peeked == '-' || char.IsDigit((char)peeked)) {
						// Array

						var arraySpec = new ArraySpec();
						arraySpec.rank = 0;
						while (true) {
							SkipWhite();
							int c = PeekChar();
							if (c == '*')
								ReadChar();
							else if (c == ',' || c == ']') {
							}
							else if (c == '-' || char.IsDigit((char)c)) {
								int lower = ReadInt32();
								uint? size;
								SkipWhite();
								Verify(ReadChar() == '.', "Expected '.'");
								Verify(ReadChar() == '.', "Expected '.'");
								if (PeekChar() == '.') {
									ReadChar();
									size = null;
								}
								else {
									SkipWhite();
									if (PeekChar() == '-') {
										int upper = ReadInt32();
										Verify(upper >= lower, "upper < lower");
										size = (uint)(upper - lower + 1);
										Verify(size.Value != 0 && size.Value <= 0x1FFFFFFF, "Invalid size");
									}
									else {
										uint upper = ReadUInt32();
										long lsize = (long)upper - (long)lower + 1;
										Verify(lsize > 0 && lsize <= 0x1FFFFFFF, "Invalid size");
										size = (uint)lsize;
									}
								}
								if (arraySpec.lowerBounds.Count == arraySpec.rank)
									arraySpec.lowerBounds.Add(lower);
								if (size.HasValue && arraySpec.sizes.Count == arraySpec.rank)
									arraySpec.sizes.Add(size.Value);
							}
							else
								Verify(false, "Unknown char");

							arraySpec.rank++;
							SkipWhite();
							if (PeekChar() != ',')
								break;
							ReadChar();
						}

						Verify(ReadChar() == ']', "Expected ']'");
						tspecs.Add(arraySpec);
					}
					else {
						// Generic args

						var ginstSpec = new GenericInstSpec();
						while (true) {
							SkipWhite();
							peeked = PeekChar();
							bool needSeperators = peeked == '[';
							if (peeked == ']')
								break;
							Verify(!needSeperators || ReadChar() == '[', "Expected '['");
							ginstSpec.args.Add(ReadType(needSeperators));
							SkipWhite();
							Verify(!needSeperators || ReadChar() == ']', "Expected ']'");
							SkipWhite();
							if (PeekChar() != ',')
								break;
							ReadChar();
						}

						Verify(ReadChar() == ']', "Expected ']'");
						tspecs.Add(ginstSpec);
					}
					break;

				case '&':	// ByRef
					ReadChar();
					tspecs.Add(ByRefSpec.Instance);
					break;

				case '*':	// Ptr
					ReadChar();
					tspecs.Add(PtrSpec.Instance);
					break;

				default:
					return tspecs;
				}
			}
		}

19 Source : PatternParser.cs
with Apache License 2.0
from apache

private void ParseInternal(string pattern, string[] matches)
		{
			int offset = 0;
			while(offset < pattern.Length)
			{
				int i = pattern.IndexOf('%', offset);
				if (i < 0 || i == pattern.Length - 1)
				{
					ProcessLiteral(pattern.Substring(offset));
					offset = pattern.Length;
				}
				else
				{
					if (pattern[i+1] == '%')
					{
						// Escaped
						ProcessLiteral(pattern.Substring(offset, i - offset + 1));
						offset = i + 2;
					}
					else
					{
						ProcessLiteral(pattern.Substring(offset, i - offset));
						offset = i + 1;

						FormattingInfo formattingInfo = new FormattingInfo();

						// Process formatting options

						// Look for the align flag
						if (offset < pattern.Length)
						{
							if (pattern[offset] == '-')
							{
								// Seen align flag
								formattingInfo.LeftAlign = true;
								offset++;
							}
						}
						// Look for the minimum length
						while (offset < pattern.Length && char.IsDigit(pattern[offset]))
						{
							// Seen digit
							if (formattingInfo.Min < 0)
							{
								formattingInfo.Min = 0;
							}

							formattingInfo.Min = (formattingInfo.Min * 10) + int.Parse(pattern[offset].ToString(), NumberFormatInfo.InvariantInfo);

							offset++;
						}
						// Look for the separator between min and max
						if (offset < pattern.Length)
						{
							if (pattern[offset] == '.')
							{
								// Seen separator
								offset++;
							}
						}
						// Look for the maximum length
						while (offset < pattern.Length && char.IsDigit(pattern[offset]))
						{
							// Seen digit
							if (formattingInfo.Max == int.MaxValue)
							{
								formattingInfo.Max = 0;
							}

							formattingInfo.Max = (formattingInfo.Max * 10) + int.Parse(pattern[offset].ToString(), NumberFormatInfo.InvariantInfo);

							offset++;
						}

						int remainingStringLength = pattern.Length - offset;

						// Look for pattern
						for(int m=0; m<matches.Length; m++)
						{
							string key = matches[m];

							if (key.Length <= remainingStringLength)
							{
								if (string.Compare(pattern, offset, key, 0, key.Length) == 0)
								{
									// Found match
									offset = offset + matches[m].Length;

									string option = null;

									// Look for option
									if (offset < pattern.Length)
									{
										if (pattern[offset] == '{')
										{
											// Seen option start
											offset++;
											
											int optEnd = pattern.IndexOf('}', offset);
											if (optEnd < 0)
											{
												// error
											}
											else
											{
												option = pattern.Substring(offset, optEnd - offset);
												offset = optEnd + 1;
											}
										}
									}

									ProcessConverter(matches[m], option, formattingInfo);
									break;
								}
							}
						}
					}
				}
			}
		}

19 Source : AlphanumComparatorFast.cs
with MIT License
from Apollo199999999

public int Compare(object x, object y)
    {
        string s1 = x as string;
        if (s1 == null)
        {
            return 0;
        }
        string s2 = y as string;
        if (s2 == null)
        {
            return 0;
        }

        int len1 = s1.Length;
        int len2 = s2.Length;
        int marker1 = 0;
        int marker2 = 0;

        // Walk through two the strings with two markers.
        while (marker1 < len1 && marker2 < len2)
        {
            char ch1 = s1[marker1];
            char ch2 = s2[marker2];

            // Some buffers we can build up characters in for each chunk.
            char[] space1 = new char[len1];
            int loc1 = 0;
            char[] space2 = new char[len2];
            int loc2 = 0;

            // Walk through all following characters that are digits or
            // characters in BOTH strings starting at the appropriate marker.
            // Collect char arrays.
            do
            {
                space1[loc1++] = ch1;
                marker1++;

                if (marker1 < len1)
                {
                    ch1 = s1[marker1];
                }
                else
                {
                    break;
                }
            } while (char.IsDigit(ch1) == char.IsDigit(space1[0]));

            do
            {
                space2[loc2++] = ch2;
                marker2++;

                if (marker2 < len2)
                {
                    ch2 = s2[marker2];
                }
                else
                {
                    break;
                }
            } while (char.IsDigit(ch2) == char.IsDigit(space2[0]));

            // If we have collected numbers, compare them numerically.
            // Otherwise, if we have strings, compare them alphabetically.
            string str1 = new string(space1);
            string str2 = new string(space2);

            int result;

            if (char.IsDigit(space1[0]) && char.IsDigit(space2[0]))
            {
                int thisNumericChunk = int.Parse(str1);
                int thatNumericChunk = int.Parse(str2);
                result = thisNumericChunk.CompareTo(thatNumericChunk);
            }
            else
            {
                result = str1.CompareTo(str2);
            }

            if (result != 0)
            {
                return result;
            }
        }
        return len1 - len2;
    }

19 Source : PhoneEditTextBinding.cs
with Apache License 2.0
from AppRopio

private string FilteredPhoneString(string str, string filter)
        {
            int onOriginal = 0, onFilter = 0, onOutput = 0;
            var outputString = new StringBuilder();
            bool done = false;

            while (onFilter < filter.Length && !done)
            {
                var filterChar = filter[onFilter];
                var originalChar = onOriginal >= str.Length ? (char)0 : str[onOriginal];
                switch (filterChar)
                {
                    case '#':
                        if (originalChar == 0)
                        {
                            done = true;
                            if (outputString.Length > 1 && outputString[outputString.Length - 1] == ' ')
                                outputString.Remove(outputString.Length - 1, 1);
                            break;
                        }
                        if (char.IsDigit(originalChar))
                        {
                            outputString.Append(originalChar);
                            onOriginal++;
                            onFilter++;
                            onOutput++;
                        }
                        else
                        {
                            onOriginal++;
                        }
                        break;
                    default:
                        // Any other character will automatically be inserted for the user as they type (spaces, - etc..) or deleted as they delete if there are more numbers to come.
                        outputString.Append(filterChar);
                        onOutput++;
                        onFilter++;
                        if (originalChar == filterChar)
                            onOriginal++;
                        break;
                }
            }
            return outputString.ToString();
        }

19 Source : FiltersDateBinding.cs
with Apache License 2.0
from AppRopio

private string FilteredPhoneString(string str, string filter)
        {
            int onOriginal = 0, onFilter = 0, onOutput = 0;
            var outputString = new StringBuilder();
            bool done = false;

            while (onFilter < filter.Length && !done)
            {
                var filterChar = filter[onFilter];
                var originalChar = onOriginal >= str.Length ? (char)0 : str[onOriginal];
                switch (filterChar)
                {
                    case '#':
                        if (originalChar == 0)
                        {
                            done = true;
                            break;
                        }
                        if (char.IsDigit(originalChar))
                        {
                            outputString.Append(originalChar);
                            onOriginal++;
                            onFilter++;
                            onOutput++;
                        }
                        else
                        {
                            onOriginal++;
                        }
                        break;
                    default:
                        // Any other character will automatically be inserted for the user as they type (spaces, - etc..) or deleted as they delete if there are more numbers to come.
                        outputString.Append(filterChar);
                        onOutput++;
                        onFilter++;
                        if (originalChar == filterChar)
                            onOriginal++;
                        break;
                }
            }
            return outputString.ToString();
        }

19 Source : PhoneFormatter.cs
with Apache License 2.0
from AppRopio

public string FilteredPhoneString(string str)
        {
            int onOriginal = 0, onFilter = 0, onOutput = 0;
            var outputString = new StringBuilder();
            bool done = false;

            while (onFilter < FILTER.Length && !done)
            {
                var filterChar = FILTER[onFilter];
                var originalChar = onOriginal >= str.Length ? (char)0 : str[onOriginal];
                switch (filterChar)
                {
                    case '#':
                        if (originalChar == 0)
                        {
                            done = true;
                            break;
                        }
                        if (char.IsDigit(originalChar))
                        {
                            outputString.Append(originalChar);
                            onOriginal++;
                            onFilter++;
                            onOutput++;
                        }
                        else
                        {
                            onOriginal++;
                        }
                        break;
                    default:
                        // Any other character will automatically be inserted for the user as they type (spaces, - etc..) or deleted as they delete if there are more numbers to come.
                        outputString.Append(filterChar);
                        onOutput++;
                        onFilter++;
                        if (originalChar == filterChar)
                            onOriginal++;
                        break;
                }
            }
            return outputString.ToString();
        }

See More Examples