GetStringAndRelease() public static method

public static GetStringAndRelease ( StringBuilder sb ) : string
sb StringBuilder
return string
コード例 #1
0
ファイル: KeyValuePair.cs プロジェクト: smartmaster/corert
        /// <summary>
        /// Used by KeyValuePair.ToString to reduce generic code
        /// </summary>
        internal static string PairToString(object key, object value)
        {
            StringBuilder s = StringBuilderCache.Acquire();

            s.Append('[');

            if (key != null)
            {
                s.Append(key);
            }

            s.Append(", ");

            if (value != null)
            {
                s.Append(value);
            }

            s.Append(']');

            return(StringBuilderCache.GetStringAndRelease(s));
        }
コード例 #2
0
    static string GetFileContentMD5(string file)
    {
        try
        {
            FileStream fs = new FileStream(file, FileMode.Open);
            System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            byte[] retVal = md5.ComputeHash(fs);
            fs.Close();

            StringBuilder sb = StringBuilderCache.Acquire();
            for (int i = 0; i < retVal.Length; i++)
            {
                sb.Append(retVal[i].ToString("x2"));
            }
            return(StringBuilderCache.GetStringAndRelease(sb));
        }
        catch (System.Exception ex)
        {
            Debugger.Log("Md5file() fail, error:" + ex.Message);
            return(string.Empty);
        }
    }
コード例 #3
0
        /// <summary>
        /// Datadog tag requirements:
        /// 1. Tag must start with a letter
        /// 2. Tag cannot exceed 200 characters
        /// 3. If the first two requirements are met, then valid characters will be retained while all other characters will be converted to underscores. Valid characters include:
        ///    - Alphanumerics
        ///    - Underscores
        ///    - Minuses
        ///    - Colons
        ///    - Slashes
        ///
        /// 4. Optionally, periods can be replaced by underscores.
        /// Note: This method will trim leading/trailing whitespace before checking the requirements.
        /// </summary>
        /// <param name="value">Input string to convert into tag name</param>
        /// <param name="normalizePeriods">True if we replace dots by underscores</param>
        /// <param name="normalizedTagName">If the method returns true, the normalized tag name</param>
        /// <returns>Returns whether the conversion was successful</returns>
        public static bool TryConvertToNormalizedTagName(this string value, bool normalizePeriods, out string normalizedTagName)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                normalizedTagName = null;
                return(false);
            }

            var trimmedValue = value.Trim();

            if (!char.IsLetter(trimmedValue[0]) || trimmedValue.Length > 200)
            {
                normalizedTagName = null;
                return(false);
            }

            var sb = StringBuilderCache.Acquire(trimmedValue.Length);

            sb.Append(trimmedValue.ToLowerInvariant());

            for (var x = 0; x < sb.Length; x++)
            {
                switch (sb[x])
                {
                case (>= 'a' and <= 'z')or(>= '0' and <= '9') or '_' or ':' or '/' or '-':
                    continue;

                case '.' when !normalizePeriods:
                    continue;

                default:
                    sb[x] = '_';
                    break;
                }
            }

            normalizedTagName = StringBuilderCache.GetStringAndRelease(sb);
            return(true);
        }
コード例 #4
0
ファイル: JsonWriter.cs プロジェクト: wangdi2014/Nirvana
        public void WriteAnnotatedGenes(IEnumerable <string> annotatedGenes)
        {
            _positionFieldClosed = true;
            _writer.Flush();
            _jasixIndexCreator?.EndSection(JasixCommons.PositionsSectionTag, _bgzipTextWriter.Position - 1);

            _writer.Write("\n]");

            if (annotatedGenes == null)
            {
                return;
            }
            _writer.Write($",\"{JasixCommons.GenesSectionTag}\":[\n");
            _writer.Flush();

            _jasixIndexCreator?.BeginSection(JasixCommons.GenesSectionTag, _bgzipTextWriter.Position);

            var sb             = StringBuilderCache.Acquire();
            var firstGeneEntry = true;

            foreach (string jsonString in annotatedGenes)
            {
                if (!firstGeneEntry)
                {
                    sb.Append(",\n");
                }
                sb.Append(jsonString);
                firstGeneEntry = false;
            }

            _writer.Write(sb.ToString());
            _writer.Flush();
            _jasixIndexCreator?.EndSection(JasixCommons.GenesSectionTag, _bgzipTextWriter.Position - 1);

            StringBuilderCache.GetStringAndRelease(sb);
            _writer.WriteLine();
            _writer.Write("]");
        }
