Giter Club home page Giter Club logo

towel's Introduction

Gmail   GitHub Profile   Discord Profile   LinkedIn Profile   GitHub Discussions

Repositories

  • Towel 2014+
    A .NET library with data structures, algorithms, mathematics, extensions, and more.
  • dotnet-console-games 2020+
    Game examples implemented as .NET console applications and blazor ports.
  • SevenEngine 2013 [Archived]
    An old college project; a battle simulator in C# using OpenGL (via OpenTK).
Expand...

  • dotnet-blazor-games 2020-2021
    Game examples implemented as .NET blazor components. NOTE: this was my first attempt to get the dotnet-console-games playable on blazor, but I found a better approach to porting the code which is now included in the dotnet-console-games repository rather than a seperate repository.
  • dotnet-benchmarks 2020+
    Benchmark almanac for .NET code.
  • dotnet-winforms-examples 2021+
    Random winforms examples people ask me for help with.
  • rust-console-games 2021+
    Game examples implemented as rust console applications.

Authored Content

Expand...

You can check out more of my gists here.

towel's People

Contributors

65001 avatar azuxirenleadguy avatar thehlopster avatar whiteblackgoose avatar zacharypatten 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 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

towel's Issues

Towel.Mathematics.Symbolics.Expression to Linq Expression

We have the ability to parse System.Linq.Expressions.Expression into Towel.Mathematics.Symbolics.Expression, but the the reverse would be useful as well. Then a Towel.Mathematics.Symbolics.Expression could be compiled into a delegate by first converting it into a System.Linq.Expressions.Expression and then calling CreateDelegate. Since there is also string parsing, you could generate a delegate from mathematical syntax defined in a string. The ability to convert a math expression into a compiled delegate would likely be much more performant than just keeping it as a Towel.Mathematics.Symbolics.Expression.

Exception thrown for non-generic method inside generic class

The exception:

System.InvalidOperationException: Sequence contains no matching element
at System.Linq.ThrowHelper.ThrowNoMatchException()
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source, Func`2 predicate)
at Towel.Meta.GetXmlNameMethodBase(MethodInfo methodInfo, ConstructorInfo constructorInfo)
at Towel.Meta.GetXmlName(MethodInfo methodInfo)
at Towel.Meta.GetDocumentation(MethodInfo methodInfo)

image

This exception happens on Meta.cs, line 846:

methodInfo = methodInfo.DeclaringType.GetGenericTypeDefinition().GetMethods().First(x => x.MetadataToken == methodInfo.MetadataToken);

My method is not generic and the class is, is it still required to update the method info in that case?

image

Structure:

public class GenericClass<TType> 
{
    public void Dispose()
    {
    }
}

The problem is, the MetadataToken for the methods are different, please take a look:

This is the value for the original method info (the one that called GetDocumentation:

image

And this is the value for the one in the call response:

image

@ZacharyPatten please let me know if you need more information, I'm also trying to figure it out on my end.

Enum.Parse accepts integer values (TryParse)

Describe the bug
The Enum.Parse method accepts integer values rather than just enum values from the source code. Towel is using this method underneath Syntax.TryParse. This should be updated to only support enum value strings.

To Reproduce

using System;
using static Towel.Syntax;
static class Program
{
	static void Main()
	{
		ENUM a = (ENUM)Enum.Parse(typeof(ENUM), "111");
		Console.WriteLine(a);
		TryParse("111", out ENUM b); // <- prefer this to fail
		Console.WriteLine(b);
	}
	public enum ENUM { A, B, C, D, }
}

Custom classes for Matrices?

I know you can use user-defined classes for matrices, but I cannot go through it. Let's say I want to implement my float:

public class MyFloat
{
    private float value;
    public MyFloat(float value)
    {
        this.value = value;
    }

    public static MyFloat operator *(MyFloat a, MyFloat b) => new MyFloat(a.value * b.value);
    public static MyFloat operator +(MyFloat a, MyFloat b) => new MyFloat(a.value + b.value);
    public static MyFloat operator /(MyFloat a, MyFloat b) => new MyFloat(a.value / b.value);
    public static MyFloat operator -(MyFloat a, MyFloat b) => new MyFloat(a.value - b.value);
    public static MyFloat Zero => new MyFloat(0);
    public static implicit operator MyFloat(float a) => new MyFloat(a);
    public static implicit operator float(MyFloat a) => a.value;
    public static implicit operator MyFloat(int a) => new MyFloat(a); // this one is needed for Constant<T>.Zero
}

Then I create two matrices and try to multiply them

var a = new Matrix<MyFloat>(3, 5);
for (int i = 0; i < a.Rows; i++)
    for (int j = 0; j < a.Columns; j++)
        a[i, j] = 3;

var b = new Matrix<MyFloat>(5, 6);
for (int i = 0; i < b.Rows; i++)
    for (int j = 0; j < b.Columns; j++)
        b[i, j] = 5;

var c = a  * b;
Console.WriteLine(c);

And then it hangs. I think I'm missing something, but couldn't find it in docs or samples, but how do I make it work?

Join forces?

I notice you're implementing a set of functionality that is very similar to the kinds of things I've implemented in my own libraries - collection stuff including several data structures, geometry, generic math, a few sort functions...

Even Symbolics.Expression seems vaguely related to my work on a universal syntax tree and a standard expression language.

Plus, 15 years ago I implemented units-of-measure-inference support as an add-on to an obscure .NET programming language called boo, and I just haven't had time to do something like that for C# (I am of the opinion that unit checking works better as a built-in language feature rather than as a library, but language features are more difficult to do.)

What would you think about joining forces and merging our libraries? Here's the web site for mine.

Add "bool IsLocalFunction(this MethodInfo methodInfo)" Extension Method

Describe the enhancement
It would be nice to have an extension method on MethodInfo that let's you determine if the method is a local function or not. There aren't any function in .Net for doing this currently (that I'm aware of), and with the ability to have static local functions in C# 8.0, this extension method will have more use.

You can detect local functions based on the "MethodInfo.Name" property. Local functions have names formated like this:
"g__MethodName|0_1" so we can likely just look for the '|' character in the method name.

Purpose of enhancement
The purpose is pretty self explanatory. It would be a useful extension method.

But specifically, it is a good extension method for the "Serialization.StaticDelegateToXml(...)" Method. We don't want to allow serialization of local functions. The name of local functions includes an index, so as you add other local functions, the method name will change making deserialization not possible. Attempting to serialize local functions should throw an exception.

Alternative considerations
I wish there was an alternative to using string analysis on the method name to determine local functions, but I don't think there are any alternatives currently.

Cancellation Token For Path Finding Algorithms

Describe the enhancement
The path finding algorithms need an overload with a cancellation token that allows users to cut off the algorithm (because it could run forever).

Purpose of enhancement
Obvious

Alternative considerations
N/A

`GetDocumentation()` not working on members of generic classes

GetDocumentation() does not work (i.e. returns null) when members reference generic type arguments of the enclosing type.

Repro steps

  1. Create a generic type e.g:
public class MyGenericClass<T> {
    /// <summary>foo method</summary>
    public void Foo(T x) {}
}
  1. Call GetDocumentation() on it:
Assert.IsNotNull(typeof(MyGenericClass<T>).GetMethod("Foo").GetDocumentation());

Expected

GetDocumentation() should return something like "<summary>foo method</summary>" (plus some whitespace around it).

Actual

GetDocumentation() returns null.

Additional context

The root cause of this is that Type.IsGenericParameter is only true for parameters using type arguments of the method, but it is false for parameters using type arguments of the class.

You can verify that here: https://dotnetfiddle.net/belm44

Related question I just posted on StackOverflow: https://stackoverflow.com/questions/61542867/how-to-get-type-genericparameterposition-for-method-parameter-of-class-generic

Implicit Casting Operators From Value Tuple To Measurement Types

Describe the enhancement
Add implicit conversions from value tuples to the measurement types. This will simplify the syntax of creating measurements. Example:

Speed<double> a = (1d, Meters / Seconds);

This will especially help with the syntax of using measurements in vectors and matrices.

Purpose of enhancement
This is just syntax sugar for measurements.

Alternative considerations
N/A

Alter the IDataStructure interface

The IDataStructure interface (and all data structure interfaces) should be altered.

Instead of "void Stepper(Step step)" the methods should instead be "Stepper Stepper()". This should not be a property, because it needs to be consistent with other Stepper retrieval functions that take parameters.

The reason for this is to simplify the syntax of using the Stepper extension methods. C# will not allow you to call delegate extension methods on methods. Methods must be wrapped in a delegate before hand (and the correct type of delegate).

Data Structures

Implement a generic data structures in Towel.Datastructures:

  • B tree
  • Skip List
  • Heap with dynamic priorities HeapArrayMap<TCompare, TEquate, THash>
    • Towel already has a HeapArray<T, TCompare>, but for dynamic priority scenarios a Map<T, int> to look up an index of a T to adjust the priority and sift up/down as necessary.
  • KD Tree
  • runtime ND Omnitree
    • Towel already has omnitrees that have set numbers of dimensions at compile time, but not one that has dynamic dimensions at runtime. This will be much slower than the compile time dimension safe versions, but still nice to have.

Use the compile time Heap in the graph search algorithms

Describe the enhancement
The pathfinding algorithms are currently using the delegate comparing (runtime) version of the Heap data structure. This needs to be switched to the struct comparing (compile time) version for a speed increase.

Purpose of enhancement
optimization

Alter Data Structure Key Functions

The functions which add generic keys on data structures should be altered.

Example (from red black tree):

public T Get(Key key, Compare<T, Key> comparison)

They should be altered to the following:

public T Get(CompareToKnownValue comparison)

This allows querying without the creation of a "key" object, which is much cleaner code.

Matrix Setup Function

There is a lot of duplicate code in the Matrix class for null checking and setting up the ref parameter. This can probably be cleaned up with a setup function before any mathematics.

Data Structures: Delegates -> struct Generic Parameters

Describe the enhancement
The data structures all need to be modified to allow struct generic parameters (where struct, IAction<A>, where struct, IFunc<A, B>) instead of delegates (Action<A>, Func<A, B>).

Purpose of enhancement
This is a massive performance boost because struct generic parameters can be inlined by the JIT but delegates currently are not. Delegates will still be supported via ActionRuntime<A> and FuncRuntime<A, B> if the user prefers clean code over performance.

Data Structures

  • List
  • Stack
  • Queue
  • Heap
  • AVL Tree
  • Red Black Tree
  • Set
  • Map
  • Omnitree
  • GraphMap
  • GraphWeightedMap

Omnitree Subdivision Override Inference

Describe the enhancement
The default subdivision algorithm in the omnitree is median, but I should be able to detect if the generic type of the axis is a numeric (and the default compare is used), then we can change the default to be the mean algorithm instead.

Purpose of enhancement
This would be an optimization for anyone that uses the default options in the omnitree constructor.

Alternative considerations
N/A

MethodInfo.ConvertToCSharpMethodSignature extension method

This was requested in #90.

Will be the same as the existing Type.ConvertToCSharpSource extension methods for types, but it will convert the MethodInfo to the string as it would appear in the source code.

Some Topics Open To Discussion:

  • How to handle local functions?
  • Show/hide access modifier if default? (probably parameterize this or just always include access modifier)
  • Parameterize whether to keep applied generics?

Add Measurement Parsing

Describe the enhancement
Add functionality to parse strings into measurements. For at least the first iteration, we only want to support strict parsing (no unit abbreviations) in the format of the current ToString() results of the measurement types. This should be implemented by building a parsing library via reflection.

Purpose of enhancement
Obvious

Alternative considerations
N/A

inheritdoc

inheritdoc was added to the language. Need to update all method overloads to use it rather than duplicating the XML documentation

Kill the "Code" class

The code class was used for some syntax sugar in older versions of the code and is no longer necessary. It should be removed if it is possible to convert existing code into cleaner solutions.

The "Restart" step status has been commented out and will most likely remain omitted for the first release of the code.

Static fields can be set outside?

For example

public static T Zero
{
    get
    {
        if (!_zero_assigned)
        {
            _zero = Convert<int, T>(0);
            _zero_assigned = true;
        }
 	return _zero;
    }
    set
    {
 	_zero = value;
 	_zero_assigned = true;
    }
}

Why do we need Zero and other constant field to be settable?

Also, to me it should look like:

private static T GetOrDefault<TDefault>(ref T field, ref bool assigned, TDefault value)
{
    if (!assigned)
    {
        field = Convert<TDefault, T>(value);
        assigned = true;
    }
    return field;
}

public static Zero => GetOrDefault(ref _zero, ref _zero_assigned, 0);

[Examples] include examples for both clean and performance patterns

Much of the code in Towel is written two support patterns for both cleanest and most performant code. There needs to be two sets of examples demonstrating both patterns.

For example...

// Clean Pattern
IMap<string, int> map = MapHashLinked.New<string, int>();
// Performance Pattern
struct IntHash : IFunc<int, int> { public int Do(int a) => a; }
struct IntEquate : IFunc<int, int, bool> { public bool Do(int a, int b) => a == b; }

var map = new MapHashLinked<string, int, IntEquate, IntHash>();

Change StepBreak delegates to return a bool rather than StepStatus?

If "StepStatus.Restart" remains omitted, it might be best to kill StepStatus alltogether in favor of bool values for Continue/Break. This could end up being much faster, but may result in more obscure code. Need to research the performance difference before making a decision.

Generic type parameter being removed while using `ConvertToCSharpSource`

While using ConvertToCSharpSource on a parameter's type:

parameterInfo.ParameterType.ConvertToCSharpSource(true)

The type parameter is being excluded:

image

Here's the original code:

Expression<Func<TEntity, bool>> predicate = null

As you can see, TEntity has been removed.

What seems weird is that the Type contains the TEntity reference:

image

And that the same call to a method's return type includes the type parameter:

method.ReturnType.ConvertToCSharpSource(true)

image

@ZacharyPatten I'm filing this as a bug, because it seems like so, but please let me know if there's something wrong I'm doing or expecting...

Thanks.

EDIT: just as an extra info (I'm debugging, trying to find out where the problem is), the generic arguments seem to be all there:

image

Replace T[] with Memory<T> / Span<T>

Memory / Span are simply superior to T[] and cover almost the same uses.
I can't think of a reason to do this, besides that it is work. I'd be happy to PR these changes together with some Benchmarks showing the Performance (and usability) enhancements

Constant<T>.Pi requires GreaterThanOrEqual to be defined

To be precise, in this line

pi = Maximum(pi, Constant<T>.Three);

It's better to first check whether the class has this operator defined, it's obviously unnecessary for this line, but it's called when Constant.One is called.

My solution is presented in #56, but I don't think it fits the code quality requirements

CommandLine: Support Collection Parameters

Describe the enhancement
It would be nice if the CommandLine supported collection arguments. We can dynamically detect if the generic type on the CommandLine.Argument<T> is a collection, and if it is handle it differently than singular arguments.

Example Command: myapp.exe ids "1, 2, 3"

Purpose of enhancement
Simplification.

Alternative considerations
Another option is to add a CommandLine.CollectionArgument<T> or create a wrapper for the generic CommandLine.Argument<Collection<T>> that allow configurable parsing techniques.

Bad check for bounds

this

Matrix<int> a = new int[,]
{
    {6,  1, 1},
    {4, -2, 5},
    {2,  8, 7}
};
Console.WriteLine(a[3, 3]);

leads to exception here in Get

return _matrix[row * Columns + column];

Because you should check it with >=, not >

get
{
    if (row < 0 || row >= /*NOT with >*/ Rows)
    {
        throw new ArgumentOutOfRangeException(nameof(row), row, "!(" + nameof(row) + " >= 0) || !(" + nameof(row) + " < " + nameof(Rows) + ")");
    }
    if (column < 0 || column >= /*NOT with >*/ Columns)
    {
        throw new ArgumentOutOfRangeException(nameof(column), row, "!(" + nameof(column) + " >= 0) || !(" + nameof(column) + " < " + nameof(Columns) + ")");
    }
    return Get(row, column);
}

same with set

Compile Time Delegates For Search Algorithms

Describe the enhancement
The search algorithms all need to be modified to allow compile time delegates in the form of structs that implement the functional interfaces: IAction<A>, IFunc<A, B>, etc. The sorting algorithms already follow this pattern and can be used as an example.

Purpose of enhancement
This will allow for more optimized algorithms if users opt into the compile-time strategy.

Not a bug, just a question.

Hey Zach!

Your code for loading XML comments in Towel is awesome. I don't want to pull in the whole Nuget though. Can I "borrow" this code for our MIT licensed open source blazor component library MudBlazor ?. We are using it to generate the documentation. Of course you'll be fully credited on our credits page and we'll link to this github repo.

Thanks man!

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.