labels – Should empty field captions be specific or generic?

I have an app with basic user profile fields editing functionality. Each field presents the field name, the field value, and an edit button (e.g a pencil).

My question regards what I display on those fields when they haven’t been filled in yet. I don’t care about the exact text inside, but I do care whether this text will be specific for each field or generic.

Example (specific empty field captions):

Name:    No name specified yet     ✎
Age:     No age specified yet      ✎
Address: No address specified yet  ✎

Example (generic empty field captions):

Name:    Not specified yet         ✎
Age:     Not specified yet         ✎
Address: Not specified yet         ✎

Which one is preferable and why?

c# – how to use a generic list for inherited classes?

I am stuck with a design and could use some advise if it is even possible in c# what I want.
To explain, I will put some code here

First, my base classes

public class TableBase
{
}

public class TableRepositoryBase
{
    public virtual void ReadFromDB(List<TableBase> list)
    {
    }
}

from here I want to inherit classed to use along with database tables,
for example user would look like this

public class TableUser : TableBase
{
    public int UserID { get; set; }
    public string FirstNane { get; set; }
    public string LastName { get; set; }
}

public class TableRepositoryUser : TableRepositoryBase
{
    public override void ReadFromDB(List<TableBase> list)
    {
        //base.ReadFromDB(list);

        // write code here to populate the list from the database
        for (int i = 0; i < 10; i++)
        {
            list.Add(new TableUser() { UserID = i, FirstNane = i.ToString(), LastName = i.ToString() });
        }
    }
}

Now I want to use this in a simple test project, so I create a new windows form project, drop a datagridview on it, and then I setup a new datasource like this

enter image description here

So, now I can bind this to the datagridview, no problems there. I can also add the columns in designtime. This all seems ok.
Also, the designer created a BindingSource for me, called tableUserBindingSource

Now I would like to populate the list with values, using the method ReadFromDB
So I try this code

TableRepositoryUser tableRepositoryUser = new TableRepositoryUser();

List<TableUser> list = (List<TableUser>)tableUserBindingSource.List;
tableRepositoryUser.ReadFromDB(list);

But the last line does not compiles, the error is

Severity Code Description Project File Line Suppression State
Error CS1503 Argument 1: cannot convert from
‘System.Collections.Generic.List<ObjectListTest.TableUser>’ to
‘System.Collections.Generic.List<ObjectListTest.TableBase>’ ObjectListTest C:UserssourcereposObjectListTestObjectListTestForm1.cs 65 Active

And this seems clear to me, the class expects a list of TableBase and not of TableUser.

But, TableUser is derived from TableBase so should this not work like this ?
Do I need some generic list or something to get this working ?
If so, an example on how to use a generic list like this (derived classes) would be nice.
I have been looking at examples of generic list for some time but I just cannot find how to use them for this case.

I also found this which suggests that what I want is not possible. But this question is many years old, maybe by know there is some alternative way of doing what I want ?

multiplication – Which is (if any) the generic fastest method to perform modular exponentiation?