コード例 #5
0
        private static bool GetCalendarInfo(string localeName, CalendarId calendarId, CalendarDataType dataType, out string calendarString)
        {
            calendarString = null;

            const int initialStringSize = 80;
            const int maxDoubleAttempts = 5;

            for (int i = 0; i < maxDoubleAttempts; i++)
            {
                StringBuilder stringBuilder = StringBuilderCache.Acquire((int)(initialStringSize * Math.Pow(2, i)));

                CalendarDataResult result = Interop.GlobalizationInterop.GetCalendarInfo(
                    localeName,
                    calendarId,
                    dataType,
                    stringBuilder,
                    stringBuilder.Capacity);

                if (result == CalendarDataResult.Success)
                {
                    calendarString = StringBuilderCache.GetStringAndRelease(stringBuilder);
                    return(true);
                }
                else
                {
                    StringBuilderCache.Release(stringBuilder);

                    if (result != CalendarDataResult.InsufficentBuffer)
                    {
                        return(false);
                    }

                    // else, it is an InsufficentBuffer error, so loop and increase the string size
                }
            }

            return(false);
        }
コード例 #6
0
        public bool TryParse(TextReader stream, [NotNullWhen(true)] out JsonValue?value, [NotNullWhen(false)] out string?errorMessage)
        {
            value = null;

            var buffer = StringBuilderCache.Acquire();

            while (stream.Peek() != -1)
            {
                var c = (char)stream.Peek();
                if (char.IsWhiteSpace(c) || c == ',' || c == ']' || c == '}')
                {
                    break;
                }

                stream.Read();                 // eat the character

                if (!_IsNumberChar(c))
                {
                    StringBuilderCache.Release(buffer);
                    errorMessage = "Expected ',', ']', or '}'.";
                    return(false);
                }

                buffer.Append(c);
            }

            var result = StringBuilderCache.GetStringAndRelease(buffer);

            if (!double.TryParse(result, NumberStyles.Any, CultureInfo.InvariantCulture, out double dbl))
            {
                errorMessage = $"Value not recognized: '{result}'";
                return(false);
            }

            value        = dbl;
            errorMessage = null;
            return(true);
        }
コード例 #7
0
ファイル: XMLUtil.cs プロジェクト: lodejard/AllNetCore
        public static String BitFieldEnumToString(Type type, Object value)
        {
            int iValue = (int)value;

            if (iValue == 0)
            {
                return(Enum.GetName(type, 0));
            }

            StringBuilder result = StringBuilderCache.Acquire();
            bool          first  = true;
            int           flag   = 0x1;

            for (int i = 1; i < 32; ++i)
            {
                if ((flag & iValue) != 0)
                {
                    String sFlag = Enum.GetName(type, flag);

                    if (sFlag == null)
                    {
                        continue;
                    }

                    if (!first)
                    {
                        result.Append(", ");
                    }

                    result.Append(sFlag);
                    first = false;
                }

                flag = flag << 1;
            }

            return(StringBuilderCache.GetStringAndRelease(result));
        }
コード例 #8
0
            private unsafe string GetNextKey(ref char *p)
            {
                // It is generally cheaper to change a local and then write back to ref at the end
                // rather than updating the ref on each operation.
                char *temp = p;

                StringBuilder sb = StringBuilderCache.Acquire();

                // Skip leading whitespace
                while (*temp == ' ')
                {
                    temp++;
                }

                // Start parsing key
                while (*temp != '=')
                {
                    // Key cannot have whitespace
                    if (*temp == ' ')
                    {
                        break;
                    }

                    sb.Append(*temp);
                    temp++;
                }

                // Skip trailing whitespace and '='
                while (*temp == ' ' || *temp == '=')
                {
                    temp++;
                }

                // Set the ref p to temp
                p = temp;

                return(StringBuilderCache.GetStringAndRelease(sb));
            }
