Giter Club home page Giter Club logo

betterconsoletables's Introduction

Hi there 👋

I'm Douglas, a Fullstack developer in Oregon, US.

I enjoy writing utilities & tools, and gamedev in my spare time!

Things I code with

React JavaScript Vue C# SQLite MySQL TypeScript Postgresql Python SASS AngularJS MSSQL Redis NPM DotNet ESLint Lua

Things I use

Mapbox Unity Blender GIMP KeePassXC Open Street Map GitKraken Vuetify Bitwarden Quasar Visual Studio Code KDE DrawIO Firefox Visual Studio Obsidian Insomnia

My Homelab Tech

Grafana Portainer Proxmox PFSense Postgresql Ubiquiti Windows Dell TrueNAS Jellyfin Docker InfluxDB Caddy Debian Ubuntu

Interests

SCP Foundation MyAnimeList Steam

betterconsoletables's People

Contributors

bchavez avatar brianmwhite avatar danielabbatt avatar douglasg14b avatar emmekappa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

betterconsoletables's Issues

Error no rows

Hi,
if you create a table without rows the ToString() method returns errors.

 var table = new Table(..);
....
table.AddRows(rows); // rows count = 0
var ret = table.ToString();

System.IndexOutOfRangeException
Index was outside the bounds of the array.
   at BetterConsoleTables.Table.ToString(Int32[] columnLengths)
   at BetterConsoleTables.Table.ToString()

Text wrapping

I've already created a performance friendly text-wrapping method, but the current table generation logic doesn't enable cells to be dynamically sized vertically.

Exception when piping to file

Given a IList data set added to a Table using the From method is written to the console
When the result is piped to a file (e.g. dotnet run > test.txt)
Then an unhandled exception is raised, namely:

Unhandled exception. System.ArgumentOutOfRangeException: Positive number required. (Parameter 'width')
Actual value was -1.
   at System.ConsolePal.SetWindowSize(Int32 width, Int32 height)
   at System.Console.set_WindowWidth(Int32 value)
   at BetterConsoleTables.Table.PadRow(String row)
   at BetterConsoleTables.Table.FormatHeader(Int32[] columnLengths, IList`1 values, Char innerDelimiter, Char outerDelimiter)
   at BetterConsoleTables.Table.ToString(Int32[] columnLengths)
   at BetterConsoleTables.Table.ToString()

Example code:

        public void Present<T>(IList<T> index) where T : IModel
        {
            var table = new Table(TableConfiguration.Markdown());
            table.From(index);
            Console.WriteLine(table.ToString());
        }

[BUG] RPI 4 ARM Linux System.PlatformNotSupportedException "Popcnt.PopCount"

Hello. I was trying to run a project using this library in a RaspberryPi 4, and I get this exception:

Unhandled exception: System.PlatformNotSupportedException: Operation is not supported on this platform.
   at System.Runtime.Intrinsics.X86.Popcnt.PopCount(UInt32 value)
   at BetterConsoles.Colors.Extensions.FormatExtensions.BitCount(FontStyleExt styles)
   at BetterConsoles.Colors.Extensions.FormatExtensions.GetAnsiCodes(IFormat format, Int32 extraArraySize)
   at BetterConsoles.Colors.Extensions.StringExtensions.SetStyle(String value, IFormat format)
   at BetterConsoles.Tables.Table.FormatRow(IList`1 values, IList`1 formats, Int32[] columnLengths, Char& innerDelimiter, Char& outerDelimiter)
   at BetterConsoles.Tables.Table.ToString(Int32[] columnLengths)
   at BetterConsoles.Tables.Table.ToString()
   at Media.Storage.Console.Commands.HealthCommand.Handle(IConsole console, IHost host, String[] labels, ErrorHandler errorHandler, OutputFormat outputFormat, String output, String colSep, String rowSep, Boolean exact) in C:\Users\PedroSilva\source\repos\Media\Media.Storage.Console\Commands\HealthCommand.cs:line 143

It works fine when running on a Windows 10 x64 machine. I think the issue is with this PopCount call here, which I assume is just a performance optimization for platforms that support it. Would it be possible to exclude based on the processor (ARM vs x86) instead of just the framework version?

using BetterConsoles.Core;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
#if NETCOREAPP3_0_OR_GREATER || NET5_0_OR_GREATER
using System.Runtime.Intrinsics.X86;
#endif
using System.Text;
using System.Threading.Tasks;
namespace BetterConsoles.Colors.Extensions
{
public static class FormatExtensions
{
internal static FormatType Merge(this FontStyleExt style, ColorFormatType colorFormat)
{
return (FormatType)((int)style | (int)colorFormat);
}
/// <summary>
/// Gets the hamming weight of the enum.
/// The number of non-0 bits that are set
/// </summary>
public static uint BitCount(this FontStyleExt styles)
{
#if NETCOREAPP3_0_OR_GREATER || NET5_0_OR_GREATER
return Popcnt.PopCount((uint)styles);
#else
uint count = 0;

In the meantime, since I assume this conditional block can just be removed without any functionality being lost, I will just git clone the project and make the changes locally on my end, so it's cool for me. Just wanted to put this here in case other people stumble across the same issue as me.

Thanks ☺️

Crashes in LinqPad :(

Hi there,

I'm trying to use this library in LINQPad to copy/paste a table for some readme docs; but soon as I try to call .ToString on the table, I get an IO exception.

I'm guessing because the library is running in an execution context without the console subsystem, but it would be nice if it ran in a situation like this without a console.

Here's the query I tried to run in LINQPad:

void Main()
{
   Randomizer.Seed = new Random(1337);

   var orderIds = 0;
   var testOrders = new Faker<Order>()
       .RuleFor(o => o.OrderId, f => orderIds++)
       .RuleFor(o => o.Item, f => f.Commerce.Product() )
       .RuleFor(o => o.Quantity, f => f.Random.Number(1, 5));
 
   var orders = testOrders.Generate(5).ToArray();
   orders.Dump();

   var table = new Table("OrderId", "Item", "Quantity");

   
   foreach( var o in orders){
      table.AddRow(o.OrderId, o.Item, o.Quantity);
   }
   table.ToString().Dump();
}

// Define other methods and classes here
public class Order{
   public int OrderId{get;set;}
   public string Item{get;set;}
   public int Quantity{get;set;}
}

And here's the exception stack I'm getting:
LINQPad_2863

Feel free to close the issue if you don't think this is an appropriate execution environment.

Also, I could send a pull request to fix the issue if you think it is appropriate to accept one.

Let me know.

Thanks!
Brian

Multiline support in a Cell

Does this library support formatting cells with multiple lines?

I tried embedding System.Environment.NewLine but that corrupted the table format

Html output

Hi,
Is possible create output html?

Best regards

Print tables side-by-side.

I wonder if there's a way to print two tables side by side rather than one after the other. Maybe via some string manipulation? I would love to hear from you.

Config.UnicodeAlt(); not working

.Config = Config.UnicodeAlt(); Not working

I needed to delete that line and add:
table.Config = TableConfiguration.UnicodeAlt();

Should be changed in documentation

thank you

Issue with Unicode support?

            var table = new Table("Họ tên", "Tuổi", "Giới tính", "Chi phí đồng phục");
            foreach (Student student in students)
            {
                double uniformCost = student.CalculateUniformCost();
                string gender = (student is Female_Student) ? "Nữ" : "Nam";
                table.AddRow(student.name, student.age, gender, uniformCost);
            }
            table.Config = TableConfiguration.Unicode();
            Console.WriteLine(table.ToString());

image

IDK if this is bug of old windows console or your libary have issue with Unicode intergration

Does not work on linux

Unhandled Exception: System.PlatformNotSupportedException: Operation is not supported on this platform.
23:43:06.176    at System.ConsolePal.set_WindowWidth(Int32 value)
23:43:06.176    at BetterConsoleTables.Table.PadRow(String row)
23:43:06.176    at BetterConsoleTables.Table.ToString(Int32[] columnLengths)

header width not quite right

Hi.

I'm currently using version 2.0.3-rc1 of the library and am getting a weird column width issue

image

The code that generates this is

    var decodingtable = new BetterConsoles.Tables.Table(decodingHeaders.ToArray());
    decodingtable.Config = new BetterConsoles.Tables.Configuration.TableConfig(BetterConsoles.Tables.Style.Unicode);
    foreach (var file in decodingValues.Keys)
    {
        var indexMin = decodingValues[file].IndexOf(decodingValues[file].Min());
        var benchmarkValues = decodingValues[file].ConvertAll(v => v.ToString(@"ss\.ffffff"));
        benchmarkValues[indexMin] = benchmarkValues[indexMin].ForegroundColor(System.Drawing.Color.DarkGreen);
        decodingtable.AddRow(
            Array.Empty<string>()
            .Append(file)
            .Concat(benchmarkValues).ToArray());
    }

    Console.Write(decodingtable.ToString());

I am setting the foreground color as DarkGreen for the cell that contains the minimum value in a list/row.

Any ideas as to why this is happening?

Thanks.

Null value are not handled

If I am building a table from a collection of objects, and any of the property values are null, a NullReferenceException is thrown. I should get (null) or something similar in the output.

Weird quirck

Hi @douglasg14b

I found somethig weird in my testing
I compare table printout to expected string in my integration test.
When i run test from Visual Studio all is fine.
When i run test in dotnet test cli command it sqrews up printout.
Speciffically it adds whitespaces and test failes
┌──────┬───────────┐
│ �[38;2;250;250;210m Id �[0m │ �[38;2;0;128;0m Name �[0m │
├──────┼───────────┤
│ �[38;2;250;250;210m1291�[0m │ �[38;2;0;128;0mChristine�[0m │
└──────┴───────────┘
Look at the space after ┌──────┬───────────┐
There id plenty of whitespaces there.
They show up only when test is run thrue dotnet test
Can you comment that ?

[Enhancement] Make formatting for Table.From() path easier

This issue highlighted that this path may be awkward: #28

            var table = new Table(TableConfig.Unicode());
            table.From(statistics.ToArray());
            
            // Enable inner formatting for all columns.
            foreach (var header in table.Headers)
                header.RowsFormat.InnerFormatting = true;
            
            Console.Write(table.ToString());   

Perhaps the From() method could accept some parameters that apply to all columns?

Version 2 (Colors, New API, and More)

Goals/Scope:

  • Individual Cell Formatting
    • Color
    • Alignment
    • [ ] Wrapping
  • Per Column Formatting
    • Color
    • Alignment
  • Maintain performant, non-formatted Table class
  • DI Friendliness (interface usage)
  • Interoperability between a normal and a formatted table
  • Table/Tables centering and Full-Width
    • To support non-console users, this should accept a outputWidth argument

Out of Scope:

  • Table divider/format coloring
    • The ability to color the table syntax itself
  • Value-based formatting
    • Configurable formatting based on the cells value and/or type

This will mostly require a rewrite of much of the Table's working so I can bake in interoperability and compatibility while minimizing code reuse.

Misc Thoughts:

Extracting table through reflection:

  • Use a more fluent-like API for creation from a Type.
    • Table.From<TModel>(TModel tableModel)
      • .From<> returns a config builder for the type
    • .AddColumn(TModel x => x.MyProp, ...config ... )
    • Alternatively: .AddColumn(TModel x => x.MyProp).SetColor(...).AlignContent(...).AddColumn(...) ...

Bugs

  • Adding rows after headers doesn't ensure rows are sized to match column count
  • Adding columns as an array during table creation doesn't setup format matrix

IndexOutOfRangeException when no rows were given

This is the stack trace:

System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at BetterConsoleTables.Table.ToString(Int32[] columnLengths)
   at BetterConsoleTables.Table.ToString()

Table colors

Something I really want to add in are table colors.

This will mean redesigning the table generation logic and configuration from scratch. I'm thinking of leaving the current non-colored table, and having a seperate class for colored tables. This ensures backwards compatibility (if anyone actually uses this library...), and keep the performance benefits of the current implementation.

I'll want to extract common items for the table and config into an interface, to make compatibility a bit simpler.

Buffer size to be too large.

Hi,
what does this mean?

The new console window size would force the console buffer size to be too large.
Parameter name: width
Actual value was 186

Best regards

PadRowInConsole can generate an ArgumentOutOfRangeException when outputting to file instead of console

BetterConsoles.Tables.TableBase.PadRowInConsole can generate an ArgumentOutOfRangeException when outputting to a file using: >> file.txt. This happens when the table is too large horizontally to fit within the console window.

System.ArgumentOutOfRangeException: Positive number required.
Parameter name: width
Actual value was -1.
   at System.Console.SetWindowSize(Int32 width, Int32 height)
   at BetterConsoles.Tables.TableBase`3.PadRowInConsole(String renderedRow)
   at BetterConsoles.Tables.TableBase`3.GenerateDivider(Int32[] columnLengths, Char innerDelimiter, Char divider, Char left, Char right)
   at BetterConsoles.Tables.Table.ToString(Int32[] columnLengths)
   at BetterConsoles.Tables.Table.ToString()

protected string PadRowInConsole(string renderedRow)

Tested on .NET Framework 4.8 and BetterConsoleTables 2.0.4-rc1

[Enhancement] Add pseudo-bold & dim for RGB colors

Right now if you try and bold or dim an RGB colored piece of text, nothing happens.

This is because RGB already sets the intensity and the majority or terminals will not try and change that with the bold sequence.

I could detect that we are using RGB & bold/dim at the same time, and then manually adjust the intensity of the provided RGB.

[Bug] [Hard] Inner/Custom formatting in cells can reset that cells general formatting

If a cell say, starts with a pre-formatted string and that cell has formatting. The cells formatting will be inserted before that custom formatting (At the beginning of the cells string), and if that custom formatting terminates with an ANSI reset, then that cells formatting will be terminated at that reset point.

Example:

�[38;2;220;220;220m�[38;2;204;83;78mSolo�[0m: A Star Wars Story

image

Live table updates

I frequently find myself needing to display real time tables in console apps. Is it possible to update the table in a loop and write row by row instead of building the entire table and printing it all at once?

Version 2 default table text color

Is there a way to change the default text color in version 2? After transitioning from v1 to v2, all table text was colored gray. I know that you can change it by using ColumnBuilder but it seems overly verbose to have to change it for each and every column for both the column header and rows. # #

Column align to right

Hi,
wonderful job. Is it possible to specify in ToString if the column is aligned to the right?

Best regards

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.