After a bit of surfing, I have found that Schönhage–Strassen (without taking in consideration recent optimizations) seems to be the base algorithm to perform the requested operation. Anyways, this algorithm is focused on “raw” multiplication of two integers $a$ and $b$, if a sufficiently large $N$ is chosen (the multiplication is modulus $2^N+1$.

A first question would be: how is this algorithm abstracted to perform exponentiation?

Say, we want to perform $$c^k pmod{n},$$ how we proceed?
A naive approach would be to use the Schönhage–Strassen with $a = c$, $b = c$ and $N$ such that $2^N+1 = n$, as many times as needed (in this case, $k-1$ times). Am I in the good direction? If not, how does it works? Is this algorithm the best one yet known?

design – C# is it acceptable to create a generic class and use an enum as generic type?

Abstract

The case:
Application contains a lot of views with a list of data. Data views (lists of records) have pagination, filtering and sorting options.
The user must be able to select a “sorting property” to sort the shown data by a specific property.
The user-interface contains a selection control (ComboBox) the user can interact with. The combobox options represent the sorting properties that are currently available in the displayed data.
It’s a very standard/common case.

Example image:

enter image description here

The image shows a typical datalist view. The bar above the data grid shows the ComboBox.
I wanted to create a class structure to design a general pagination solution.
One part of my code is as follows:

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;

enum SortProperty {
    Id, Name, Date, Balance
}
    

public class Program
{
    public static void Main()
    {
        Program main = new Program();
        main.Test();
    }
    
    private void Test() {
        
        ObservableCollection<SortPropertyOption<SortProperty>> sortingOptions = new ObservableCollection<SortPropertyOption<SortProperty>>();
        
        // The outside world can create options and use its own data type (class generic type) to represent the
        // property in the data. In this case an enum is used by the outside world.
        // but it could also be a string (maybe a database field name) or an integer, etc...
        sortingOptions.Add(new SortPropertyOption<SortProperty>(SortProperty.Name, "Name"));
        sortingOptions.Add(new SortPropertyOption<SortProperty>(SortProperty.Date, "Date"));
        sortingOptions.Add(new SortPropertyOption<SortProperty>(SortProperty.Balance, "Balance"));
        
        // SortPropertyOption collection could be passed to the view (by a binding or something).
        // When an option is selected in the view, the SortPropertyOption.OptionValue can be accessed by the using-code (outside world)
        // which then knows what to do.
    }
}

public class SortPropertyOption<T> {
    
    private T _optionValue;
    private string _text;
    
    public T OptionValue { get { return _optionValue; } }
    public string Text { get { return _text; } }
    
    public SortPropertyOption(T optionValue, string text) {
        
        _optionValue = optionValue;
        _text = text;
    }
}

The reason for the generic in SortPropertyOption is that the outside world that uses my classes, can use its own data type for identifying the property/column in the dataset. The datalayer can provide an enum or strings that say what properties are available in the data.

In my question, an enum is used as generic type for SortPropertyOption. Is that acceptable?

Also, a .NET Fiddle link: https://dotnetfiddle.net/vyVWaf

ag.algebraic geometry – What is a generic pencil?

In Voisin book “Hodge theory and Complex Algebraic Geometry 2”. There is the following corollary

Corollary 2.10. If $Xsubset mathbb{P}^N$ is a smooth projective complex variety, then a generic pencil $(X_t)_{tin mathbb{P}^1 }$ of hyperplane sections of $X$ is a Lefschetz pencil.

Then, there is no more information about “generic pencil” in the book. I would like to know how a generic pencil is defined.

Thank you!

swift – Weak reference implementing a (generic) protocol

I want to create an array of weak references implementing a protocol for observable functionality.
If possible this protocol should have an associated type, so I would not need to create identical ones for each type.

However in Swift 4 this does not seem to work, what I want is basically this:


protocol DelegateBase: AnyObject {
    associatedtype Item
    func onDataUpdated(data: (Item))
}

protocol Delegate : DelegateBase where Item == Int {
    // Will have func onDataUpdated(data: (Int))
}

// T should be a class implementing Delegate, but cannot find a way to 
// define T in a way that the Swift compiler accepts it
class WeakListener<T> {
    weak var listener : T?

    init(listener: T) {
        self.listener = listener
    }
}

class Implementation {
    val listeners = (WeakListener<Delegate>)()
}

If I define everything as non-generic I can make it work, but I would like the convenience of copy pasting a concrete version of DelegateBase for each type I want to support.

// This works but is clunky

protocol DelegateA {
    func onDataUpdated(data: (Int))
}
// DelegateB with type Double, DelegateC with type X

class WeakListenerA {
    weak var listener : DelegateA?

    init(listener: DelegateA) {
        self.listener = listener
    }
}
// WeakListenerB with type Double, WeakListenerC with type X

class ImplementationA {
    val listeners = (WeakListenerA)()
}
// ImplementationB with type Double, ImplementationC with type X

Is there a finite generic magma?

Does there exist a finite set $S$ with a single binary operation $*$, where the only equational identities that hold are of the form $t=t$ for some term $t$?

Generic converter for plain java objects

As part of my recent transition from c# to java i decided to write a small converter implementation to translate DTO objects to entities. I’m fully aware of already existing solutions, especially in spring boot, but decieded to create this class as part of my learning process to write projects in java.

General note: I’ve used lombok to not write get and set methods by hand

The main goal for me was to create a simple to use class to convert DTOs or input objects into entities by mapping the fields between them. Ideally the implementation would allow me to extend the base class to implement special converters while still using the basic reflection mapping.

Main implementation

public class Converter<F, T> {
    private final static String SET_METHOD_PREFIX = "set";
    private final static String GET_METHOD_PREFIX = "get";
    
    private final List<Field> fieldsOfF;
    private final List<Field> fieldsOfT;

    private final List<Method> methodsOfF;
    private final List<Method> methodsOfT;

    private final Class<T> classToType;
    private final Class<F> classFromType;

    public Converter(Class<F> fromClass, Class<T> toClass) {
        this.classToType = toClass;
        this.classFromType = fromClass;

        this.fieldsOfF = getAllFields(fromClass);
        this.fieldsOfT = getAllFields(toClass);

        this.methodsOfF = getAllMethods(fromClass);
        this.methodsOfT = getAllMethods(toClass);
    }

    public T convert(F object) throws ConverterException {
        T instance = getInstance(classToType);

        for (Field item : fieldsOfF) {
            setValue(instance, getValue(object, item, methodsOfF), item, fieldsOfT, methodsOfT);
        }

        return instance;
    }

    public F convertBack(T object) throws ConverterException {
        F instance = getInstance(classFromType);

        for (Field item : fieldsOfT) {
            setValue(instance, getValue(object, item, methodsOfT), item, fieldsOfF, methodsOfF);
        }

        return instance;
    }

    private Object getValue(Object object, Field field, List<Method> methods) throws ConverterException {
        Optional<Method> optionalMethod;
        Object value = null;
        if (field.canAccess(object)) {
            try {
                value = field.get(object);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();

                throw new ConverterException(e.getMessage(), e);
            }
        } else {
            optionalMethod = methods.stream().filter(
                    x -> x.getName().equals((GET_METHOD_PREFIX + capitalizeFirstChar(field.getName()))) && x.canAccess(object))
                    .findFirst();
            if (optionalMethod.isPresent()) {
                try {
                    value = optionalMethod.get().invoke(object);
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    e.printStackTrace();

                    throw new ConverterException(e.getMessage(), e);
                }
            }
        }
        return value;
    }

    private void setValue(Object instance, Object value, Field item, List<Field> fields, List<Method> methods)
            throws ConverterException {
        Optional<Field> optionalField = fields.stream().filter(
                x -> x.getName().equals(item.getName()) && x.getType().equals(item.getType()) && x.canAccess(instance))
                .findFirst();
        if (optionalField.isPresent()) {
            try {
                optionalField.get().set(instance, value);
            } catch (IllegalArgumentException | IllegalAccessException e) {
                e.printStackTrace();
            }
        } else {
            Optional<Method> optionalMethod = methods.stream().filter(
                    x -> x.getName().equals((SET_METHOD_PREFIX + capitalizeFirstChar(item.getName()))) && x.canAccess(instance))
                    .findFirst();
            if (value != null) {
                if (optionalMethod.isPresent() && optionalMethod.get().getParameterCount() == 1
                        && optionalMethod.get().getParameters()(0).getType().isAssignableFrom(value.getClass())) {
                    try {
                        optionalMethod.get().invoke(instance, value);
                    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                        e.printStackTrace();

                        throw new ConverterException(e.getMessage(), e);
                    }
                }
            }
        }
    }

    private <E> E getInstance(Class<E> instanceClass) throws ConverterException {
        E instance = null;
        try {
            instance = instanceClass.getDeclaredConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException
                | NoSuchMethodException | SecurityException e) {
            e.printStackTrace();

            throw new ConverterException(e.getMessage(), e);
        }
        return instance;
    }

    private <E> List<Field> getAllFields(Class<E> clazz) {
        if (clazz == null) {
            return Collections.emptyList();
        }

        List<Field> result = new ArrayList<>(getAllFields(clazz.getSuperclass()));
        List<Field> filteredFields = Arrays.stream(clazz.getDeclaredFields()).collect(Collectors.toList());
        result.addAll(filteredFields);
        return result;
    }

    private <E> List<Method> getAllMethods(Class<E> clazz) {
        if (clazz == null) {
            return Collections.emptyList();
        }

        List<Method> result = new ArrayList<>(getAllMethods(clazz.getSuperclass()));
        List<Method> filteredFields = Arrays.stream(clazz.getDeclaredMethods()).collect(Collectors.toList());
        result.addAll(filteredFields);
        return result;
    }

    private String capitalizeFirstChar(String value) {
        return value.substring(0, 1).toUpperCase() + value.substring(1);
    }
}

The main methods are convert(T object) and convertBack(F object). I’ve tried to keep the usage as simple as possible without any additional methods or setup steps.

Specific implementation

public class SampleEntityConverter extends Converter<SampleDTO, SampleEntity> {

    private Converter<SampleNestedDTO, SampleNestedEntity> nestedConverter = new Converter<>(SampleNestedDTO.class,
            SampleNestedEntity.class);

    public SampleEntityConverter() {
        super(SampleDTO.class, SampleEntity.class);
    }

    @Override
    public SampleEntity convert(SampleDTO object) throws ConverterException {
        SampleEntity instance = super.convert(object);
        if (object.nested != null) {
            instance.setNested(nestedConverter.convert(object.nested));
        }

        return instance;
    }

    @Override
    public SampleDTO convertBack(SampleEntity object) throws ConverterException {
        SampleDTO instance = super.convertBack(object);
        if (object.getNested() != null) {
            instance.nested = nestedConverter.convertBack(object.getNested());
        }
        return instance;
    }
}

Sample DTO and entity classes

The SampleDTO is a very simple DTO object with a abstract class as base to check if my implementation will handle inherited classes correctly

@ToString
public class SampleDTO extends AuditedDTO {
    public String field1;
    public Integer field2;
    public Boolean field3;
    public Instant field4;
    
    public SampleNestedDTO nested;
    
    public List<String> list1 = new ArrayList<>();
    
    public Map<String, Instant> map1 = new HashMap<>();
    
    public SampleDTO() {
        this.created = Instant.now();
        this.createdBy = "Test";
    }
}
@ToString
public class SampleNestedDTO {
    public String nestedField1;
    public Integer nestedField2;
    public Boolean nestedField3;
    public Instant nestedField4;
}
public abstract class AuditedDTO {
    public Instant created;
    public String createdBy;
    public Instant lastUpdate;
    public String lastUpdatedBy;
}

The SampleEntity object uses only get and set methods instead of public member variables to match our implementation of hiberante entities.

@ToString
public class SampleEntity extends AuditedEntity {
    @Getter
    @Setter
    private String field1;
    
    @Getter
    @Setter
    private Integer field2;
    
    @Getter
    @Setter
    private Boolean field3;
    
    @Getter
    @Setter
    private Instant field4;
    
    @Getter
    @Setter
    private SampleNestedEntity nested;
    
    @Getter
    @Setter
    private List<String> list1 = new ArrayList<>();
    
    @Getter
    @Setter
    private Map<String, Instant> map1 = new HashMap<>();
}
@ToString
public class SampleNestedEntity {
    @Getter
    @Setter
    private String nestedField1;
    
    @Getter
    @Setter
    private Integer nestedField2;
    
    @Getter
    @Setter
    private Boolean nestedField3;
    
    @Getter
    @Setter
    private Instant nestedField4;
}
@ToString
public abstract class AuditedEntity {
    @Getter
    @Setter
    private Instant created;

    @Getter
    @Setter
    private String createdBy;

    @Getter
    @Setter
    private Instant lastUpdate;

    @Getter
    @Setter
    private String lastUpdatedBy;
}

Usage

Now with my implementation of the converter simply using it as

Converter<SampleDTO, SampleEntity> converter = new Converter<>(SampleDTO.class, SampleEntity.class);

SampleDTO sampleDto = new SampleDTO();
sampleDto.field1 = "Sample String";
sampleDto.field2 = 1;
sampleDto.field3 = true;
sampleDto.field4 = Instant.now();
sampleDto.list1.add("String 1");
sampleDto.list1.add("String 2");
sampleDto.list1.add("String 3");
sampleDto.map1.put("Now", Instant.now());
sampleDto.map1.put("Tomorrow", Instant.now().plus(1, ChronoUnit.DAYS));
        
sampleDto.nested = new SampleNestedDTO();
sampleDto.nested.nestedField1 = "Sample nested String";
sampleDto.nested.nestedField2 = 2;
sampleDto.nested.nestedField3 = false;
sampleDto.nested.nestedField4 = Instant.now();

SampleEntity sampleEntity = converter.convert(sampleDto);
// sampleEntity.getNested() will be null and not converted with the baisc converter

will convert the sampleDto but this will not convert nested objects as it can only handle simple datatypes and collections. The special implementation as SampleEntityConverter will handle nested entites.

SampleEntityConverter converter = new SampleEntityConverter();

SampleDTO sampleDto = new SampleDTO();
sampleDto.field1 = "Sample String";
sampleDto.field2 = 1;
sampleDto.field3 = true;
sampleDto.field4 = Instant.now();
sampleDto.list1.add("String 1");
sampleDto.list1.add("String 2");
sampleDto.list1.add("String 3");
sampleDto.map1.put("Now", Instant.now());
sampleDto.map1.put("Tomorrow", Instant.now().plus(1, ChronoUnit.DAYS));
        
sampleDto.nested = new SampleNestedDTO();
sampleDto.nested.nestedField1 = "Sample nested String";
sampleDto.nested.nestedField2 = 2;
sampleDto.nested.nestedField3 = false;
sampleDto.nested.nestedField4 = Instant.now();

SampleEntity sampleEntity = converter.convert(sampleDto);
// sampleEntity.getNested() will be converted using the SampleEntityConverter

I’ve added a simple exception class ConverterException as

public class ConverterException extends Exception {

    private static final long serialVersionUID = -2846211687408157933L;
    
    public ConverterException(String message, Throwable cause) {
        super(message, cause);
    }

}

because exceptions should only occur during the design and writing of classes and not at production use runtime. This will make the handling of the different exceptions a bit simpler and keep the resulting code cleaner as there is only one type of exception to catch.

SampleEntity sampleEntity = null;
try {
    sampleEntity = converter.convert(sampleDto);
} catch (ConverterException e) {
    // handle exception
    e.printStackTrace();
}

Questions

Now to my questions:

  1. Are there any general improvements to my code in regards to naming conventions, type usage or any general errors I’ve made when using my knowledge of c# on java.
  2. Regarding the constructor methods of the Converter<F, T>, could this be a potential cause for performance problems when reading larger classes or deep inhiterances?
  3. Am I using the Field and Method methods correctly to check if a field can be set or a method can be called?
  4. Are there any caveats to use super.convert() in the specific implentations?

Thanks

google – Is it better for SEO to use generic meta data that is the same for multiple pages or to omit the meta data?

Our company has developed software to create and publish posts automatically on a WordPress site. Since the posts are published automatically and the images are also saved automatically, is it good SEO practice to use generic data for each post?

For example, if I have this data for every image:

        title: 'My awesome image',
        alt_text: 'an image of something awesome',
        caption: 'This is the caption text',
        description: 'More explanatory information'.

Is this wrong? What would be the right thing to do if I don’t have the budget to write custom data for each image?
Is it better for SEO if we don’t post generic data and instead remove the fields?

google – SEO post images generic data, no code only opinions

Our company has developed a sw to create and publish posts automatically on a wordpress site. My question is since the posts are published automatically and the images are also saved automatically, is there a good SEO practice for the generic data of a post?
Let me explain with an example, if I have saved this data for each image:

        title: 'My awesome image',
        alt_text: 'an image of something awesome',
        caption: 'This is the caption text',
        description: 'More explanatory information'.

Is this wrong? What would be the right thing to do if I didn’t have the possibility to have an operator write the custom data for each image?
For istance is better for SEO don’t post generic data and remove additional fields?

Thank you all