コード例 #9
0
        private static void DrawDownloadTaskInfo(DownloadTaskInfo downloadTaskInfo)
        {
            EditorGUI.indentLevel++;
            EditorGUILayout.BeginVertical();
            {
                var sb = StringBuilderCache.Acquire();
                sb.AppendLine("URL: " + downloadTaskInfo.UrlStr);
                sb.AppendLine("Save Path: " + downloadTaskInfo.SavePath);
                if (downloadTaskInfo.Size > 0L)
                {
                    sb.AppendFormat("Size: {0:N0}\n", downloadTaskInfo.Size);
                }

                if (downloadTaskInfo.Crc32 != null)
                {
                    sb.AppendFormat("CRC 32: {0}\n", downloadTaskInfo.Crc32.Value);
                }

                EditorGUILayout.LabelField(StringBuilderCache.GetStringAndRelease(sb), EditorStyles.wordWrappedLabel);
            }
            EditorGUILayout.EndVertical();
            EditorGUI.indentLevel--;
        }
コード例 #10
0
        public void When_acquiring_multiple_instances()
        {
            var builderOne = StringBuilderCache.Acquire();
            var builderTwo = StringBuilderCache.Acquire();

            builderOne.ShouldNotBeSameAs(builderTwo);

            builderOne.Append("Hello");

            var builderOneStr = StringBuilderCache.GetStringAndRelease(builderOne);

            builderOneStr.ShouldBe("Hello");

            var builderThree = StringBuilderCache.Acquire();

            builderThree.ShouldBeSameAs(builderOne);

            var builderTwoStr = StringBuilderCache.GetStringAndRelease(builderTwo);

            builderTwoStr.ShouldBeEmpty();

            builderThree.ShouldNotBeSameAs(builderTwo);
        }
コード例 #11
0
    public override string FindFileError(string fileName)
    {
        if (Path.IsPathRooted(fileName))
        {
            return(fileName);
        }

        StringBuilder sb = StringBuilderCache.Acquire();

        if (Path.GetExtension(fileName) == ".lua")
        {
            fileName = fileName.Substring(0, fileName.Length - 4);
        }

        sb.AppendFormat("\n\tno file '{0}'", LuaConst.luaResDir);

        sb.AppendFormat("\n\tno file ./Resources/?.lua");
        sb = sb.Replace("?", fileName);

        sb.AppendFormat("\n\t" + base.FindFileError(fileName));

        return(StringBuilderCache.GetStringAndRelease(sb));
    }
コード例 #12
0
        protected string ReadLine()
        {
            var sb = StringBuilderCache.Acquire();

            int c;

            while ((c = this.BStream.ReadByte()) != -1)
            {
                if (c == '\r')
                {
                    continue;
                }

                if (c == '\n')
                {
                    break;
                }

                sb.Append((char)c);
            }

            return(StringBuilderCache.GetStringAndRelease(sb));
        }
コード例 #13
0
ファイル: LuaResLoader.cs プロジェクト: hw233/Poker
    public override string FindFileError(string fileName)
    {
        if (Path.IsPathRooted(fileName))
        {
            return(fileName);
        }

        StringBuilder sb = StringBuilderCache.Acquire();

        if (Path.GetExtension(fileName) == ".lua")
        {
            fileName = fileName.Substring(0, fileName.Length - 4);
        }

        for (int i = 0; i < searchPaths.Count; i++)
        {
            sb.AppendFormat("\n\tno file '{0}'", searchPaths[i]);
        }

        sb.AppendFormat("\n\tno file ./Resources/?.lua");
        sb = sb.Replace("?", fileName);
        return(StringBuilderCache.GetStringAndRelease(sb));
    }
