Autor
|
Tema: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets) (Leído 526,937 veces)
|
Elektro Enjuto
|
Un código para calcular la entropía de un String, basado en la fórmula de Shannon: https://en.wikipedia.org/wiki/Entropy_(information_theory)' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' CalculateStringEntropy(String) As Double #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Calculates the entropy of a string based on the Shannon's entropy formula. ''' <para></para> ''' The entropy is a measure of the amount of uncertainty or randomness in a set of characters. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <seealso href="https://en.wikipedia.org/wiki/Entropy_(information_theory)"/> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="str"> ''' The input string. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' A number representing the entropy value of the input string. ''' <para></para> ''' A higher entropy value indicates that the text contains more randomness or unpredictability, ''' while a lower entropy value indicates that the text is more structured or predictable. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' To calculate the entropy of the given text, the algorithm first counts the frequency of each character in the text. ''' It then uses these frequencies to calculate the probability of each character appearing in the text. ''' Once the probability of each character is known, the algorithm applies Shannon's entropy formula, ''' which looks like this: H = -Σp(x)log2p(x), where H is the entropy, p(x) is the probability that ''' character x will appear in the text, and log2 is the base 2 logarithm. ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function CalculateStringEntropy(str As String) As Double For Each c As Char In str If Not map.ContainsKey(c) Then map.Add(c, 1) Else map(c) += 1 End If Next c Dim result As Double = 0.0 Dim len As Integer = str.Length For Each item As KeyValuePair(Of Char, Integer) In map Dim frequency As Double = item.Value / len result -= frequency * (System.Math.Log(frequency) / System.Math.Log(2)) Next item Return result End Function #End Region End Class End Namespace #End Region
|
|
|
En línea
|
@%$& #$ %&#$, ¡hay que decirlo más!.
|
|
|
Elektro Enjuto
|
Un código para convertir el texto de un String a sets de caracteres Unicode. Nota: como resultará evidente, no es posible añadir soporte para los caracteres que carecen de un equivalente. UnicodeCharacterMaps.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Option Statements " Option Strict Off Option Explicit On Option Infer Off #End Region #Region " Public Members Summary " #Region " Properties " ' MathematicalBold As Dictionary(Of Char, String) ' MathematicalBoldItalic As Dictionary(Of Char, String) ' MathematicalBoldScript As Dictionary(Of Char, String) ' MathematicalItalic As Dictionary(Of Char, String) ' MonoSpace As Dictionary(Of Char, String) ' SansSerif As Dictionary(Of Char, String) ' SansSerifBold As Dictionary(Of Char, String) ' SansSerifBoldItalic As Dictionary(Of Char, String) ' SansSerifItalic As Dictionary(Of Char, String) #End Region #End Region #Region " Imports " Imports System.Collections.Generic #End Region #Region " UnicodeCharacterMaps " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Provides access to predefined alphabetic and alphanumeric character maps for a range of Unicode character sets. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' The Unicode character sets are standardized sets of characters that cover ''' various scripts and symbols used in written languages worldwide. ''' <para></para> ''' Unicode provides a unique code point for each character, ensuring interoperability and ''' compatibility across different platforms and systems. ''' <para></para> ''' The character sets defined in this class represent specific stylistic variations ''' of alphabetic characters used in mathematics and typography. ''' <para></para> ''' These character sets are commonly used in scientific and mathematical contexts, ''' as well as in typography and font design. ''' <para></para> ''' They allow for precise representation of stylized alphabetic characters ''' in various mathematical equations, formulas, and text layouts. ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- Public Class UnicodeCharacterMaps #Region " Private Fields " ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Mathematical Bold' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D400 to U+1D433). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝐀', and dictionary key: 'a' gets value: '𝐚'. ''' </summary> Private Shared _mathematicalBold As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Mathematical Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D434 to U+1D467). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝐴', and dictionary key: 'a' gets value: '𝑎'. ''' </summary> Private Shared _mathematicalItalic As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Mathematical Bold Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D468 to U+1D49B). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝑨', and dictionary key: 'a' gets value: '𝒂'. ''' </summary> Private Shared _mathematicalBoldItalic As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Mathematical Bold Script' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D4D0 to U+1D503). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝓐', and dictionary key: 'a' gets value: '𝓪'. ''' </summary> Private Shared _mathematicalBoldScript As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Sans-Serif' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5A0 to U+1D5D3). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝖠', and dictionary key: 'a' gets value: '𝖺'. ''' </summary> Private Shared _sansSerif As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Sans-Serif Bold' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5D4 to U+1D607). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝗔', and dictionary key: 'a' gets value: '𝗮'. ''' </summary> Private Shared _sansSerifBold As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Sans-Serif Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D608 to U+1D63B). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝘈', and dictionary key: 'a' gets value: '𝘢'. ''' </summary> Private Shared _sansSerifItalic As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Sans-Serif Bold Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D63C to U+1D66F). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝘼', and dictionary key: 'a' gets value: '𝙖'. ''' </summary> Private Shared _sansSerifBoldItalic As Dictionary(Of Char, String) ''' <summary> ''' (Backing Field) ''' <para></para> ''' A dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Monospace' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D670 to U+1D6A3). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝙰', and dictionary key: 'a' gets value: '𝚊'. ''' </summary> Private Shared _monoSpace As Dictionary(Of Char, String) #End Region #Region " Properties " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Mathematical Bold' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D400 to U+1D433). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝐀', and dictionary key: 'a' gets value: '𝐚'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property MathematicalBold As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._mathematicalBold Is Nothing Then UnicodeCharacterMaps._mathematicalBold = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝐀"}, {"B"c, "𝐁"}, {"C"c, "𝐂"}, {"D"c, "𝐃"}, {"E"c, "𝐄"}, {"F"c, "𝐅"}, {"G"c, "𝐆"}, {"H"c, "𝐇"}, {"I"c, "𝐈"}, {"J"c, "𝐉"}, {"K"c, "𝐊"}, {"L"c, "𝐋"}, {"M"c, "𝐌"}, {"N"c, "𝐍"}, {"O"c, "𝐎"}, {"P"c, "𝐏"}, {"Q"c, "𝐐"}, {"R"c, "𝐑"}, {"S"c, "𝐒"}, {"T"c, "𝐓"}, {"U"c, "𝐔"}, {"V"c, "𝐕"}, {"W"c, "𝐖"}, {"X"c, "𝐗"}, {"Y"c, "𝐘"}, {"Z"c, "𝐙"}, {"a"c, "𝐚"}, {"b"c, "𝐛"}, {"c"c, "𝐜"}, {"d"c, "𝐝"}, {"e"c, "𝐞"}, {"f"c, "𝐟"}, {"g"c, "𝐠"}, {"h"c, "𝐡"}, {"i"c, "𝐢"}, {"j"c, "𝐣"}, {"k"c, "𝐤"}, {"l"c, "𝐥"}, {"m"c, "𝐦"}, {"n"c, "𝐧"}, {"o"c, "𝐨"}, {"p"c, "𝐩"}, {"q"c, "𝐪"}, {"r"c, "𝐫"}, {"s"c, "𝐬"}, {"t"c, "𝐭"}, {"u"c, "𝐮"}, {"v"c, "𝐯"}, {"w"c, "𝐰"}, {"x"c, "𝐱"}, {"y"c, "𝐲"}, {"z"c, "𝐳"}, {"0"c, "𝟎"}, {"1"c, "𝟏"}, {"2"c, "𝟐"}, {"3"c, "𝟑"}, {"4"c, "𝟒"}, {"5"c, "𝟓"}, {"6"c, "𝟔"}, {"7"c, "𝟕"}, {"8"c, "𝟖"}, {"9"c, "𝟗"} } End If Return UnicodeCharacterMaps._mathematicalBold End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Mathematical Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D434 to U+1D467). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝐴', and dictionary key: 'a' gets value: '𝑎'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property MathematicalItalic As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._mathematicalItalic Is Nothing Then UnicodeCharacterMaps._mathematicalItalic = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝐴"}, {"B"c, "𝐵"}, {"C"c, "𝐶"}, {"D"c, "𝐷"}, {"E"c, "𝐸"}, {"F"c, "𝐹"}, {"G"c, "𝐺"}, {"H"c, "𝐻"}, {"I"c, "𝐼"}, {"J"c, "𝐽"}, {"K"c, "𝐾"}, {"L"c, "𝐿"}, {"M"c, "𝑀"}, {"N"c, "𝑁"}, {"O"c, "𝑂"}, {"P"c, "𝑃"}, {"Q"c, "𝑄"}, {"R"c, "𝑅"}, {"S"c, "𝑆"}, {"T"c, "𝑇"}, {"U"c, "𝑈"}, {"V"c, "𝑉"}, {"W"c, "𝑊"}, {"X"c, "𝑋"}, {"Y"c, "𝑌"}, {"Z"c, "𝑍"}, {"a"c, "𝑎"}, {"b"c, "𝑏"}, {"c"c, "𝑐"}, {"d"c, "𝑑"}, {"e"c, "𝑒"}, {"f"c, "𝑓"}, {"g"c, "𝑔"}, {"h"c, "𝘩"}, {"i"c, "𝑖"}, {"j"c, "𝑗"}, {"k"c, "𝑘"}, {"l"c, "𝑙"}, {"m"c, "𝑚"}, {"n"c, "𝑛"}, {"o"c, "𝑜"}, {"p"c, "𝑝"}, {"q"c, "𝑞"}, {"r"c, "𝑟"}, {"s"c, "𝑠"}, {"t"c, "𝑡"}, {"u"c, "𝑢"}, {"v"c, "𝑣"}, {"w"c, "𝑤"}, {"x"c, "𝑥"}, {"y"c, "𝑦"}, {"z"c, "𝑧"} } End If Return UnicodeCharacterMaps._mathematicalItalic End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Mathematical Bold Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D468 to U+1D49B). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝑨', and dictionary key: 'a' gets value: '𝒂'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property MathematicalBoldItalic As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._mathematicalBoldItalic Is Nothing Then UnicodeCharacterMaps._mathematicalBoldItalic = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝑨"}, {"B"c, "𝑩"}, {"C"c, "𝑪"}, {"D"c, "𝑫"}, {"E"c, "𝑬"}, {"F"c, "𝑭"}, {"G"c, "𝑮"}, {"H"c, "𝑯"}, {"I"c, "𝑰"}, {"J"c, "𝑱"}, {"K"c, "𝑲"}, {"L"c, "𝑳"}, {"M"c, "𝑴"}, {"N"c, "𝑵"}, {"O"c, "𝑶"}, {"P"c, "𝑷"}, {"Q"c, "𝑸"}, {"R"c, "𝑹"}, {"S"c, "𝑺"}, {"T"c, "𝑻"}, {"U"c, "𝑼"}, {"V"c, "𝑽"}, {"W"c, "𝑾"}, {"X"c, "𝑿"}, {"Y"c, "𝒀"}, {"Z"c, "𝒁"}, {"a"c, "𝒂"}, {"b"c, "𝒃"}, {"c"c, "𝒄"}, {"d"c, "𝒅"}, {"e"c, "𝒆"}, {"f"c, "𝒇"}, {"g"c, "𝒈"}, {"h"c, "𝒉"}, {"i"c, "𝒊"}, {"j"c, "𝒋"}, {"k"c, "𝒌"}, {"l"c, "𝒍"}, {"m"c, "𝒎"}, {"n"c, "𝒏"}, {"o"c, "𝒐"}, {"p"c, "𝒑"}, {"q"c, "𝒒"}, {"r"c, "𝒓"}, {"s"c, "𝒔"}, {"t"c, "𝒕"}, {"u"c, "𝒖"}, {"v"c, "𝒗"}, {"w"c, "𝒘"}, {"x"c, "𝒙"}, {"y"c, "𝒚"}, {"z"c, "𝒛"} } End If Return UnicodeCharacterMaps._mathematicalBoldItalic End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Mathematical Bold Script' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D4D0 to U+1D503). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝓐', and dictionary key: 'a' gets value: '𝓪'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property MathematicalBoldScript As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._mathematicalBoldScript Is Nothing Then UnicodeCharacterMaps._mathematicalBoldScript = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝓐"}, {"B"c, "𝓑"}, {"C"c, "𝓒"}, {"D"c, "𝓓"}, {"E"c, "𝓔"}, {"F"c, "𝓕"}, {"G"c, "𝓖"}, {"H"c, "𝓗"}, {"I"c, "𝓘"}, {"J"c, "𝓙"}, {"K"c, "𝓚"}, {"L"c, "𝓛"}, {"M"c, "𝓜"}, {"N"c, "𝓝"}, {"O"c, "𝓞"}, {"P"c, "𝓟"}, {"Q"c, "𝓠"}, {"R"c, "𝓡"}, {"S"c, "𝓢"}, {"T"c, "𝓣"}, {"U"c, "𝓤"}, {"V"c, "𝓥"}, {"W"c, "𝓦"}, {"X"c, "𝓧"}, {"Y"c, "𝓨"}, {"Z"c, "𝓩"}, {"a"c, "𝓪"}, {"b"c, "𝓫"}, {"c"c, "𝓬"}, {"d"c, "𝓭"}, {"e"c, "𝓮"}, {"f"c, "𝓯"}, {"g"c, "𝓰"}, {"h"c, "𝓱"}, {"i"c, "𝓲"}, {"j"c, "𝓳"}, {"k"c, "𝓴"}, {"l"c, "𝓵"}, {"m"c, "𝓶"}, {"n"c, "𝓷"}, {"o"c, "𝓸"}, {"p"c, "𝓹"}, {"q"c, "𝓺"}, {"r"c, "𝓻"}, {"s"c, "𝓼"}, {"t"c, "𝓽"}, {"u"c, "𝓾"}, {"v"c, "𝓿"}, {"w"c, "𝔀"}, {"x"c, "𝔁"}, {"y"c, "𝔂"}, {"z"c, "𝔃"} } End If Return UnicodeCharacterMaps._mathematicalBoldScript End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Sans-Serif' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5A0 to U+1D5D3). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝖠', and dictionary key: 'a' gets value: '𝖺'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property SansSerif As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._sansSerif Is Nothing Then UnicodeCharacterMaps._sansSerif = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝖠"}, {"B"c, "𝖡"}, {"C"c, "𝖢"}, {"D"c, "𝖣"}, {"E"c, "𝖤"}, {"F"c, "𝖥"}, {"G"c, "𝖦"}, {"H"c, "𝖧"}, {"I"c, "𝖨"}, {"J"c, "𝖩"}, {"K"c, "𝖪"}, {"L"c, "𝖫"}, {"M"c, "𝖬"}, {"N"c, "𝖭"}, {"O"c, "𝖮"}, {"P"c, "𝖯"}, {"Q"c, "𝖰"}, {"R"c, "𝖱"}, {"S"c, "𝖲"}, {"T"c, "𝖳"}, {"U"c, "𝖴"}, {"V"c, "𝖵"}, {"W"c, "𝖶"}, {"X"c, "𝖷"}, {"Y"c, "𝖸"}, {"Z"c, "𝖹"}, {"a"c, "𝖺"}, {"b"c, "𝖻"}, {"c"c, "𝖼"}, {"d"c, "𝖽"}, {"e"c, "𝖾"}, {"f"c, "𝖿"}, {"g"c, "𝗀"}, {"h"c, "𝗁"}, {"i"c, "𝗂"}, {"j"c, "𝗃"}, {"k"c, "𝗄"}, {"l"c, "𝗅"}, {"m"c, "𝗆"}, {"n"c, "𝗇"}, {"o"c, "𝗈"}, {"p"c, "𝗉"}, {"q"c, "𝗊"}, {"r"c, "𝗋"}, {"s"c, "𝗌"}, {"t"c, "𝗍"}, {"u"c, "𝗎"}, {"v"c, "𝗏"}, {"w"c, "𝗐"}, {"x"c, "𝗑"}, {"y"c, "𝗒"}, {"z"c, "𝗓"}, {"0"c, "𝟢"}, {"1"c, "𝟣"}, {"2"c, "𝟤"}, {"3"c, "𝟥"}, {"4"c, "𝟦"}, {"5"c, "𝟧"}, {"6"c, "𝟨"}, {"7"c, "𝟩"}, {"8"c, "𝟪"}, {"9"c, "𝟫"} } End If Return UnicodeCharacterMaps._sansSerif End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Sans-Serif Bold' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5D4 to U+1D607). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝗔', and dictionary key: 'a' gets value: '𝗮'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property SansSerifBold As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._sansSerifBold Is Nothing Then UnicodeCharacterMaps._sansSerifBold = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝗔"}, {"B"c, "𝗕"}, {"C"c, "𝗖"}, {"D"c, "𝗗"}, {"E"c, "𝗘"}, {"F"c, "𝗙"}, {"G"c, "𝗚"}, {"H"c, "𝗛"}, {"I"c, "𝗜"}, {"J"c, "𝗝"}, {"K"c, "𝗞"}, {"L"c, "𝗟"}, {"M"c, "𝗠"}, {"N"c, "𝗡"}, {"O"c, "𝗢"}, {"P"c, "𝗣"}, {"Q"c, "𝗤"}, {"R"c, "𝗥"}, {"S"c, "𝗦"}, {"T"c, "𝗧"}, {"U"c, "𝗨"}, {"V"c, "𝗩"}, {"W"c, "𝗪"}, {"X"c, "𝗫"}, {"Y"c, "𝗬"}, {"Z"c, "𝗭"}, {"a"c, "𝗮"}, {"b"c, "𝗯"}, {"c"c, "𝗰"}, {"d"c, "𝗱"}, {"e"c, "𝗲"}, {"f"c, "𝗳"}, {"g"c, "𝗴"}, {"h"c, "𝗵"}, {"i"c, "𝗶"}, {"j"c, "𝗷"}, {"k"c, "𝗸"}, {"l"c, "𝗹"}, {"m"c, "𝗺"}, {"n"c, "𝗻"}, {"o"c, "𝗼"}, {"p"c, "𝗽"}, {"q"c, "𝗾"}, {"r"c, "𝗿"}, {"s"c, "𝘀"}, {"t"c, "𝘁"}, {"u"c, "𝘂"}, {"v"c, "𝘃"}, {"w"c, "𝘄"}, {"x"c, "𝘅"}, {"y"c, "𝘆"}, {"z"c, "𝘇"}, {"0"c, "𝟬"}, {"1"c, "𝟭"}, {"2"c, "𝟮"}, {"3"c, "𝟯"}, {"4"c, "𝟰"}, {"5"c, "𝟱"}, {"6"c, "𝟲"}, {"7"c, "𝟳"}, {"8"c, "𝟴"}, {"9"c, "𝟵"} } End If Return UnicodeCharacterMaps._sansSerifBold End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Sans-Serif Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D608 to U+1D63B). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝘈', and dictionary key: 'a' gets value: '𝘢'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property SansSerifItalic As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._sansSerifItalic Is Nothing Then UnicodeCharacterMaps._sansSerifItalic = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝘈"}, {"B"c, "𝘉"}, {"C"c, "𝘊"}, {"D"c, "𝘋"}, {"E"c, "𝘌"}, {"F"c, "𝘍"}, {"G"c, "𝘎"}, {"H"c, "𝘏"}, {"I"c, "𝘐"}, {"J"c, "𝘑"}, {"K"c, "𝘒"}, {"L"c, "𝘓"}, {"M"c, "𝘔"}, {"N"c, "𝘕"}, {"O"c, "𝘖"}, {"P"c, "𝘗"}, {"Q"c, "𝘘"}, {"R"c, "𝘙"}, {"S"c, "𝘚"}, {"T"c, "𝘛"}, {"U"c, "𝘜"}, {"V"c, "𝘝"}, {"W"c, "𝘞"}, {"X"c, "𝘟"}, {"Y"c, "𝘠"}, {"Z"c, "𝘡"}, {"a"c, "𝘢"}, {"b"c, "𝘣"}, {"c"c, "𝘤"}, {"d"c, "𝘥"}, {"e"c, "𝘦"}, {"f"c, "𝘧"}, {"g"c, "𝘨"}, {"h"c, "𝘩"}, {"i"c, "𝘪"}, {"j"c, "𝘫"}, {"k"c, "𝘬"}, {"l"c, "𝘭"}, {"m"c, "𝘮"}, {"n"c, "𝘯"}, {"o"c, "𝘰"}, {"p"c, "𝘱"}, {"q"c, "𝘲"}, {"r"c, "𝘳"}, {"s"c, "𝘴"}, {"t"c, "𝘵"}, {"u"c, "𝘶"}, {"v"c, "𝘷"}, {"w"c, "𝘸"}, {"x"c, "𝘹"}, {"y"c, "𝘺"}, {"z"c, "𝘻"} } End If Return UnicodeCharacterMaps._sansSerifItalic End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z', ''' and the values are their corresponding symbols from the 'Sans-Serif Bold Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D63C to U+1D66F). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝘼', and dictionary key: 'a' gets value: '𝙖'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property SansSerifBoldItalic As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._sansSerifBoldItalic Is Nothing Then UnicodeCharacterMaps._sansSerifBoldItalic = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝘼"}, {"B"c, "𝘽"}, {"C"c, "𝘾"}, {"D"c, "𝘿"}, {"E"c, "𝙀"}, {"F"c, "𝙁"}, {"G"c, "𝙂"}, {"H"c, "𝙃"}, {"I"c, "𝙄"}, {"J"c, "𝙅"}, {"K"c, "𝙆"}, {"L"c, "𝙇"}, {"M"c, "𝙈"}, {"N"c, "𝙉"}, {"O"c, "𝙊"}, {"P"c, "𝙋"}, {"Q"c, "𝙌"}, {"R"c, "𝙍"}, {"S"c, "𝙎"}, {"T"c, "𝙏"}, {"U"c, "𝙐"}, {"V"c, "𝙑"}, {"W"c, "𝙒"}, {"X"c, "𝙓"}, {"Y"c, "𝙔"}, {"Z"c, "𝙕"}, {"a"c, "𝙖"}, {"b"c, "𝙗"}, {"c"c, "𝙘"}, {"d"c, "𝙙"}, {"e"c, "𝙚"}, {"f"c, "𝙛"}, {"g"c, "𝙜"}, {"h"c, "𝙝"}, {"i"c, "𝙞"}, {"j"c, "𝙟"}, {"k"c, "𝙠"}, {"l"c, "𝙡"}, {"m"c, "𝙢"}, {"n"c, "𝙣"}, {"o"c, "𝙤"}, {"p"c, "𝙥"}, {"q"c, "𝙦"}, {"r"c, "𝙧"}, {"s"c, "𝙨"}, {"t"c, "𝙩"}, {"u"c, "𝙪"}, {"v"c, "𝙫"}, {"w"c, "𝙬"}, {"x"c, "𝙭"}, {"y"c, "𝙮"}, {"z"c, "𝙯"} } End If Return UnicodeCharacterMaps._sansSerifBoldItalic End Get End Property ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a dictionary where the keys are the alphabet letters from 'a' to 'Z' and numbers from '0' to '9', ''' and the values are their corresponding symbols from the 'Monospace' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D670 to U+1D6A3). ''' <para></para> ''' e.g., dictionary key: 'A' gets value: '𝙰', and dictionary key: 'a' gets value: '𝚊'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property MonoSpace As Dictionary(Of Char, String) Get If UnicodeCharacterMaps._monoSpace Is Nothing Then UnicodeCharacterMaps._monoSpace = New Dictionary(Of Char, String)(EqualityComparer (Of Char ). Default) From { {"A"c, "𝙰"}, {"B"c, "𝙱"}, {"C"c, "𝙲"}, {"D"c, "𝙳"}, {"E"c, "𝙴"}, {"F"c, "𝙵"}, {"G"c, "𝙶"}, {"H"c, "𝙷"}, {"I"c, "𝙸"}, {"J"c, "𝙹"}, {"K"c, "𝙺"}, {"L"c, "𝙻"}, {"M"c, "𝙼"}, {"N"c, "𝙽"}, {"O"c, "𝙾"}, {"P"c, "𝙿"}, {"Q"c, "𝚀"}, {"R"c, "𝚁"}, {"S"c, "𝚂"}, {"T"c, "𝚃"}, {"U"c, "𝚄"}, {"V"c, "𝚅"}, {"W"c, "𝚆"}, {"X"c, "𝚇"}, {"Y"c, "𝚈"}, {"Z"c, "𝚉"}, {"a"c, "𝚊"}, {"b"c, "𝚋"}, {"c"c, "𝚌"}, {"d"c, "𝚍"}, {"e"c, "𝚎"}, {"f"c, "𝚏"}, {"g"c, "𝚐"}, {"h"c, "𝚑"}, {"i"c, "𝚒"}, {"j"c, "𝚓"}, {"k"c, "𝚔"}, {"l"c, "𝚕"}, {"m"c, "𝚖"}, {"n"c, "𝚗"}, {"o"c, "𝚘"}, {"p"c, "𝚙"}, {"q"c, "𝚚"}, {"r"c, "𝚛"}, {"s"c, "𝚜"}, {"t"c, "𝚝"}, {"u"c, "𝚞"}, {"v"c, "𝚟"}, {"w"c, "𝚠"}, {"x"c, "𝚡"}, {"y"c, "𝚢"}, {"z"c, "𝚣"}, {"0"c, "𝟶"}, {"1"c, "𝟷"}, {"2"c, "𝟸"}, {"3"c, "𝟹"}, {"4"c, "𝟺"}, {"5"c, "𝟻"}, {"6"c, "𝟼"}, {"7"c, "𝟽"}, {"8"c, "𝟾"}, {"9"c, "𝟿"} } End If Return UnicodeCharacterMaps._monoSpace End Get End Property #End Region #Region " Constructors " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Prevents a default instance of the <see cref="UnicodeCharacterMaps"/> class from being created. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- <DebuggerNonUserCode> Private Sub New() End Sub #End Region End Class End Namespace #End Region
EL CÓDIGO CONTINÚA EN EL SIGUIENTE POST 👇👇👇
|
|
« Última modificación: 10 Septiembre 2023, 09:09 am por Elektro Enjuto »
|
En línea
|
@%$& #$ %&#$, ¡hay que decirlo más!.
|
|
|
Elektro Enjuto
|
CONTINUACIÓN DEL CÓDIGO DE ARRIBA ☝️☝️☝️ UnicodeAlphabeticCharacterSets.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " UnicodeAlphabeticCharacterSets " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Specifies a Unicode alphabetic character set. ''' <para></para> ''' This enum is used by <see cref="UtilString.ConvertToUnicodeLetters"/> function. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' The Unicode character sets are standardized sets of characters that cover ''' various scripts and symbols used in written languages worldwide. ''' <para></para> ''' Unicode provides a unique code point for each character, ensuring interoperability and ''' compatibility across different platforms and systems. ''' <para></para> ''' The alphabetic character sets defined in this enumeration represent ''' specific stylistic variations of alphabetic characters used in mathematics and typography. ''' <para></para> ''' These character sets are commonly used in scientific and mathematical contexts, ''' as well as in typography and font design. ''' <para></para> ''' They allow for precise representation of stylized alphabetic characters ''' in various mathematical equations, formulas, and text layouts. ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- Public Enum UnicodeAlphabeticCharacterSets ''' <summary> ''' Unicode symbols from the 'Mathematical Bold Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D468 to U+1D49B), ''' representing the alphabet letters from 'a' to 'Z'. ''' <para></para> ''' e.g., 'A': '𝑨', 'a': '𝒂'. ''' </summary> MathematicalBoldItalic ''' <summary> ''' Unicode symbols from the 'Mathematical Bold Script' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D4D0 to U+1D503), ''' representing the alphabet letters from 'a' to 'Z'. ''' <para></para> ''' e.g., 'A': '𝓐', 'a': '𝓪'. ''' </summary> MathematicalBoldScript ''' <summary> ''' Unicode symbols from the 'Mathematical Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D434 to U+1D467), ''' representing the alphabet letters from 'a' to 'Z'. ''' <para></para> ''' e.g., 'A': '𝐴', 'a': '𝑎'. ''' </summary> MathematicalItalic ''' <summary> ''' Unicode symbols from the 'Sans-Serif Bold Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D63C to U+1D66F), ''' representing the alphabet letters from 'a' to 'Z'. ''' <para></para> ''' e.g., 'A': '𝘼', 'a': '𝙖'. ''' </summary> SansSerifBoldItalic ''' <summary> ''' Unicode symbols from the 'Sans-Serif Italic' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D608 to U+1D63B), ''' representing the alphabet letters from 'a' to 'Z'. ''' <para></para> ''' e.g., 'A': '𝘈', 'a': '𝘢'. ''' </summary> SansSerifItalic End Enum End Namespace #End Region
UnicodeAlphanumericCharacterSets.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " UnicodeAlphanumericCharacterSets " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Specifies a Unicode alphanumeric character set. ''' <para></para> ''' This enum is used by <see cref="UtilString.ConvertToUnicodeLetters"/> function. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' The Unicode character sets are standardized sets of characters that cover ''' various scripts and symbols used in written languages worldwide. ''' <para></para> ''' Unicode provides a unique code point for each character, ensuring interoperability and ''' compatibility across different platforms and systems. ''' <para></para> ''' The alphanumeric character sets defined in this enumeration represent ''' specific stylistic variations of alphabetic characters used in mathematics and typography. ''' <para></para> ''' These character sets are commonly used in scientific and mathematical contexts, ''' as well as in typography and font design. ''' <para></para> ''' They allow for precise representation of stylized alphabetic characters ''' in various mathematical equations, formulas, and text layouts. ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- Public Enum UnicodeAlphanumericCharacterSets ''' <summary> ''' Unicode symbols from the 'Mathematical Bold' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D400 to U+1D433), ''' representing the alphabet letters from 'a' to 'Z' and numbers from '0' to '9'. ''' <para></para> ''' e.g., 'A': '𝐀', 'a': '𝐚'. ''' </summary> MathematicalBold ''' <summary> ''' Unicode symbols from the 'Monospace' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D670 to U+1D6A3), ''' representing the alphabet letters from 'a' to 'Z' and numbers from '0' to '9'. ''' <para></para> ''' e.g., 'A': '𝙰', 'a': '𝚊'. ''' </summary> MonoSpace ''' <summary> ''' Unicode symbols from the 'Sans-Serif' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5A0 to U+1D5D3), ''' representing the alphabet letters from 'a' to 'Z' and numbers from '0' to '9'. ''' <para></para> ''' e.g., 'A': '𝖠', 'a': '𝖺'. ''' </summary> SansSerif ''' <summary> ''' Unicode symbols from the 'Sans-Serif Bold' character set ''' of the 'Mathematical Alphanumeric Symbols' unicode blocks (U+1D5D4 to U+1D607), ''' representing the alphabet letters from 'a' to 'Z' and numbers from '0' to '9'. ''' <para></para> ''' e.g., 'A': '𝗔', 'a': '𝗮'. ''' </summary> SansSerifBold End Enum End Namespace #End Region
UtilString.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' ConvertToUnicodeLetters(String, UnicodeAlphabeticCharacterSets) As String ' ConvertToUnicodeLetters(String, UnicodeAlphanumericCharacterSets) As String #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Collections.Generic Imports System.ComponentModel Imports System.Text #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Converts the alphabetic characters in the input string to their corresponding ''' Unicode representations based on the specified character set. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input string to convert. ''' </param> ''' ''' <param name="charSet"> ''' The Unicode character set to use for the character conversion. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The input string with alphabetic characters replaced by their Unicode counterparts. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function ConvertToUnicodeLetters(input As String, charSet As UnicodeAlphabeticCharacterSets) As String If String.IsNullOrWhiteSpace(input) Then Return input End If Select Case charSet Case UnicodeAlphabeticCharacterSets.MathematicalBoldItalic charMap = UnicodeCharacterMaps.MathematicalBoldItalic Case UnicodeAlphabeticCharacterSets.MathematicalBoldScript charMap = UnicodeCharacterMaps.MathematicalBoldScript Case UnicodeAlphabeticCharacterSets.MathematicalItalic charMap = UnicodeCharacterMaps.MathematicalItalic Case UnicodeAlphabeticCharacterSets.SansSerifBoldItalic charMap = UnicodeCharacterMaps.SansSerifBoldItalic Case UnicodeAlphabeticCharacterSets.SansSerifItalic charMap = UnicodeCharacterMaps.SansSerifItalic Case Else Throw New InvalidEnumArgumentException(argumentName:=NameOf(charSet), invalidValue:=charSet, enumClass:=GetType(UnicodeAlphabeticCharacterSets)) End Select Dim sb As New StringBuilder(input.Length) For Each c As Char In input Dim value As String = Nothing If charMap.TryGetValue(c, value) Then sb.Append(value) Else sb.Append(c) End If Next Return sb.ToString() End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Converts the alphanumeric characters in the input string to their corresponding ''' Unicode representations based on the specified character set. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input string to convert. ''' </param> ''' ''' <param name="charSet"> ''' The Unicode character set to use for the character conversion. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The input string with alphanumeric characters replaced by their Unicode counterparts. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function ConvertToUnicodeLetters(input As String, charSet As UnicodeAlphanumericCharacterSets) As String If String.IsNullOrWhiteSpace(input) Then Return input End If Select Case charSet Case UnicodeAlphanumericCharacterSets.MathematicalBold charMap = UnicodeCharacterMaps.MathematicalBold Case UnicodeAlphanumericCharacterSets.MonoSpace charMap = UnicodeCharacterMaps.MonoSpace Case UnicodeAlphanumericCharacterSets.SansSerif charMap = UnicodeCharacterMaps.SansSerif Case UnicodeAlphanumericCharacterSets.SansSerifBold charMap = UnicodeCharacterMaps.SansSerifBold Case Else Throw New InvalidEnumArgumentException(argumentName:=NameOf(charSet), invalidValue:=charSet, enumClass:=GetType(UnicodeAlphanumericCharacterSets)) End Select Dim sb As New StringBuilder(input.Length) For Each c As Char In input Dim value As String = Nothing If charMap.TryGetValue(c, value) Then sb.Append(value) Else sb.Append(c) End If Next Return sb.ToString() End Function #End Region End Class End Namespace #End Region
|
|
|
En línea
|
@%$& #$ %&#$, ¡hay que decirlo más!.
|
|
|
Elektro Enjuto
|
Un código para convertir el texto de un string a superscript y vice-versa. Ejemplos de uso: Dim input As String = "The ideal temperature for sleeping is 18.3 degrees Celsius (65 degrees Fahrenheit)" Dim result As String = ConvertToSuperscript(input)
Dim input As String = "ᵀʰᵉ ⁱᵈᵉᵃˡ ᵗᵉᵐᵖᵉʳᵃᵗᵘʳᵉ ᶠᵒʳ ˢˡᵉᵉᵖⁱⁿᵍ ⁱˢ ¹⁸⋅³ ᵈᵉᵍʳᵉᵉˢ ᑦᵉˡˢⁱᵘˢ ⁽⁶⁵ ᵈᵉᵍʳᵉᵉˢ ⸁ᵃʰʳᵉⁿʰᵉⁱᵗ⁾" Dim result As String = ConvertFromSuperscript(input)
' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' ConvertToSuperscript(String) As String ' ConvertFromSuperscript(String) As String #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Collections.Generic Imports System.ComponentModel Imports System.Text #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Private Fields " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Character map used by functions that converts ASCII characters to its Superscript forms. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Private Shared charMapAsciiToSuperscript As Dictionary(Of Char, Char ) ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Character map used by functions that converts Superscript characters to its ASCII forms. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Private Shared charMapSuperscriptToAscii As List(Of KeyValuePair(Of Char, Char)) #End Region #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Converts the characters in the input string to their corresponding superscript forms. ''' <para></para> ''' Letters in a superscript text are half the normal letter size and are placed above the middle of a text line. ''' For example, the word "Sunshine" in superscript looks like this: "ᔆᵘⁿˢʰⁱⁿᵉ". ''' <para></para> ''' Superscripts are often used in mathematics to denote powers of a number, such as "x²" or "yᵐ". ''' They are also often used to write ordinal numbers, for example, 1ˢᵗ, 2ⁿᵈ, 3ʳᵈ, 4ᵗʰ, and so on. ''' <para></para> ''' Superscript (Wikipedia): <see href="https://en.wikipedia.org/wiki/Subscript_and_superscript"/> ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim input As String = "The ideal temperature for sleeping is 18.3 degrees Celsius (65 degrees Fahrenheit)" ''' Dim result As String = ConvertToSuperscript(input) ''' Console.WriteLine(result) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input string to convert to superscript. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The input string converted to their corresponding superscript forms. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function ConvertToSuperscript(input As String) As String If String.IsNullOrWhiteSpace(input) Then Throw New ArgumentNullException(paramName:=NameOf(input)) End If If UtilString.charMapAsciiToSuperscript Is Nothing Then UtilString.charMapAsciiToSuperscript = New Dictionary(Of Char, Char )(EqualityComparer (Of Char ). Default) From { {"0"c, "⁰"c}, {"1"c, "¹"c}, {"2"c, "²"c}, {"3"c, "³"c}, {"4"c, "⁴"c}, {"5"c, "⁵"c}, {"6"c, "⁶"c}, {"7"c, "⁷"c}, {"8"c, "⁸"c}, {"9"c, "⁹"c}, {"+"c, "⁺"c}, {"-"c, "⁻"c}, {"="c, "⁼"c}, {"("c, "⁽"c}, {")"c, "⁾"c}, {"."c, "⋅"c}, {"·"c, "˙"c}, {"a"c, "ᵃ"c}, {"b"c, "ᵇ"c}, {"c"c, "ᶜ"c}, {"d"c, "ᵈ"c}, {"e"c, "ᵉ"c}, {"f"c, "ᶠ"c}, {"g"c, "ᵍ"c}, {"h"c, "ʰ"c}, {"i"c, "ⁱ"c}, {"j"c, "ʲ"c}, {"k"c, "ᵏ"c}, {"l"c, "ˡ"c}, {"m"c, "ᵐ"c}, {"n"c, "ⁿ"c}, {"o"c, "ᵒ"c}, {"p"c, "ᵖ"c}, {"q"c, "۹"c}, {"r"c, "ʳ"c}, {"s"c, "ˢ"c}, {"t"c, "ᵗ"c}, {"u"c, "ᵘ"c}, {"v"c, "ᵛ"c}, {"w"c, "ʷ"c}, {"x"c, "ˣ"c}, {"y"c, "ʸ"c}, {"z"c, "ᶻ"c}, {"A"c, "ᴬ"c}, {"B"c, "ᴮ"c}, {"C"c, "ᑦ"c}, {"D"c, "ᴰ"c}, {"E"c, "ᴱ"c}, {"F"c, "⸁"c}, {"G"c, "ᴳ"c}, {"H"c, "ᴴ"c}, {"I"c, "ᴵ"c}, {"J"c, "ᴶ"c}, {"K"c, "ᴷ"c}, {"L"c, "ᴸ"c}, {"M"c, "ᴹ"c}, {"N"c, "ᴺ"c}, {"O"c, "ᴼ"c}, {"P"c, "ᴾ"c}, {"Q"c, "ᑫ"c}, {"R"c, "ᴿ"c}, {"S"c, "ᔆ"c}, {"T"c, "ᵀ"c}, {"U"c, "ᵁ"c}, {"V"c, "ⱽ"c}, {"W"c, "ᵂ"c}, {"X"c, "ᕽ"c}, {"Y"c, "ʸ"c}, {"Z"c, "ᙆ"c} } End If Dim sb As New StringBuilder(input.Length) For Each c As Char In input Dim value As Char = Nothing If UtilString.charMapAsciiToSuperscript.TryGetValue(c, value) Then sb.Append(value) Else sb.Append(c) End If Next Return sb.ToString() End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Converts the characters in the input string to their corresponding superscript forms. ''' <para></para> ''' Letters in a superscript text are half the normal letter size and are placed above the middle of a text line. ''' For example, the word "Sunshine" in superscript looks like this: "ᔆᵘⁿˢʰⁱⁿᵉ". ''' <para></para> ''' Superscripts are often used in mathematics to denote powers of a number, such as "x²" or "yᵐ". ''' They are also often used to write ordinal numbers, for example, 1ˢᵗ, 2ⁿᵈ, 3ʳᵈ, 4ᵗʰ, and so on. ''' <para></para> ''' Superscript (Wikipedia): <see href="https://en.wikipedia.org/wiki/Subscript_and_superscript"/> ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim input As String = "ᵀʰᵉ ⁱᵈᵉᵃˡ ᵗᵉᵐᵖᵉʳᵃᵗᵘʳᵉ ᶠᵒʳ ˢˡᵉᵉᵖⁱⁿᵍ ⁱˢ ¹⁸⋅³ ᵈᵉᵍʳᵉᵉˢ ᑦᵉˡˢⁱᵘˢ ⁽⁶⁵ ᵈᵉᵍʳᵉᵉˢ ⸁ᵃʰʳᵉⁿʰᵉⁱᵗ⁾" ''' Dim result As String = ConvertFromSuperscript(input) ''' Console.WriteLine(result) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input string to convert to superscript. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The input string converted to their corresponding superscript forms. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function ConvertFromSuperscript(input As String) As String If String.IsNullOrWhiteSpace(input) Then Throw New ArgumentNullException(paramName:=NameOf(input)) End If If UtilString.charMapSuperscriptToAscii Is Nothing Then UtilString.charMapSuperscriptToAscii = New List(Of KeyValuePair(Of Char, Char)) From { {New KeyValuePair(Of Char, Char)("⁰"c, "0"c)}, {New KeyValuePair(Of Char, Char)("¹"c, "1"c)}, {New KeyValuePair(Of Char, Char)("²"c, "2"c)}, {New KeyValuePair(Of Char, Char)("³"c, "3"c)}, {New KeyValuePair(Of Char, Char)("⁴"c, "4"c)}, {New KeyValuePair(Of Char, Char)("⁵"c, "5"c)}, {New KeyValuePair(Of Char, Char)("⁶"c, "6"c)}, {New KeyValuePair(Of Char, Char)("⁷"c, "7"c)}, {New KeyValuePair(Of Char, Char)("⁸"c, "8"c)}, {New KeyValuePair(Of Char, Char)("⁹"c, "9"c)}, {New KeyValuePair(Of Char, Char)("⁺"c, "+"c)}, {New KeyValuePair(Of Char, Char)("⁻"c, "-"c)}, {New KeyValuePair(Of Char, Char)("⁼"c, "="c)}, {New KeyValuePair(Of Char, Char)("⁽"c, "("c)}, {New KeyValuePair(Of Char, Char)("⁾"c, ")"c)}, {New KeyValuePair(Of Char, Char)("⋅"c, "."c)}, {New KeyValuePair(Of Char, Char)("˙"c, "·"c)}, {New KeyValuePair(Of Char, Char)("ᵃ"c, "a"c)}, {New KeyValuePair(Of Char, Char)("ᵇ"c, "b"c)}, {New KeyValuePair(Of Char, Char)("ᶜ"c, "c"c)}, {New KeyValuePair(Of Char, Char)("ᵈ"c, "d"c)}, {New KeyValuePair(Of Char, Char)("ᵉ"c, "e"c)}, {New KeyValuePair(Of Char, Char)("ᶠ"c, "f"c)}, {New KeyValuePair(Of Char, Char)("ᵍ"c, "g"c)}, {New KeyValuePair(Of Char, Char)("ʰ"c, "h"c)}, {New KeyValuePair(Of Char, Char)("ⁱ"c, "i"c)}, {New KeyValuePair(Of Char, Char)("ʲ"c, "j"c)}, {New KeyValuePair(Of Char, Char)("ᵏ"c, "k"c)}, {New KeyValuePair(Of Char, Char)("ˡ"c, "l"c)}, {New KeyValuePair(Of Char, Char)("ᵐ"c, "m"c)}, {New KeyValuePair(Of Char, Char)("ⁿ"c, "n"c)}, {New KeyValuePair(Of Char, Char)("ᵒ"c, "o"c)}, {New KeyValuePair(Of Char, Char)("ᵖ"c, "p"c)}, {New KeyValuePair(Of Char, Char)("۹"c, "q"c)}, {New KeyValuePair(Of Char, Char)("ʳ"c, "r"c)}, {New KeyValuePair(Of Char, Char)("ˢ"c, "s"c)}, {New KeyValuePair(Of Char, Char)("ᵗ"c, "t"c)}, {New KeyValuePair(Of Char, Char)("ᵘ"c, "u"c)}, {New KeyValuePair(Of Char, Char)("ᵛ"c, "v"c)}, {New KeyValuePair(Of Char, Char)("ʷ"c, "w"c)}, {New KeyValuePair(Of Char, Char)("ˣ"c, "x"c)}, {New KeyValuePair(Of Char, Char)("ʸ"c, "y"c)}, {New KeyValuePair(Of Char, Char)("ᶻ"c, "z"c)}, {New KeyValuePair(Of Char, Char)("ᴬ"c, "A"c)}, {New KeyValuePair(Of Char, Char)("ᴮ"c, "B"c)}, {New KeyValuePair(Of Char, Char)("ᑦ"c, "C"c)}, {New KeyValuePair(Of Char, Char)("ᴰ"c, "D"c)}, {New KeyValuePair(Of Char, Char)("ᴱ"c, "E"c)}, {New KeyValuePair(Of Char, Char)("⸁"c, "F"c)}, {New KeyValuePair(Of Char, Char)("ᴳ"c, "G"c)}, {New KeyValuePair(Of Char, Char)("ᴴ"c, "H"c)}, {New KeyValuePair(Of Char, Char)("ᴵ"c, "I"c)}, {New KeyValuePair(Of Char, Char)("ᴶ"c, "J"c)}, {New KeyValuePair(Of Char, Char)("ᴷ"c, "K"c)}, {New KeyValuePair(Of Char, Char)("ᴸ"c, "L"c)}, {New KeyValuePair(Of Char, Char)("ᴹ"c, "M"c)}, {New KeyValuePair(Of Char, Char)("ᴺ"c, "N"c)}, {New KeyValuePair(Of Char, Char)("ᴼ"c, "O"c)}, {New KeyValuePair(Of Char, Char)("ᴾ"c, "P"c)}, {New KeyValuePair(Of Char, Char)("ᑫ"c, "Q"c)}, {New KeyValuePair(Of Char, Char)("ᴿ"c, "R"c)}, {New KeyValuePair(Of Char, Char)("ᔆ"c, "S"c)}, {New KeyValuePair(Of Char, Char)("ᵀ"c, "T"c)}, {New KeyValuePair(Of Char, Char)("ᵁ"c, "U"c)}, {New KeyValuePair(Of Char, Char)("ⱽ"c, "V"c)}, {New KeyValuePair(Of Char, Char)("ᵂ"c, "W"c)}, {New KeyValuePair(Of Char, Char)("ᕽ"c, "X"c)}, {New KeyValuePair(Of Char, Char)("ʸ"c, "Y"c)}, {New KeyValuePair(Of Char, Char)("ᙆ"c, "Z"c)} } End If Dim defaultPair As New KeyValuePair(Of Char, Char) Dim sb As New StringBuilder(input.Length) For Each c As Char In input Dim pair As KeyValuePair(Of Char, Char) = charMapSuperscriptToAscii.Find(Function(kv) kv.Key = c) If Not pair.Equals(defaultPair) Then sb.Append(pair.Value) Else sb.Append(c) End If Next Return sb.ToString() End Function #End Region End Class End Namespace #End Region
|
|
|
En línea
|
@%$& #$ %&#$, ¡hay que decirlo más!.
|
|
|
Elektro Enjuto
|
Un algoritmo para justificar un string. Me he inspirado en este servicio online: https://onlinetexttools.com/justify-textEjemplo de uso: Dim input As String = "About 20% of oxygen is produced by the Amazon rainforest. The Earth's atmosphere is about 78 percent nitrogen, 21 percent oxygen, and about 1 percent other gases. For the existence of most organisms on the planet, oxygen is a necessary element, it provides the body with energy and removes carbon dioxide. Fortunately, plants constantly replenish the oxygen level of our planet thanks to photosynthesis. During this process, carbon dioxide and water are converted into energy, releasing oxygen as a byproduct. The Amazon rainforest covers 5.5 million square kilometers (2.1 million square miles), recycling much of the Earth's oxygen while absorbing large amounts of carbon dioxide." Dim lineLength As Integer = 50 Dim result As String = UtilString.JustifyText(input, lineLength, justifyLastLine:=True) Console.WriteLine(result)
Salida: About 20% of oxygen is produced by the Amazon rainforest. The Earth's atmosphere is about 78 percent nitrogen, 21 percent oxygen, and about 1 percent other gases.
For the existence of most organisms on the planet, oxygen is a necessary element, it provides the body with energy and removes carbon dioxide. Fortunately, plants constantly replenish the oxygen level of our planet thanks to photosynthesis. During this process, carbon dioxide and water are converted into energy, releasing oxygen as a byproduct.
The Amazon rainforest covers 5.5 million square kilometers (2.1 million square miles), recycling much of the Earth's oxygen while absorbing large amounts of carbon dioxide. ' *********************************************************************** ' Author : ElektroStudios ' Modified : 13-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' JustifyText(String, Integer, Opt: Boolean) As String #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Collections.ObjectModel Imports System.Text #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Justifies the input text by adjusting the line width and spacing between words. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim input As String = ''' "About 20% of oxygen is produced by the Amazon rainforest. The Earth's atmosphere is about 78 percent nitrogen, 21 percent oxygen, and about 1 percent other gases. ''' ''' For the existence of most organisms on the planet, oxygen is a necessary element, it provides the body with energy and removes carbon dioxide. Fortunately, plants constantly replenish the oxygen level of our planet thanks to photosynthesis. During this process, carbon dioxide and water are converted into energy, releasing oxygen as a byproduct. ''' ''' The Amazon rainforest covers 5.5 million square kilometers (2.1 million square miles), recycling much of the Earth's oxygen while absorbing large amounts of carbon dioxide." ''' ''' Dim lineLength As Integer = 50 ''' ''' Dim result As String = JustifyText(input, lineLength, justifyLastLine:=True) ''' ''' Console.WriteLine(result) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input text. ''' </param> ''' ''' <param name="length"> ''' The desired length for each text line. ''' </param> ''' ''' <param name="justifyLastLine"> ''' Optional. Indicates whether to justify the last line of the paragraphs. ''' <para></para> ''' Default value is: False. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The resulting justified text. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function JustifyText(input As String, length As Integer, Optional justifyLastLine As Boolean = False) As String Dim paragraphs As String() = input.Split({Environment.NewLine}, StringSplitOptions.None) Dim paragraphsCount As Integer = paragraphs.Length For paragraphIdx As Integer = 0 To paragraphsCount - 1 Dim words As String() = paragraphs(paragraphIdx).Split(" "c) Dim currentLine As New StringBuilder() Dim currentLineLength As Integer = 0 For Each word As String In words Dim wordLength As Integer = word.Length If currentLineLength + wordLength <= length Then currentLine.Append(word & " ") currentLineLength += wordLength + 1 Else lines.Add(currentLine.ToString().Trim()) currentLine = New StringBuilder(word & " ") currentLineLength = wordLength + 1 End If If wordLength > length Then Dim remainingWord As String = word While remainingWord.Length > length lines.Add(remainingWord.Substring(0, length)) remainingWord = remainingWord.Substring(length) End While If remainingWord.Length > 0 Then lines.Add(remainingWord) End If End If Next lines.Add(currentLine.ToString().Trim()) For i As Integer = 0 To lines.Count - 1 Dim line As String = lines(i) If (i = lines.Count - 1) AndAlso Not justifyLastLine Then justifiedLines.Add(line) Continue For End If Dim lineLength As Integer = line.Length Dim wordsInLine As String() = line.Split(" "c) Dim wordsCount As Integer = wordsInLine.Length If wordsCount > 1 Then Dim remainingSpaces As Integer = length - line.Replace(" "c, "").Length Dim spacesPerGap As Integer = remainingSpaces \ (wordsCount - 1) Dim extraSpaces As Integer = remainingSpaces Mod (wordsCount - 1) Dim justifiedLine As New StringBuilder(wordsInLine(0)) For j As Integer = 1 To wordsCount - 1 justifiedLine.Append(" "c, spacesPerGap) If j <= extraSpaces Then justifiedLine.Append(" "c) End If justifiedLine.Append(wordsInLine(j)) Next line = justifiedLine.ToString() End If justifiedLines.Add(line) Next If Not justifyLastLine AndAlso justifiedLines.Count > 1 Then justifiedLines(justifiedLines.Count - 1) = justifiedLines(justifiedLines.Count - 1).TrimEnd() End If Next Return String.Join(Environment.NewLine, justifiedLines) End Function #End Region End Class End Namespace #End Region
|
|
« Última modificación: 10 Septiembre 2023, 09:21 am por Elektro Enjuto »
|
En línea
|
@%$& #$ %&#$, ¡hay que decirlo más!.
|
|
|
Elektro Enjuto
|
Un algoritmo para volcar un texto de forma vertical. Inspirado en este servicio: https://onlinetexttools.com/flip-text-verticallyLos resultados son idénticos o muy similares a estos: UtilString.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' FlipTextVertically(String, VerticalFlipTextMode, Opt: Char) As String #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Collections.Generic Imports System.ComponentModel Imports System.Linq Imports System.Text #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Transforms the source string into vertical text. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <seealso href="https://onlinetexttools.com/flip-text-vertically"/> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input string to flip it vertically. ''' <para></para> ''' If this value is null, no changes are made to the string. ''' </param> ''' ''' <param name="flipMode"> ''' The vertical flip mode indicating how the text should be flipped. ''' </param> ''' ''' <param name="separatorChar"> ''' Optional. The character used to separate columns. Default is "|". ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The resulting vertically flipped text. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function FlipTextVertically(input As String, flipMode As VerticalFlipTextMode, Optional separatorChar As Char = "|"c) As String If String.IsNullOrEmpty(input) Then Return input End If If separatorChar.Equals(Nothing) Then Throw New ArgumentNullException(paramName:=NameOf(separatorChar)) End If Select Case flipMode Case VerticalFlipTextMode.CharByChar Dim lines As String() = input.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) Dim maxLength As Integer = lines.Max(Function(line) line.Length) Dim verticalText As New StringBuilder() For i As Integer = 0 To maxLength - 1 For j As Integer = 0 To lines.Length - 1 If i < lines(j).Length Then verticalText.Append(lines(j)(i)) Else verticalText.Append(" "c) End If If j < lines.Length - 1 Then verticalText.Append($" {separatorChar} ") End If Next verticalText.AppendLine() Next Return verticalText.ToString() Case VerticalFlipTextMode.WordByWord Dim lines As String() = input.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) Dim wordsPerLine As New List(Of List(Of String))() For Each line As String In lines Dim words As String() = line.Split({" "c}, StringSplitOptions.RemoveEmptyEntries) wordsPerLine.Add(words.ToList()) Next Dim maxLength As Integer = wordsPerLine.Max(Function(words) words.Count) Dim verticalText As New StringBuilder() For i As Integer = 0 To maxLength - 1 For j As Integer = 0 To wordsPerLine.Count - 1 Dim words As List(Of String) = wordsPerLine(j) If i < words.Count Then verticalText.Append(words(i).PadRight(words.Max(Function(word) word.Length))) Else verticalText.Append(" ".PadRight(words.Max(Function(word) word.Length))) End If If j < wordsPerLine.Count - 1 Then verticalText.Append($" {separatorChar} ") End If Next verticalText.AppendLine() Next Return verticalText.ToString() Case VerticalFlipTextMode.SentenceBySentence Dim GetMaxSentences As Func(Of String(), Integer) = Function(_lines As String()) As Integer Dim _maxSentences As Integer = 0 For Each line As String In _lines Dim sentences As String() = line.Split({"."c}, StringSplitOptions.RemoveEmptyEntries) _maxSentences = System.Math.Max(_maxSentences, sentences.Length) Next Return _maxSentences End Function Dim GetColumnWidths As Func(Of String(), Integer, Integer()) = Function(_lines As String(), _maxSentences As Integer) As Integer() Dim _columnWidths As Integer() = New Integer(_lines.Length - 1) {} For i As Integer = 0 To _lines.Length - 1 Dim line As String = _lines(i) Dim sentences As String() = line.Split({"."c}, StringSplitOptions.RemoveEmptyEntries) Dim maxWidth As Integer = 0 For j As Integer = 0 To System.Math.Min(_maxSentences, sentences.Length) - 1 maxWidth = System.Math.Max(maxWidth, sentences(j).Trim().Length) Next _columnWidths(i) = maxWidth Next Return _columnWidths End Function Dim lines As String() = input.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) Dim maxSentences As Integer = GetMaxSentences(lines) Dim columnWidths As Integer() = GetColumnWidths(lines, maxSentences) Dim output As New StringBuilder() For i As Integer = 0 To maxSentences - 1 For j As Integer = 0 To lines.Length - 1 Dim line As String = lines(j) Dim sentences As String() = line.Split({"."c}, StringSplitOptions.RemoveEmptyEntries) Dim sentence As String = "" If i < sentences.Length Then sentence = sentences(i).Trim() & "." End If Dim column As String = sentence.PadRight(columnWidths(j) + 1) output.Append(column) If j < lines.Length - 1 Then output.Append($" {separatorChar} ") End If Next output.AppendLine() Next Return output.ToString() Case Else Throw New InvalidEnumArgumentException(argumentName:=NameOf(flipMode), invalidValue:=flipMode, enumClass:=GetType(VerticalFlipTextMode)) End Select End Function #End Region End Class End Namespace #End Region
VerticalFlipTextMode.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Option Statements " Option Strict Off Option Explicit On Option Infer Off #End Region #Region " Imports " #End Region #Region " VerticalFlipTextMode " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Specifies how the text should be flipped when using <see cref="UtilString.FlipTextVertically"/> function. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Enum VerticalFlipTextMode As Integer ''' <summary> ''' Divides the text into characters. ''' That is, all the characters from every text row get rearranged in columns. ''' </summary> CharByChar ''' <summary> ''' Divides the text into words. ''' <para></para> ''' That is, all the words from every text row get rearranged in columns. ''' </summary> WordByWord ''' <summary> ''' Divides the text into sentences. ''' <para></para> ''' That is, if you have several sentences in one line, ''' then after rewriting them vertically, they will appear in a single column. ''' </summary> SentenceBySentence End Enum End Namespace #End Region
|
|
|
En línea
|
@%$& #$ %&#$, ¡hay que decirlo más!.
|
|
|
Elektro Enjuto
|
Un algoritmo para envolver de forma decorativa los caracteres de un string. Inspirado en este servicio: https://onlinetexttools.com/add-symbols-around-lettersLos resultados son idénticos o muy similares a esto: ...con opciones de personalización.
' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' WrapCharacters(String, Char, Char, Opt: Boolean, Opt: Boolean) As String #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Linq Imports System.Text #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Decorates the input string by wrapping each character with the specified decorative symbols ''' for its left and right sides. ''' <para></para> ''' For example, if the input string is 'ABC', the resulting string could be similar to this: '{A}{B}{C}'. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input string to decorate. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="leftChar"> ''' The character used for decorating the left side of the characters in the input string. ''' </param> ''' ''' <param name="rightChar"> ''' The character used for decorating the right side of the characters in the input string. ''' </param> ''' ''' <param name="surroundNonAlphanumeric"> ''' If true, also decorates non-alphanumeric characters. ''' <para></para> ''' Default value is: False. ''' </param> ''' ''' <param name="squishRepeatedDecorationChars"> ''' If true, and if <paramref name="leftChar"/> and <paramref name="rightChar"/> are the same characters, ''' only draws the decorative symbol for the left side of the characters in the input string. ''' <para></para> ''' Default value is: False. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The resulting decorated string. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function WrapCharacters(input As String, leftChar As Char, rightChar As Char, Optional surroundNonAlphanumeric As Boolean = False, Optional squishRepeatedDecorationChars As Boolean = False) As String If String.IsNullOrEmpty(input) Then Throw New ArgumentNullException(paramName:=NameOf(input)) End If If leftChar.Equals(Nothing) Then Throw New ArgumentNullException(paramName:=NameOf(leftChar)) End If If rightChar.Equals(Nothing) Then Throw New ArgumentNullException(paramName:=NameOf(rightChar)) End If Dim areSameDecorationChars As Boolean = (leftChar = rightChar) Dim sb As New StringBuilder() For Each c As Char In input Dim decoratedChar As String = If(Char.IsLetterOrDigit(c) OrElse (surroundNonAlphanumeric AndAlso Not Char.IsWhiteSpace(c)), If(squishRepeatedDecorationChars AndAlso areSameDecorationChars, $"{leftChar}{c}", $"{leftChar}{c}{rightChar}"), c) sb.Append(decoratedChar) Next Return sb.ToString() End Function #End Region End Class End Namespace #End Region
|
|
|
En línea
|
@%$& #$ %&#$, ¡hay que decirlo más!.
|
|
|
Elektro Enjuto
|
Un algoritmo para dibujar cajas unicode envolviendo un texto. Útil para decorar la interfaz de aplicaciones de consola. Inspirado en este servicio: https://onlinetexttools.com/draw-box-around-text( el resultado debería ser idéntico. ) Ejemplo de uso: Dim input As String = "Push this button!" Dim verticalPadding As Integer = 1 Dim horizontalPadding As Integer = 2 Dim fillChar As Char = "█"c Dim drawingStyle As New BoxDrawingStyle With { .Top = "═"c, .Bottom = "═"c, .Left = "║"c, .Right = "║"c, .TopLeft = "╔"c, .TopRight = "╗"c, .BottomLeft = "╚"c, .BottomRight = "╝"c } Dim result As String = DrawTextBox(input, verticalPadding, horizontalPadding, fillChar, drawingStyle) Console.WriteLine(result) IO. File. WriteAllText("\box.txt", result, Encoding. Unicode)
Salida: UtilString.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Public Members Summary " #Region " Functions " ' DrawTextBox(String, Opt: Integer, Opt: Integer, Opt: Char, Opt: BoxDrawingStyle) As String #End Region #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Linq Imports System.Text #End Region #Region " String Util " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common Partial Public NotInheritable Class UtilString #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Draws a box around the specified text, that is, a text-box. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim input As String = "Push this button!" ''' Dim verticalPadding As Integer = 1 ''' Dim horizontalPadding As Integer = 2 ''' Dim fillChar As Char = "█"c ''' Dim drawingStyle As New BoxDrawingStyle With { ''' .Top = "═"c, .Bottom = "═"c, ''' .Left = "║"c, .Right = "║"c, ''' .TopLeft = "╔"c, ''' .TopRight = "╗"c, ''' .BottomLeft = "╚"c, ''' .BottomRight = "╝"c ''' } ''' ''' Dim result As String = DrawTextBox(input, verticalPadding, horizontalPadding, fillChar, drawingStyle) ''' ''' Console.WriteLine(result) ''' IO.File.WriteAllText("\box.txt", result, Encoding.Unicode) ''' ' Output: ''' ' ╔═════════════════════╗ ''' ' ║█████████████████████║ ''' ' ║██Push this button!██║ ''' ' ║█████████████████████║ ''' ' ╚═════════════════════╝ ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="input"> ''' The input text to be boxed. ''' </param> ''' ''' <param name="verticalPadding"> ''' Optional. The number of vertical padding lines. Default value is: '0'. ''' </param> ''' ''' <param name="horizontalPadding"> ''' Optional. The number of horizontal padding characters. Default value is: '0'. ''' </param> ''' ''' <param name="fillChar"> ''' Optional. The character used to fill the empty space in the box. Default value is: " " (white-space). ''' </param> ''' ''' <param name="drawingStyle"> ''' Optional. The style of the box drawing. If not specified, a default style will be used. ''' <para></para> ''' If this value is null, "-" character is used for vertical sides, ''' "|" for horizontal sides and "+" for all corners. ''' <para></para> ''' Default value is: null. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The resulting string containing the text enclosed in the box. ''' </returns> ''' -------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function DrawTextBox(input As String, Optional verticalPadding As Integer = 0, Optional horizontalPadding As Integer = 0, Optional fillChar As Char = " "c, Optional drawingStyle As BoxDrawingStyle = Nothing) As String If String.IsNullOrEmpty(input) Then Throw New ArgumentNullException(paramName:=NameOf(input)) End If If verticalPadding < 0 Then Throw New ArgumentException("Value can't be less than zero.", paramName:=NameOf(input)) End If If horizontalPadding < 0 Then Throw New ArgumentException("Value can't be less than zero.", paramName:=NameOf(input)) End If If fillChar.Equals(Nothing) Then Throw New ArgumentNullException(paramName:=NameOf(fillChar)) End If If drawingStyle = BoxDrawingStyle.Empty Then drawingStyle = New BoxDrawingStyle With { .Top = "-"c, .Bottom = "-"c, .Left = "|"c, .Right = "|"c, .TopLeft = "+"c, .TopRight = "+"c, .BottomLeft = "+"c, .BottomRight = "+"c } End If Dim lines As String() = input.Split({Environment.NewLine}, StringSplitOptions.None) Dim linesLength As Integer = lines.Length Dim maxLength As Integer = lines.Max(Function(line As String) line.Length) Dim boxWidth As Integer = maxLength + (horizontalPadding * 2) Dim boxHeight As Integer = linesLength + (verticalPadding * 2) Dim sb As New StringBuilder() ' Draw top line. sb.AppendLine(drawingStyle.TopLeft & New String(drawingStyle.Top, boxWidth) & drawingStyle.TopRight) ' Draw top padding line(s). For i As Integer = 0 To verticalPadding - 1 sb.AppendLine(drawingStyle.Left & New String(fillChar, boxWidth) & drawingStyle.Right) Next ' Draw inner line(s). For i As Integer = 0 To lines.Length - 1 Dim paddedLine As String = lines(i).PadRight(maxLength, fillChar) sb.AppendLine(drawingStyle.Left & New String(fillChar, horizontalPadding) & paddedLine & New String(fillChar, horizontalPadding) & drawingStyle.Right) Next ' Draw bottom padding line(s). For i As Integer = 0 To verticalPadding - 1 sb.AppendLine(drawingStyle.Left & New String(fillChar, boxWidth) & drawingStyle.Right) Next ' Draw bottom line. sb.AppendLine(drawingStyle.BottomLeft & New String(drawingStyle.Bottom, boxWidth) & drawingStyle.BottomRight) Return sb.ToString() End Function #End Region End Class End Namespace #End Region
BoxDrawingStyle.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 11-July-2023 ' *********************************************************************** #Region " Option Statements " Option Strict Off Option Explicit On Option Infer Off #End Region #Region " Usage Examples " #End Region #Region " Imports " Imports System.Runtime.InteropServices Imports System.Xml.Serialization #End Region #Region " BoxDrawingStyle " ' ReSharper disable once CheckNamespace Namespace DevCase.Core.DataProcessing.Common ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Defines the characters used to draw the sides and corners of a box. ''' </summary> ''' -------------------------------------------------------------------------------------------------- <Serializable> <XmlRoot(NameOf(BoxDrawingStyle))> <StructLayout(LayoutKind.Sequential)> Public Structure BoxDrawingStyle #Region " Fields " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' The character used for the top line of the box. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Top As Char ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' The character used for the bottom line of the box. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Bottom As Char ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' The character used for the left border of the box. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Left As Char ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' The character used for the right border of the box. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Right As Char ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' The character used for the top-left corner of the box. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public TopLeft As Char ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' The character used for the top-right corner of the box. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public TopRight As Char ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' The character used for the bottom-left corner of the box. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public BottomLeft As Char ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' The character used for the bottom-right corner of the box. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public BottomRight As Char #End Region #Region " Properties " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Gets a <see cref="BoxDrawingStyle"/> with all characters set to null. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- Public Shared ReadOnly Property Empty As BoxDrawingStyle Get Return New BoxDrawingStyle() End Get End Property #End Region #Region " Public Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Determines whether this instance of <see cref="BoxDrawingStyle"/> is equal to another object. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="obj"> ''' The object to compare with this instance. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see langword="true"/> if the specified object is equal to this instance; ''' otherwise, <see langword="false"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Public Overrides Function Equals(obj As Object) As Boolean If TypeOf obj Is BoxDrawingStyle Then Dim otherStyle As BoxDrawingStyle = DirectCast(obj, BoxDrawingStyle) Return Me.Top = otherStyle.Top AndAlso Me.Bottom = otherStyle.Bottom AndAlso Me.Left = otherStyle.Left AndAlso Me.Right = otherStyle.Right AndAlso Me.TopLeft = otherStyle.TopLeft AndAlso Me.TopRight = otherStyle.TopRight AndAlso Me.BottomLeft = otherStyle.BottomLeft AndAlso Me.BottomRight = otherStyle.BottomRight End If Return False End Function #End Region #Region " Operators " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Determines whether two instances of <see cref="BoxDrawingStyle"/> are equal. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="style1"> ''' The first <see cref="BoxDrawingStyle"/> to compare. ''' </param> ''' ''' <param name="style2"> ''' The second <see cref="BoxDrawingStyle"/> to compare. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see langword="true"/> if the specified instances are equal; otherwise, <see langword="false"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Public Shared Operator =(style1 As BoxDrawingStyle, style2 As BoxDrawingStyle) As Boolean Return style1.Top = style2.Top AndAlso style1.Bottom = style2.Bottom AndAlso style1.Left = style2.Left AndAlso style1.Right = style2.Right AndAlso style1.TopLeft = style2.TopLeft AndAlso style1.TopRight = style2.TopRight AndAlso style1.BottomLeft = style2.BottomLeft AndAlso style1.BottomRight = style2.BottomRight End Operator ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Determines whether two instances of <see cref="BoxDrawingStyle"/> are not equal. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="style1"> ''' The first <see cref="BoxDrawingStyle"/> to compare. ''' </param> ''' ''' <param name="style2"> ''' The second <see cref="BoxDrawingStyle"/> to compare. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see langword="true"/> if the specified instances are not equal; otherwise, <see langword="false"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Public Shared Operator <>(style1 As BoxDrawingStyle, style2 As BoxDrawingStyle) As Boolean Return Not (style1 = style2) End Operator #End Region End Structure End Namespace #End Region
|
|
|
En línea
|
@%$& #$ %&#$, ¡hay que decirlo más!.
|
|
|
Elektro Enjuto
|
Algunos atajos a modo de extensiones de métodos para simplificar la generación de excepciones al cumplir cierta condición en un objeto. Ejemplos de uso: - Object.ThrowIf Dim value As Integer = 0 ' value.ThrowIf(Of ArgumentOutOfRangeException)(Function(x) x = 0) value.ThrowIf(Function(x) x = 0, New ArgumentOutOfRangeException(paramName:=NameOf(value)))
- Object.ThrowIfNotInRange Dim value As Integer = 10 ' value.ThrowIfNotInRange(min:=1, max:=9) value.ThrowIfNotInRange(min:=1, max:=9, message:="Value is not within the allowed range.", paramName:=NameOf(value))
- Object.ThrowIfNull Dim obj As Object = Nothing ' obj.ThrowIfNull(Of ArgumentNullException) obj.ThrowIfNull(New ArgumentNullException(paramName:=NameOf(obj)))
- Object.ThrowIfDefault Dim obj As Integer = 0 ' obj.ThrowIfDefault(Of ArgumentNullException) obj.ThrowIfDefault(New ArgumentNullException(paramName:=NameOf(obj)))
Y para un valor booleano: - Boolean.ThrowIfFalse Dim value As Boolean = False ' value.ThrowIfFalse(Of ArgumentException) value.ThrowIfFalse(New ArgumentException(message:="'true' expected.", paramName:=NameOf(value)))
- Boolean.ThrowIfTrue Dim value As Boolean = True ' value.ThrowIfTrue(Of ArgumentException) value.ThrowIfTrue(New ArgumentException(message:="'false' expected.", paramName:=NameOf(value)))
ObjectExtensions.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 09-July-2023 ' *********************************************************************** #Region " Public Members Summary " ' Object.ThrowIf(Of TObject, TException As Exception)(Func(Of TObject, Boolean), Opt: TException) ' Object.ThrowIfNull(Of TException As Exception)(Opt: TException) ' Object.ThrowIfDefault(Of TException As Exception)(Opt: TException) ' Object.ThrowIfNotInRange(T, T, Opt: String, Opt: String) ' Object.IsDefault As Boolean #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.ComponentModel Imports System.Reflection Imports System.Runtime.CompilerServices #End Region #Region " Object Extensions " ' ReSharper disable once CheckNamespace Namespace DevCase.Extensions.ObjectExtensions ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Contains custom extension methods to use with the <see cref="Object"/> type. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- <ImmutableObject(True)> <HideModuleName> Public Module ObjectExtensions #Region " Public Extension Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Throws the specified exception if the given condition in the source object is true. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim value As Integer = 0 ''' ' value.ThrowIf(Of ArgumentOutOfRangeException)(Function(x) x = 0) ''' value.ThrowIf(Function(x) x = 0, New ArgumentOutOfRangeException(paramName:=NameOf(value))) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="TObject"> ''' The type of object to evaluate. ''' </typeparam> ''' ''' <typeparam name="TException"> ''' The type of exception to throw. ''' </typeparam> ''' ''' <param name="obj"> ''' The object to evaluate. ''' </param> ''' ''' <param name="predicate"> ''' The predicate function to evaluate the object. ''' </param> ''' ''' <param name="ex"> ''' Optionally, a instance of the exception to throw when ''' the <paramref name="predicate"/> condition is true. ''' <para></para> ''' If this value is null, a default instance of the exception type will be used. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub ThrowIf(Of TObject, TException As Exception)(obj As TObject, predicate As Func(Of TObject, Boolean), Optional ex As TException = Nothing) If predicate(obj) Then If ex Is Nothing Then ex = Activator.CreateInstance(Of TException) End If Throw ex End If End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Throws the specified exception if the source object is null. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim obj As Object = Nothing ''' ' obj.ThrowIfNull(Of ArgumentNullException) ''' obj.ThrowIfNull(New ArgumentNullException(paramName:=NameOf(obj))) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="TException"> ''' The type of exception to throw. ''' </typeparam> ''' ''' <param name="obj"> ''' The object to check for null. ''' </param> ''' ''' <param name="ex"> ''' Optionally, a instance of the exception to throw when the source object is null. ''' <para></para> ''' If this value is null, a default instance of the exception type will be used. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub ThrowIfNull(Of TException As Exception)(obj As Object, Optional ex As TException = Nothing) If obj Is Nothing Then If ex Is Nothing Then ex = Activator.CreateInstance(Of TException) End If Throw ex End If End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Throws the specified exception if the source object is the default value of its type. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim obj As Integer = 0 ''' ' obj.ThrowIfDefault(Of ArgumentNullException) ''' obj.ThrowIfDefault(New ArgumentNullException(paramName:=NameOf(obj))) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="TException"> ''' The type of exception to throw. ''' </typeparam> ''' ''' <param name="obj"> ''' The object to evaluate. ''' </param> ''' ''' <param name="ex"> ''' Optionally, a instance of the exception to throw when the source object is the default value of its type. ''' <para></para> ''' If this value is null, a default instance of the exception type will be used. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub ThrowIfDefault(Of TObject, TException As Exception)(obj As TObject, Optional ex As TException = Nothing) If obj.IsDefault() Then If ex Is Nothing Then ex = Activator.CreateInstance(Of TException) End If Throw ex End If End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Throws an <see cref="ArgumentOutOfRangeException"/> if the ''' source value is not within the specified range. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim value As Integer = 10 ''' ' value.ThrowIfNotInRange(min:=1, max:=9) ''' value.ThrowIfNotInRange(min:=1, max:=9, message:="Value is not within the allowed range.", paramName:=NameOf(value)) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' The type of value to evaluate. ''' </typeparam> ''' ''' <param name="value"> ''' The value to evaluate. ''' </param> ''' ''' <param name="min"> ''' The minimum allowed value (inclusive). ''' </param> ''' ''' <param name="max"> ''' The maximum allowed value (inclusive). ''' </param> ''' ''' <param name="message"> ''' Optionally, the custom error message for the <see cref="ArgumentOutOfRangeException"/>. ''' </param> ''' ''' <param name="paramName"> ''' Optionally, the name of the parameter that caused the <see cref="ArgumentOutOfRangeException"/>. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <exception cref="ArgumentOutOfRangeException"> ''' Thrown when the value is not within the specified range. ''' </exception> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub ThrowIfNotInRange(Of T As {IComparable(Of T), IConvertible, IEquatable(Of T), IFormattable})(value As T, min As T, max As T, Optional message As String = Nothing, Optional paramName As String = Nothing) If value.CompareTo(min) < 0 OrElse value.CompareTo(max) > 0 Then #Disable Warning CA2208 ' Instantiate argument exceptions correctly Dim ex As New ArgumentOutOfRangeException() #Enable Warning CA2208 ' Instantiate argument exceptions correctly Dim messageField As FieldInfo = Nothing Dim actualValueField As FieldInfo = Nothing Dim paramNameField As FieldInfo = Nothing Dim bindingFlags As BindingFlags = BindingFlags.Instance Or BindingFlags.NonPublic Dim exType As Type = ex.GetType() If actualValueField Is Nothing Then actualValueField = exType.GetField("m_actualValue", bindingFlags) End If Do While exType IsNot Nothing AndAlso ((message IsNot Nothing AndAlso messageField Is Nothing) OrElse (paramName IsNot Nothing AndAlso paramNameField Is Nothing)) If actualValueField Is Nothing Then actualValueField = exType.GetField("m_actualValue", bindingFlags) End If If message IsNot Nothing AndAlso messageField Is Nothing Then messageField = exType.GetField("_message", bindingFlags) End If If paramName IsNot Nothing AndAlso paramNameField Is Nothing Then paramNameField = exType.GetField("m_paramName", bindingFlags) End If exType = exType.BaseType Loop actualValueField?.SetValue(ex, value) messageField?.SetValue(ex, message) paramNameField?.SetValue(ex, paramName) Throw ex End If End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Determines whether the source object is the default value of its type. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' The type of the objectto evaluate. ''' </typeparam> ''' ''' <param name="obj"> ''' The object to evaluate. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' Returns True if the source object is the default value of its type; otherwise, False. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Function IsDefault(Of T)(obj As T) As Boolean Return EqualityComparer(Of T).Default.Equals(obj, Nothing) End Function #End Region End Module End Namespace #End Region
BooleanExtensions.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 09-July-2023 ' *********************************************************************** #Region " Public Members Summary " ' Boolean.ThrowIfTrue(Of TException As Exception)(Opt: TException) ' Boolean.ThrowIfFalse(Of TException As Exception)(Opt: TException) #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.ComponentModel Imports System.Runtime.CompilerServices #End Region #Region " Boolean Extensions " ' ReSharper disable once CheckNamespace Namespace DevCase.Extensions.BooleanExtensions ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Contains custom extension methods to use with <see cref="Boolean"/> datatype. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- <HideModuleName> Public Module BooleanExtensions #Region " Public Extension Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Throws an exception if the source value is true. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim value As Boolean = True ''' ' value.ThrowIfTrue(Of ArgumentException) ''' value.ThrowIfTrue(New ArgumentException(message:="'false' expected.", paramName:=NameOf(value))) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' ''' <typeparam name="TException"> ''' The type of exception to throw. ''' </typeparam> ''' ''' <param name="value"> ''' The value to evaluate. ''' </param> ''' ''' <param name="ex"> ''' Optionally, a instance of the exception to throw if the source <paramref name="value"/> is true. ''' <para></para> ''' If this value is null, a default instance of the exception type will be used. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub ThrowIfTrue(Of TException As Exception)(value As Boolean, Optional ex As TException = Nothing) If value Then If ex Is Nothing Then ex = Activator.CreateInstance(Of TException) End If Throw ex End If End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Throws an exception if the source value is false. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim value As Boolean = False ''' ' value.ThrowIfFalse(Of ArgumentException) ''' value.ThrowIfFalse(New ArgumentException(message:="'true' expected.", paramName:=NameOf(value))) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' ''' <typeparam name="TException"> ''' The type of exception to throw. ''' </typeparam> ''' ''' <param name="value"> ''' The value to evaluate. ''' </param> ''' ''' <param name="ex"> ''' Optionally, a instance of the exception to throw if the source <paramref name="value"/> is false. ''' <para></para> ''' If this value is null, a default instance of the exception type will be used. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub ThrowIfFalse(Of TException As Exception)(value As Boolean, Optional ex As TException = Nothing) If Not value Then If ex Is Nothing Then ex = Activator.CreateInstance(Of TException) End If Throw ex End If End Sub #End Region End Module End Namespace #End Region
|
|
|
En línea
|
@%$& #$ %&#$, ¡hay que decirlo más!.
|
|
|
Elektro Enjuto
|
Un código para forzar la eliminación de un directorio (que tenga el atributo de 'solo lectura') y sus subdirectorios. Y también para forzar la eliminación o el reciclado de un archivo (que tenga el atributo de 'solo lectura'). Nota: este código no modifica los permisos de usuario de archivos ni de carpetas. DirectoryInfoExtensions.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 09-July-2023 ' *********************************************************************** #Region " Public Members Summary " ' DirectoryInfo.ForceDelete() ' DirectoryInfo.ForceDelete(Boolean) #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.ComponentModel Imports System.IO Imports System.Runtime.CompilerServices Imports System.Security Imports DevCase.Win32 #End Region #Region " DirectoryInfo Extensions " ' ReSharper disable once CheckNamespace Namespace DevCase.Extensions.DirectoryInfoExtensions ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Contains custom extension methods to use with <see cref="Global.System.IO.DirectoryInfo"/> type. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- <HideModuleName> Public Module DirectoryInfoExtensions #Region " Public Extension Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Forces the deletion of the specified directory if it is empty, ''' by removing the read-only attribute and deleting it. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="directory"> ''' The directory to be deleted. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Sub ForceDelete(directory As DirectoryInfo) If directory.IsRootVolume Then Throw New InvalidOperationException($"An attempt to delete the root directory of a volume (""{directory.FullName}"").") End If If directory.IsReadOnly Then directory.Attributes = directory.Attributes And Not FileAttributes.ReadOnly End If directory.Delete(recursive:=False) End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Forces the deletion of the specified directory, specifying whether to delete subdirectories and files ''' by removing the read-only attribute and deleting them. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="directory"> ''' The directory to be deleted. ''' </param> ''' ''' <param name="recursive"> ''' True to delete this directory, its subdirectories, and all files; otherwise, False. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <SecuritySafeCritical> Public Sub ForceDelete(directory As DirectoryInfo, recursive As Boolean) If directory.IsRootVolume Then Throw New InvalidOperationException($"An attempt to delete the root directory of a volume (""{directory.FullName}"").") End If If Not recursive AndAlso Not directory.IsEmpty Then ' recursive value is False and the user is attempting to delete ' a directory that is not empty (it needs recursive deletion). ' ' We let the built-in "Delete" method to throw the exception for us. IO.Directory.Delete(directory.FullName, recursive:=False) End If If directory.IsReadOnly Then directory.Attributes = directory.Attributes And Not FileAttributes.ReadOnly End If ' Try recursive deletion. Try For Each subdirectory As DirectoryInfo In directory.GetDirectories("*", SearchOption.AllDirectories) If subdirectory.IsReadOnly Then subdirectory.Attributes = subdirectory.Attributes And Not FileAttributes.ReadOnly End If Next For Each file As FileInfo In directory. GetFiles("*", SearchOption. AllDirectories) file. Attributes = file. Attributes And Not FileAttributes. ReadOnly End If Next directory.Delete(recursive:=True) Catch ex As Exception Throw End Try End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Determines whether the source directory is read-only, ''' i.e., it has the <see cref="FileAttributes.ReadOnly"/> attribute. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="directory"> ''' The directory to check. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' True if the directory is read-only; otherwise, False. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Function IsReadOnly(directory As DirectoryInfo) As Boolean Return (directory.Attributes And FileAttributes.ReadOnly) <> 0 End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Determines whether the <see cref="DirectoryInfo.FullName"/> path ''' in the source directory refers to the root of a volume (e.g "C:\"). ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="directory"> ''' The directory to check. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' True if the <see cref="DirectoryInfo.FullName"/> path ''' in the source directory refers to the root of a volume (e.g "C:\"); ''' otherwise, False. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Function IsRootVolume(directory As DirectoryInfo) As Boolean Return NativeMethods.PathCchIsRoot(directory.FullName) End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Determines whether the source directory is empty (contains no files and no directories). ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="sender"> ''' The source <see cref="Global.System.IO.DirectoryInfo"/>. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' <see langword="True"/> if the directory is empty (contains no files and no directories), ''' otherwise, <see langword="False"/>. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> Public Function IsEmpty(sender As Global.System.IO.DirectoryInfo) As Boolean Return Not sender.EnumerateFileSystemInfos().Any() End Function #End Region End Module End Namespace #End Region
KernelBase.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 01-July-2019 ' *********************************************************************** #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.Runtime.InteropServices Imports System.Security #End Region #Region " P/Invoking " ' ReSharper disable once CheckNamespace Namespace DevCase.Win32.NativeMethods ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Platform Invocation methods (P/Invoke), access unmanaged code. ''' <para></para> ''' KernelBase.dll. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- <HideModuleName> <SuppressUnmanagedCodeSecurity> <CodeAnalysis.SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification:="Required to migrate this code to .NET Core")> <CodeAnalysis.SuppressMessage("Interoperability", "CA1401:P/Invokes should not be visible", Justification:="")> Public Module KernelBase #Region " KernelBase.dll " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Determines whether a path string refers to the root of a volume. ''' <para></para> ''' This function differs from <see cref="NativeMethods.PathIsRoot"/> in that it accepts paths with "\", "\?" and "\?\UNC" prefixes. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' <see href="https://docs.microsoft.com/en-us/windows/desktop/api/pathcch/nf-pathcch-pathcchisroot"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="path"> ''' A pointer to the path string. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' Returns <see langword="True"/> if the specified path is a root, or <see langword="False"/> otherwise. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DllImport("KernelBase.dll", SetLastError:=True, CharSet:=CharSet.Auto, BestFitMapping:=False, ThrowOnUnmappableChar:=True)> Public Function PathCchIsRoot(path As String ) As <MarshalAs(UnmanagedType.Bool)> Boolean End Function #End Region End Module End Namespace #End Region
FileInfoExtensions.vb' *********************************************************************** ' Author : ElektroStudios ' Modified : 10-September-2023 ' *********************************************************************** #Region " Public Members Summary " ' FileInfo.ForceDelete() ' FileInfo.ForceRecycle(UIOption) #End Region #Region " Option Statements " Option Strict On Option Explicit On Option Infer Off #End Region #Region " Imports " Imports System.ComponentModel Imports System.IO Imports System.Runtime.CompilerServices Imports System.Security #End Region #Region " FileInfo Extensions " ' ReSharper disable once CheckNamespace Namespace DevCase.Extensions.FileInfoExtensions ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Contains custom extension methods to use with <see cref="Global.System.IO.FileInfo"/> type. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- <HideModuleName> Public Module FileInfoExtensions #Region " Public Extension Methods " ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Sends the source file to the Recycle Bin. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example. ''' <code language="VB.NET"> ''' Dim file As New FileInfo("C:\File.ext") ''' file.Recycle(UIOption.OnlyErrorDialogs) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="sender"> ''' The source <see cref="Global.System.IO.FileInfo"/>. ''' </param> ''' ''' <param name="dialog"> ''' Specifies which dialog boxes to show when recycling. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <SecuritySafeCritical> Public Sub Recycle(sender As Global.System.IO.FileInfo, dialog As FileIO.UIOption) Microsoft.VisualBasic.FileIO.FileSystem.DeleteFile(sender.FullName, dialog, Microsoft.VisualBasic.FileIO.RecycleOption.SendToRecycleBin, Microsoft.VisualBasic.FileIO.UICancelOption.DoNothing) End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Forces the permanent deletion of the specified file by removing the read-only attribute and deleting it. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="file"> ''' The file to be permanently deleted. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <SecuritySafeCritical> Public Sub ForceDelete (file As FileInfo ) file. Attributes = file. Attributes And Not FileAttributes. ReadOnly End If End Sub ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Forces the recycling of the specified file by removing the read-only attribute and sending it to the recycle bin. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="file"> ''' The file to be permanently deleted. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> <Extension> <EditorBrowsable(EditorBrowsableState.Always)> <SecuritySafeCritical> Public Sub ForceRecycle (file As FileInfo, dialog As FileIO. UIOption) file. Attributes = file. Attributes And Not FileAttributes. ReadOnly End If End Sub #End Region End Module End Namespace #End Region
|
|
|
En línea
|
@%$& #$ %&#$, ¡hay que decirlo más!.
|
|
|
|
Mensajes similares |
|
Asunto |
Iniciado por |
Respuestas |
Vistas |
Último mensaje |
|
|
Librería de Snippets en C/C++
« 1 2 3 4 »
Programación C/C++
|
z3nth10n
|
31
|
25,810
|
2 Agosto 2013, 17:13 pm
por 0xDani
|
|
|
[APORTE] [VBS] Snippets para manipular reglas de bloqueo del firewall de Windows
Scripting
|
Eleкtro
|
1
|
4,067
|
3 Febrero 2014, 20:19 pm
por Eleкtro
|
|
|
Librería de Snippets para Delphi
« 1 2 »
Programación General
|
crack81
|
15
|
21,044
|
25 Marzo 2016, 18:39 pm
por crack81
|
|
|
Una organización en Github para subir, proyectos, snippets y otros?
Sugerencias y dudas sobre el Foro
|
z3nth10n
|
0
|
3,065
|
21 Febrero 2017, 10:47 am
por z3nth10n
|
|
|
índice de la Librería de Snippets para VB.NET !!
.NET (C#, VB.NET, ASP)
|
Eleкtro
|
7
|
6,506
|
4 Julio 2018, 21:35 pm
por Eleкtro
|
|