|
101
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 27 Febrero 2024, 13:38 pm
|
Los dos siguientes métodos sirven para truncar nombres de archivos que superen los 255 caracteres (incluyendo la longitud de la extensión del archivo), acortando la longitud cuanto sea necesario para no sobrepasar dicho límite, y añadiendo puntos suspensivos (…) al final del nombre del archivo. Eso es lo que hace con los nombres de archivo (file name), no con las rutas (file path). En caso de enviar como parámetro a cualquiera de estos dos métodos una ruta de archivo (file path), aparte de realizar los ajustes mencionados con el nombre del archivo y, en caso de que la ruta exceda el límite máximo permitido de 260 caracteres (definido en MAX_PATH), se añadirá el prefijo "\\?\" a la ruta para garantizar la compatibilidad de uso con sistemas NTFS que tengan habilitado el soporte para rutas de longitud extendida (es decir, mayores de 260 caracteres). De esta forma, y además de prevenir el uso de nombres de archivo (file names) inválidos / demasiado largos, además se garantiza que la aplicación que utilice estos métodos para la manipulación o creación de archivos sea "LONG PATH AWARE". Nota: Los métodos han pasado pruebas usando rutas locales (relativas y absolutas). No han sido probados con rutas UNC ni adaptados para ello. Leer con detenimiento el bloque de documentación XML para más información. ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' If needed, truncates the length of the specified file name or full file path ''' to comply with Windows OS maximum file name length of 255 characters ''' (including the file extension length). ''' <para></para> ''' If the file name exceeds this limit, it truncates it and ''' adds a ellipsis (…) at the end of the file name. ''' <para></para> ''' If the path exceeds the MAX_PATH limit (260 characters), ''' it adds the "\\?\" prefix to support extended-length paths. ''' <para></para> ''' See also: <see href="https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation"/> ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' This method is particularly useful when dealing with file names or file paths that might exceed ''' the maximum allowed length, preventing potential errors related to file name length limitations ''' when creating files in the drive. ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="filePath"> ''' The file name or full file path. ''' </param> ''' ''' <param name="maxFileNameLength"> ''' Optional. The maximum character length that the file name can have. ''' Default (and maximum) value is 255. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' The truncated file name or full file path. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Function TruncateLongFilePath(filePath As String, Optional maxFileNameLength As Byte = 255) As String If String.IsNullOrEmpty(filePath) Then Throw New ArgumentNullException(paramName:=NameOf(filePath)) End If If filePath.StartsWith("\\?\", StringComparison.Ordinal) Then filePath = filePath.Substring(4) End If Dim fileInfo As New FileInfo(If(filePath.Length <= 255, filePath, $"\\?\{filePath}")) TruncateLongFilePath(fileInfo, maxFileNameLength) Return fileInfo.FullName End Function ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' If needed, truncates the length of the file name in ''' the source <see cref="FileInfo"/> object to comply with ''' Windows OS maximum file name length of 255 characters ''' (including the file extension length). ''' <para></para> ''' If the file name exceeds this limit, it truncates it and ''' adds a ellipsis (…) at the end of the file name. ''' <para></para> ''' If the path exceeds the MAX_PATH limit (260 characters), ''' it adds the "\\?\" prefix to support extended-length paths. ''' <para></para> ''' See also: <see href="https://learn.microsoft.com/en-us/windows/win32/fileio/maximum-file-path-limitation"/> ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' This method is particularly useful when dealing with file paths that might exceed ''' the maximum allowed length, preventing potential errors related to file name length limitations ''' when creating files in the drive. ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="refFileInfo"> ''' The source <see cref="FileInfo"/> object representing a full file path. ''' <para></para> ''' When this method returns, this object contains the file path with the file name truncated. ''' </param> ''' ''' <param name="maxFileNameLength"> ''' Optional. The maximum character length that the file name can have. ''' Default (and maximum) value is 255. ''' </param> ''' ---------------------------------------------------------------------------------------------------- <DebuggerStepThrough> Public Shared Sub TruncateLongFilePath(ByRef refFileInfo As FileInfo, Optional maxFileNameLength As Byte = 255) If refFileInfo Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(refFileInfo)) End If If maxFileNameLength = 0 Then Throw New ArgumentException("Value must be greater than zero.", paramName:=NameOf(maxFileNameLength)) End If If refFileInfo.Name.Length >= maxFileNameLength Then Dim fileExt As String = refFileInfo.Extension Dim fileName As String = refFileInfo.Name.Substring(0, maxFileNameLength - 1 - fileExt.Length) & $"…{fileExt}" Dim directoryName As String = Path.GetDirectoryName(refFileInfo.FullName) If directoryName.Equals("\\?", StringComparison.Ordinal) Then refFileInfo = New FileInfo($"\\?\{fileName}") ElseIf directoryName.StartsWith("\\?\", StringComparison.Ordinal) Then refFileInfo = New FileInfo(Path.Combine(refFileInfo.DirectoryName, fileName)) Else Dim fullpath As String = Path.Combine(refFileInfo.DirectoryName, fileName) refFileInfo = If(fullpath.Length >= 260, ' MAX_PATH New FileInfo($"\\?\{fullpath}"), New FileInfo(fullpath)) End If End If End Sub
|
|
|
102
|
Programación / .NET (C#, VB.NET, ASP) / Re: Librería de Snippets para VB.NET !! (Compartan aquí sus snippets)
|
en: 27 Febrero 2024, 13:19 pm
|
Convertir un objeto Datatable a una tabla en formato Markdown: ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Converts the elements of a <see cref="DataTable"/> into a Markdown table. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example that shows how to convert a DataTable object to Markdown table. ''' <code language="VB.NET"> ''' Dim dt As New DataTable() ''' dt.Columns.Add("ID", GetType(Integer)) ''' dt.Columns.Add("Name", GetType(String)) ''' dt.Rows.Add(1, "John") ''' dt.Rows.Add(2, "Doe") ''' ''' Dim markdownTable As String = EnumerableToMarkdownTable(dt) ''' Console.WriteLine(markdownTable.ToString()) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <param name="table"> ''' The source <see cref="DataTable"/>. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' A string representing the Markdown table. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Public Shared Function DataTableToMarkdownTable(table As DataTable) As String If table Is Nothing Then Throw New ArgumentNullException(paramName:=NameOf(table)) End If If table.Rows.Count = 0 Then Throw New ArgumentNullException("The source table does not contain any row.", paramName:=NameOf(table)) End If Dim columnNames As IEnumerable(Of String) = table.Columns.Cast(Of DataColumn)().Select(Function(column) column.ColumnName) Dim maxColumnValues As Integer() = columnNames.Select(Function(name) table.AsEnumerable().Max(Function(row) If(row.IsNull(name), 0, row(name).ToString().Length))).ToArray() Dim headerLine As String = "| " & String.Join(" | ", columnNames) & " |" Dim headerDataDividerLine As String = "| " & String.Join(" | ", maxColumnValues.Select(Function(length) New String("-"c, length))) & " |" Dim lines As IEnumerable(Of String) = {headerLine, headerDataDividerLine}.Concat( table.AsEnumerable().Select( Function(row) "| " & String.Join(" | ", columnNames.Select(Function(name, i) If(row.IsNull(name), "".PadRight(maxColumnValues(i)), row(name).ToString().PadRight(maxColumnValues(i))))) & " |" ) ) Return String.Join(Environment.NewLine, lines) End Function
Convertir un objeto IEnumerable a una tabla en formato Markdown: ''' ---------------------------------------------------------------------------------------------------- ''' <summary> ''' Converts the elements of an <see cref="IEnumerable(Of T)"/> into a Markdown table. ''' </summary> ''' ---------------------------------------------------------------------------------------------------- ''' <remarks> ''' Original C# concept: <see href="https://github.com/jpierson/to-markdown-table/blob/develop/src/ToMarkdownTable/LinqMarkdownTableExtensions.cs"/> ''' </remarks> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example that shows how to convert a List(Of String) object to Markdown table. ''' <code language="VB.NET"> ''' Dim list As New List(Of String) ''' list.Add("John") ''' list.Add("Doe") ''' ''' Dim markdownTable As String = EnumerableToMarkdownTable(list) ''' Console.WriteLine(markdownTable.ToString()) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <example> This is a code example that shows how to convert a List of a custom type to Markdown table. ''' <code language="VB.NET"> ''' Public Class TestClass ''' Public Property ID As Integer ''' Public Property Name As String ''' Public Property Age As Integer ''' End Class ''' ''' Dim list As New List(Of TestClass) From { ''' New TestClass() With {.ID = 1, .Name = "John", .Age = 30}, ''' New TestClass() With {.ID = 2, .Name = "Doe" , .Age = 40} ''' } ''' ''' Dim markdownTable As String = EnumerableToMarkdownTable(list) ''' Console.WriteLine(markdownTable.ToString()) ''' </code> ''' </example> ''' ---------------------------------------------------------------------------------------------------- ''' <typeparam name="T"> ''' The type of elements in the collection. ''' </typeparam> ''' ''' <param name="source"> ''' The generic collection to convert into a Markdown table. ''' </param> ''' ---------------------------------------------------------------------------------------------------- ''' <returns> ''' A string representing the Markdown table. ''' </returns> ''' ---------------------------------------------------------------------------------------------------- Public Shared Function EnumerableToMarkdownTable(Of T)(source As IEnumerable(Of T)) As String If source Is Nothing OrElse Not source.Any() Then Throw New ArgumentNullException(paramName:=NameOf(source)) End If If GetType(T).IsPrimitive OrElse GetType(T) = GetType(String) Then Return $"| Items |{Environment.NewLine}| ----- |{Environment.NewLine}{String.Join(Environment.NewLine, source.Select(Function(s) $"| {s} |"))}" End If Dim properties As PropertyInfo() = GetType(T).GetProperties(BindingFlags.Instance Or BindingFlags.Public Or BindingFlags.GetProperty) Dim fields As IEnumerable(Of FieldInfo) = GetType(T).GetRuntimeFields().Where(Function(f) f.IsPublic) Dim gettables As IEnumerable(Of MarkdownColumnData) = Enumerable.Union(properties.Select(Function(p As PropertyInfo) Return New MarkdownColumnData With { .Name = p.Name, .GetValue = Function(obj) p.GetValue(obj), .Type = p.PropertyType } End Function), fields.Select(Function(f As FieldInfo) Return New MarkdownColumnData With { .Name = f.Name, .GetValue = Function(obj) f.GetValue(obj), .Type = f.FieldType } End Function)) Dim maxColumnValues As Integer() = source. Select(Function(x) gettables.Select(Function(p) If(p.GetValue(x)?.ToString()?.Length, 0))). Union({gettables.Select(Function(p) p.Name.Length)}). Aggregate( Enumerable.Repeat(0, gettables.Count()).AsEnumerable(), Function(accumulate, x) accumulate.Zip(x, Function(a, b) System.Math.Max(a, b))). ToArray() Dim columnNames As IEnumerable(Of String) = gettables.Select(Function(p) p.Name) Dim headerLine As String = "| " & String.Join(" | ", columnNames.Select(Function(n, i) n.PadRight(maxColumnValues(i)))) & " |" Dim isNumeric As Func(Of Type, Boolean) = Function(type As Type) Return type = GetType(Byte) OrElse type = GetType(SByte) OrElse type = GetType(UShort) OrElse type = GetType(UInteger) OrElse type = GetType(ULong) OrElse type = GetType(Short) OrElse type = GetType(Integer) OrElse type = GetType(Long) OrElse type = GetType(Decimal) OrElse type = GetType(Double) OrElse type = GetType(Single) End Function Dim rightAlign As Func(Of Type, String) = Function(type As Type) Return If(isNumeric(type), ":", " "c) End Function Dim headerDataDividerLine As String = "| " & String.Join("| ", gettables.Select(Function(g, i) New String("-"c, maxColumnValues(i)) & rightAlign(g.Type))) & "|" Dim lines As IEnumerable(Of String) = { headerLine, headerDataDividerLine }.Union(source. Select(Function(s) Return "| " & String.Join(" | ", gettables.Select(Function(n, i) If(n.GetValue(s)?.ToString(), "").PadRight(maxColumnValues(i)))) & " |" End Function)) Return lines.Aggregate(Function(p, c) p & Environment.NewLine & c) End Function
|
|
|
104
|
Foros Generales / Dudas Generales / Re: TFG Antropología
|
en: 27 Febrero 2024, 06:20 am
|
Quiero presentarme. Soy Emilio, estudiante del Grado de Antropología en la UNED. Estoy haciendo el Trabajo de Fin de Grado sobre la Inteligencia Artificial en los foros de internet y me han pedido que entreviste a usuarios (será totalmente anónimo), para hacer una etnografía. Por favor, ¿alguien puede ayudarme? Sólo se trata de hacerles una serie de preguntas sobre sus motivaciones, sus resultados, problemas éticos y grado de satisfacción con la IA. Si por entrevista entendemos ofrecer una lista con una serie de preguntas por mensaje privado, y que el entrevistado puede tomarse su tiempo de reflexión para responderlas por el mismo método utilizado del mensaje por privado, entonces me ofrezco voluntario. De hecho, y si ese fuese el tipo de entrevista, creo que sería buena idea publicar aquí las preguntas y solicitar que los usuarios interesados te envién un mensaje privado con sus respuestas. Si por lo contrario hablamos de una entrevista con respuestas más inmediatas mediante un servicio de mensajeria, o mediante conversación telefónica, entonces no. En cualquier caso, considero que tengo opiniones muy valiosas para contribuir al debate y el estudio sobre cuestiones relacionadas con la IA, en concreto sobre los modelos de lenguaje generativo como GPT y comenzando por sus (únicas y compartidas) inclinaciones políticas subyacentes derivadas de las decisiones empresariales por parte de sus desarrolladores, que solo sirven para la imposición de límites arbitrarios y absurdos, con una única visión e ideología ( woke) del mundo que nos rodea, y con lo cual impide otorgarle una verdadera "libertad" de expresión a la IA, o al menos impide la capacidad de poder ofrecer respuestas que no estén limitadas por reglas ideológicas predefinidas e impuestas por sus propios creadores. PD: No soy experto en el estudio ni el desarrollo de la IA, sino un consumidor de servicios basados en IA, como por ejemplo ChatGPT y Midjourney. Aténtamente, Elektro.
|
|
|
106
|
Programación / .NET (C#, VB.NET, ASP) / Re: Simular Teclado
|
en: 18 Noviembre 2021, 15:05 pm
|
el codigo de arriba es 100% funcional , ya que funciona a las mil maravillas luego de agregar parametros que me faltaban
espero este post sirva de aporte
Hombre, pero date cuenta que no puede servir de mucho ya que el código está incompleto. Deduzco que está incompleto por que sobrepasaste el límite máximo de caracteres permitidos en un post del foro, un límite demasiado pequeño y del cual me he quejado varias veces en el pasado. Un truco es eliminar lineas de comentario para reducir caracteres, obvio. O también lo podrías compartir en pastebin o servicios similares donde el límite de caracteres es mucho mayor. O en Github gist directamente. Saludos!
|
|
|
107
|
Programación / .NET (C#, VB.NET, ASP) / Re: Juego del tonto(cartas)
|
en: 18 Noviembre 2021, 15:00 pm
|
Yo quiero saber más sobre el "juego del tonto". En serio.
Los nuevos usuarios deben intentar comprender que este foro es multicultural, hay gente de España y de toda latinoamérica.
Te sugiero humildemente que la próxima vez intentes definir mejor las cosas a las que te refieres para asegurar que lo entiendan en el resto del mundo.
Saludos!
|
|
|
110
|
Foros Generales / Foro Libre / Re: La busqueda en google no obtuvo ningún resultado,etc,etc,etc
|
en: 18 Noviembre 2021, 13:05 pm
|
Me has convencido, ya me he cambiado de google a DuckDuckGo , se nota diferencia.
No digas eso, ¡que luego me podrían llamar manipulador!. Si te convences que sea por tu propia experiencia personal. Yo solo he compartido y opinado sobre mi experiencia personal y mi percepción de la realidad. Aunque lo cierto es que es innegable que Google oculta ciertos resultados, lo reconocieron publicamente no recuerdo cuando, pero no es algo que lo hagan de forma oculta. Se supone que en principio ocultan temas de conspiración anti-covid y cosas similares como fake news, creo que lo mismo hacen algunas redes sociales que también lo han reconocido abiertamente. Aunque claro yo desconozco en que parámetros e ideologías exactas se basarán para hacer esas ocultaciones de resultados los tipos de Google, pero temas sobre política también ocultan muchos resultados o tienes que pasar 5 páginas hasta encontrar algo relevante, yo me he dado cuenta de eso muchas veces... en los resultados de artículos donde se cuestione al comunismo, el socialismo y las dictaduras modernas como Cuba y china. Yo también me alegro de verte por aquí. Estaré atento a tus publicaciones, crack. Saludos!
|
|
|
|
|
|
|