コード例 #14
0
ファイル: SaTsvWriter.cs プロジェクト: zhouhufeng/Nirvana
        private static string GetHeader(DataSourceVersion dataSourceVersion, int schemaVersion, string assembly, string jsonKey, string vcfKeys, bool matchByAllele, bool isArray)
        {
            var sb = StringBuilderCache.Acquire();

            sb.Append($"#name={dataSourceVersion.Name}\n");
            if (!string.IsNullOrEmpty(assembly))
            {
                sb.Append($"#assembly={assembly}\n");
            }
            sb.Append($"#version={dataSourceVersion.Version}\n");
            sb.Append($"#description={dataSourceVersion.Description}\n");
            var releaseDate = new DateTime(dataSourceVersion.ReleaseDateTicks, DateTimeKind.Utc);

            sb.Append($"#releaseDate={releaseDate:yyyy-MM-dd}\n");
            sb.Append($"#dataVersion={schemaVersion}\n");
            sb.Append($"#schemaVersion={SaTsvCommon.SupplementarySchemaVersion}\n");
            sb.Append($"#matchByAllele={matchByAllele}\n");
            sb.Append($"#isArray={isArray}\n");
            sb.Append($"#jsonKey={jsonKey}\n");
            sb.Append($"#vcfKeys={vcfKeys}\n");
            sb.Append("#CHROM\tPOS\tREF\tALT\tVCF\tJSON\n");
            return(StringBuilderCache.GetStringAndRelease(sb));
        }
コード例 #15
0
        internal String NormalizeUrl()
        {
            DoDeferredParse();
            StringBuilder builtUrl = StringBuilderCache.Acquire();

            if (String.Compare(m_protocol, "file", StringComparison.OrdinalIgnoreCase) == 0)
            {
                builtUrl = builtUrl.AppendFormat("FILE:///{0}/{1}", m_localSite.ToString(), m_directory.ToString());
            }
            else
            {
                builtUrl = builtUrl.AppendFormat("{0}://{1}{2}", m_protocol, m_userpass, m_siteString.ToString());

                if (m_port != -1)
                {
                    builtUrl = builtUrl.AppendFormat("{0}", m_port);
                }

                builtUrl = builtUrl.AppendFormat("/{0}", m_directory.ToString());
            }

            return(StringBuilderCache.GetStringAndRelease(builtUrl).ToUpper(CultureInfo.InvariantCulture));
        }
コード例 #16
0
        public void ReadDataVersionFromFile()
        {
            var versionFile = ResourceUtilities.GetReadStream(Resources.TopPath("dbSNP.version"));

            DataSourceVersion version;

            using (var reader = new DataSourceVersionReader(versionFile))
            {
                version = reader.GetVersion();
            }

            Assert.Equal("dbSNP", version.Name);
            Assert.Equal("147", version.Version);
            Assert.Equal(DateTime.Parse("2016-04-08").Ticks, version.ReleaseDateTicks);
            Assert.True(string.IsNullOrEmpty(version.Description));
            Assert.Contains("dataSource=dbSNP", version.ToString());            //vcf output

            var sb = StringBuilderCache.Acquire();

            version.SerializeJson(sb);

            Assert.Contains("name\":\"dbSNP", StringBuilderCache.GetStringAndRelease(sb));            //json output
        }
コード例 #17
0
        public string TryParse(TextReader stream, out JsonValue value)
        {
            value = null;

            var buffer      = StringBuilderCache.Acquire();
            var bufferIndex = 0;

            while (stream.Peek() != -1)
            {
                var c = (char)stream.Peek();
                if (char.IsWhiteSpace(c) || c == ',' || c == ']' || c == '}')
                {
                    break;
                }

                stream.Read();                 // eat the character

                if (!_IsNumberChar(c))
                {
                    StringBuilderCache.Release(buffer);
                    return("Expected ',', ']', or '}'.");
                }

                buffer.Append(c);
                bufferIndex++;
            }

            var result = StringBuilderCache.GetStringAndRelease(buffer);

            if (!double.TryParse(result, NumberStyles.Any, CultureInfo.InvariantCulture, out double dbl))
            {
                return($"Value not recognized: '{result}'");
            }

            value = dbl;
            return(null);
        }
コード例 #18
0
        // Encode a string using RFC 5987 encoding.
        // encoding'lang'PercentEncodedSpecials
        internal static string Encode5987(string input)
        {
            // Encode a string using RFC 5987 encoding.
            // encoding'lang'PercentEncodedSpecials
            StringBuilder builder = StringBuilderCache.Acquire();

            byte[] utf8bytes = ArrayPool <byte> .Shared.Rent(Encoding.UTF8.GetMaxByteCount(input.Length));

            int utf8length = Encoding.UTF8.GetBytes(input, 0, input.Length, utf8bytes, 0);

            builder.Append("utf-8\'\'");
            for (int i = 0; i < utf8length; i++)
            {
                byte utf8byte = utf8bytes[i];

                // attr-char = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
                //      ; token except ( "*" / "'" / "%" )
                if (utf8byte > 0x7F) // Encodes as multiple utf-8 bytes
                {
                    AddHexEscaped(utf8byte, builder);
                }
                else if (!HttpRuleParser.IsTokenChar((char)utf8byte) || utf8byte == '*' || utf8byte == '\'' || utf8byte == '%')
                {
                    // ASCII - Only one encoded byte.
                    AddHexEscaped(utf8byte, builder);
                }
                else
                {
                    builder.Append((char)utf8byte);
                }
            }

            Array.Clear(utf8bytes, 0, utf8length);
            ArrayPool <byte> .Shared.Return(utf8bytes);

            return(StringBuilderCache.GetStringAndRelease(builder));
        }
コード例 #19
0
    /// <summary>
    /// Helper for making interop calls that return a string, but we don't know
    /// the correct size of buffer to make. So invoke the interop call with an
    /// increasing buffer until the size is big enough.
    /// </summary>
    internal static bool CallStringMethod <TArg1, TArg2, TArg3>(
        Func <TArg1, TArg2, TArg3, StringBuilder, GlobalizationInterop.ResultCode> interopCall,
        TArg1 arg1,
        TArg2 arg2,
        TArg3 arg3,
        out string result)
    {
        const int initialStringSize = 80;
        const int maxDoubleAttempts = 5;

        StringBuilder stringBuilder = StringBuilderCache.Acquire(initialStringSize);

        for (int i = 0; i < maxDoubleAttempts; i++)
        {
            GlobalizationInterop.ResultCode resultCode = interopCall(arg1, arg2, arg3, stringBuilder);

            if (resultCode == GlobalizationInterop.ResultCode.Success)
            {
                result = StringBuilderCache.GetStringAndRelease(stringBuilder);
                return(true);
            }
            else if (resultCode == GlobalizationInterop.ResultCode.InsufficentBuffer)
            {
                // increase the string size and loop
                stringBuilder.EnsureCapacity(stringBuilder.Capacity * 2);
            }
            else
            {
                // if there is an unknown error, don't proceed
                break;
            }
        }

        StringBuilderCache.Release(stringBuilder);
        result = null;
        return(false);
    }
コード例 #20
0
        internal static bool IsInputEncoded5987(string input, out string output)
        {
            // Encode a string using RFC 5987 encoding.
            // encoding'lang'PercentEncodedSpecials
            bool          wasEncoded = false;
            StringBuilder builder    = StringBuilderCache.Acquire();

            builder.Append("utf-8\'\'");
            foreach (char c in input)
            {
                // attr-char = ALPHA / DIGIT / "!" / "#" / "$" / "&" / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~"
                //      ; token except ( "*" / "'" / "%" )
                if (c > 0x7F) // Encodes as multiple utf-8 bytes
                {
                    byte[] bytes = Encoding.UTF8.GetBytes(c.ToString());
                    foreach (byte b in bytes)
                    {
                        AddHexEscaped((char)b, builder);
                        wasEncoded = true;
                    }
                }
                else if (!IsTokenChar(c) || c == '*' || c == '\'' || c == '%')
                {
                    // ASCII - Only one encoded byte.
                    AddHexEscaped(c, builder);
                    wasEncoded = true;
                }
                else
                {
                    builder.Append(c);
                }
            }

            output = StringBuilderCache.GetStringAndRelease(builder);
            return(wasEncoded);
        }
コード例 #21
0
        private static string ComputeHash(string data, string algorithm)
        {
            // Disable MD5 insecure warning.
#pragma warning disable CA5351
            using (HashAlgorithm hash = algorithm == Sha256 ? SHA256.Create() : (HashAlgorithm)MD5.Create())
#pragma warning restore CA5351
            {
                Span <byte> result       = stackalloc byte[hash.HashSize / 8]; // HashSize is in bits
                bool        hashComputed = hash.TryComputeHash(Encoding.UTF8.GetBytes(data), result, out int bytesWritten);
                Debug.Assert(hashComputed && bytesWritten == result.Length);

                StringBuilder sb = StringBuilderCache.Acquire(result.Length * 2);

                Span <char> byteX2 = stackalloc char[2];
                for (int i = 0; i < result.Length; i++)
                {
                    bool formatted = result[i].TryFormat(byteX2, out int charsWritten, "x2");
                    Debug.Assert(formatted && charsWritten == 2);
                    sb.Append(byteX2);
                }

                return(StringBuilderCache.GetStringAndRelease(sb));
            }
        }
コード例 #22
0
ファイル: JsonWriter.cs プロジェクト: zhouhufeng/Nirvana
        private void WriteHeader(string annotator, string creationTime, string genomeAssembly, int schemaVersion,
                                 string vepDataVersion, List <IDataSourceVersion> dataSourceVersions, string[] sampleNames)
        {
            var sb         = StringBuilderCache.Acquire();
            var jsonObject = new JsonObject(sb);

            sb.Append("{\"header\":{");
            jsonObject.AddStringValue("annotator", annotator);
            jsonObject.AddStringValue("creationTime", creationTime);
            jsonObject.AddStringValue("genomeAssembly", genomeAssembly);
            jsonObject.AddIntValue("schemaVersion", schemaVersion);
            jsonObject.AddStringValue("dataVersion", vepDataVersion);

            jsonObject.AddObjectValues("dataSources", dataSourceVersions);

            if (sampleNames != null)
            {
                jsonObject.AddStringValues("samples", sampleNames);
            }
            sb.Append("},\"positions\":[\n");

            Header = StringBuilderCache.GetStringAndRelease(sb);
            _writer.Write(Header);
        }
コード例 #23
0
    public static string Query(int batchSize)
    {
        if (_queries[batchSize] != null)
        {
            return(_queries[batchSize]);
        }

        var lastIndex = batchSize - 1;

        var sb = StringBuilderCache.Acquire();

        if (DatabaseServer == DatabaseServer.PostgreSql)
        {
            sb.Append("UPDATE world SET randomNumber = temp.randomNumber FROM (VALUES ");
            Enumerable.Range(0, lastIndex).ToList().ForEach(i => sb.Append($"(@Id_{i}, @Random_{i}), "));
            sb.Append($"(@Id_{lastIndex}, @Random_{lastIndex}) ORDER BY 1) AS temp(id, randomNumber) WHERE temp.id = world.id");
        }
        else
        {
            Enumerable.Range(0, batchSize).ToList().ForEach(i => sb.Append($"UPDATE world SET randomnumber = @Random_{i} WHERE id = @Id_{i};"));
        }

        return(_queries[batchSize] = StringBuilderCache.GetStringAndRelease(sb));
    }
コード例 #24
0
        private static string GetRandomAlphaNumericString()
        {
            const int   Length = 16;
            Span <byte> randomNumbers;

            unsafe
            {
                byte *ptr = stackalloc byte[Length * 2];
                randomNumbers = new Span <byte>(ptr, Length * 2);
            }
            s_rng.GetBytes(randomNumbers);

            StringBuilder sb = StringBuilderCache.Acquire(Length);

            for (int i = 0; i < randomNumbers.Length;)
            {
                // Get a random digit 0-9, a random alphabet in a-z, or a random alphabeta in A-Z
                int rangeIndex = randomNumbers[i++] % 3;
                int value      = randomNumbers[i++] % (rangeIndex == 0 ? 10 : 26);
                sb.Append((char)(s_alphaNumChooser[rangeIndex] + value));
            }

            return(StringBuilderCache.GetStringAndRelease(sb));
        }
コード例 #25
0
    public static Task RenderFortunesHtml(IEnumerable <Fortune> model, HttpContext httpContext, HtmlEncoder htmlEncoder)
    {
        httpContext.Response.StatusCode  = StatusCodes.Status200OK;
        httpContext.Response.ContentType = "text/html; charset=UTF-8";

        var sb = StringBuilderCache.Acquire();

        sb.Append("<!DOCTYPE html><html><head><title>Fortunes</title></head><body><table><tr><th>id</th><th>message</th></tr>");
        foreach (var item in model)
        {
            sb.Append("<tr><td>");
            sb.Append(item.Id.ToString(CultureInfo.InvariantCulture));
            sb.Append("</td><td>");
            sb.Append(htmlEncoder.Encode(item.Message));
            sb.Append("</td></tr>");
        }

        sb.Append("</table></body></html>");
        var response = StringBuilderCache.GetStringAndRelease(sb);

        // fortunes includes multibyte characters so response.Length is incorrect
        httpContext.Response.ContentLength = Encoding.UTF8.GetByteCount(response);
        return(httpContext.Response.WriteAsync(response));
    }
コード例 #26
0
            public override string ToString()
            {
                var sb = StringBuilderCache.Acquire();

                sb.Append('[');
                if (LowerBound != Evaluation.MinScore)
                {
                    sb.Append(LowerBound);
                }
                sb.Append(", ");
                if (UpperBound != Evaluation.MaxScore)
                {
                    sb.Append(UpperBound);
                }
                sb.Append("], ");
                sb.Append(nameof(Depth));
                sb.Append(" = ");
                sb.Append(Depth);
                sb.Append(", ");
                sb.Append(nameof(PvMove));
                sb.Append(" = ");
                sb.Append(PvMove.ToString());
                return(StringBuilderCache.GetStringAndRelease(sb));
            }
コード例 #27
0
        public void When_Scenario2()
        {
            int loop = 100000;

            Benchmark.Initialize();

            Benchmark.Run(i =>
            {
                StringBuilder sb = new StringBuilder();

                for (int j = 0; j < 1; j++)
                {
                    sb.Append(DateTime.Now.ToLongDateString());
                    sb.Append(DateTime.Now.ToLongTimeString());
                    sb.AppendLine(j.ToString());
                }

                string result = sb.ToString();
            }, "StringBuilder", loop);

            Benchmark.Initialize();

            Benchmark.Run(i =>
            {
                StringBuilder SUT = StringBuilderCache.Acquire();

                for (int j = 0; j < 1; j++)
                {
                    SUT.Append(DateTime.Now.ToLongDateString());
                    SUT.Append(DateTime.Now.ToLongTimeString());
                    SUT.AppendLine(j.ToString());
                }

                string result = StringBuilderCache.GetStringAndRelease(SUT);
            }, "StringBuilderCache", loop);
        }
コード例 #28
0
        public static string GetJsonString(this ISample sample)
        {
            var sb         = StringBuilderCache.Acquire();
            var jsonObject = new JsonObject(sb);

            // data section
            sb.Append(JsonObject.OpenBrace);

            jsonObject.AddBoolValue("isEmpty", sample.IsEmpty);
            jsonObject.AddStringValue("genotype", sample.Genotype);
            jsonObject.AddDoubleValues("variantFrequencies", sample.VariantFrequencies);
            jsonObject.AddIntValue("totalDepth", sample.TotalDepth);
            jsonObject.AddIntValue("genotypeQuality", sample.GenotypeQuality);
            jsonObject.AddIntValue("copyNumber", sample.CopyNumber);
            jsonObject.AddIntValue("minorHaplotypeCopyNumber", sample.MinorHaplotypeCopyNumber);
            jsonObject.AddIntValues("repeatUnitCounts", sample.RepeatUnitCounts);
            jsonObject.AddIntValues("alleleDepths", sample.AlleleDepths);
            jsonObject.AddBoolValue("failedFilter", sample.FailedFilter);
            jsonObject.AddIntValues("splitReadCounts", sample.SplitReadCounts);
            jsonObject.AddIntValues("pairedEndReadCounts", sample.PairedEndReadCounts);
            jsonObject.AddBoolValue("isDeNovo", sample.IsDeNovo);
            jsonObject.AddDoubleValue("deNovoQuality", sample.DeNovoQuality);
            jsonObject.AddStringValues("diseaseAffectedStatuses", sample.DiseaseAffectedStatuses);
            jsonObject.AddDoubleValue("artifactAdjustedQualityScore", sample.ArtifactAdjustedQualityScore, "0.#");
            jsonObject.AddDoubleValue("likelihoodRatioQualityScore", sample.LikelihoodRatioQualityScore, "0.#");
            if (sample.IsLossOfHeterozygosity.HasValue)
            {
                jsonObject.AddBoolValue("lossOfHeterozygosity", sample.IsLossOfHeterozygosity.Value);
            }
            jsonObject.AddDoubleValue("somaticQuality", sample.SomaticQuality, "0.#");
            jsonObject.AddStringValues("heteroplasmyPercentile", sample.HeteroplasmyPercentile, false);
            jsonObject.AddIntValue("binCount", sample.BinCount);

            sb.Append(JsonObject.CloseBrace);
            return(StringBuilderCache.GetStringAndRelease(sb));
        }
コード例 #29
0
ファイル: CultureData.Unix.cs プロジェクト: rinack/coreclr
        private static string ConvertIcuTimeFormatString(string icuFormatString)
        {
            StringBuilder sb        = StringBuilderCache.Acquire(ICU_ULOC_FULLNAME_CAPACITY);
            bool          amPmAdded = false;

            for (int i = 0; i < icuFormatString.Length; i++)
            {
                switch (icuFormatString[i])
                {
                case ':':
                case '.':
                case 'H':
                case 'h':
                case 'm':
                case 's':
                    sb.Append(icuFormatString[i]);
                    break;

                case ' ':
                case '\u00A0':
                    // Convert nonbreaking spaces into regular spaces
                    sb.Append(' ');
                    break;

                case 'a':     // AM/PM
                    if (!amPmAdded)
                    {
                        amPmAdded = true;
                        sb.Append("tt");
                    }
                    break;
                }
            }

            return(StringBuilderCache.GetStringAndRelease(sb));
        }
コード例 #30
0
        public string GetJsonString()
        {
            var sb         = StringBuilderCache.Acquire();
            var jsonObject = new JsonObject(sb);

            jsonObject.AddStringValue("chromosome", Chromosome.EnsemblName);
            jsonObject.AddIntValue("begin", Start);
            jsonObject.AddIntValue("end", End);
            jsonObject.AddStringValue("variantType", VariantType.ToString());

            jsonObject.AddStringValue("id", Id);
            jsonObject.AddIntValue("sampleSize", SampleSize);
            if (ObservedGains != 0)
            {
                jsonObject.AddIntValue("observedGains", ObservedGains);
            }
            if (ObservedLosses != 0)
            {
                jsonObject.AddIntValue("observedLosses", ObservedLosses);
            }
            jsonObject.AddDoubleValue("variantFreqAll", VariantFreqAll, "0.#####");

            return(StringBuilderCache.GetStringAndRelease(sb));
        }