jeudi 31 octobre 2019

Using application classes as utilities in unit tests

This is a question about best practices for unit tests. Let's say I have a ClassA that does some object transforms (from CSVs to Java beans, using external library). Then I have ClassB that needs these transformed Java beans to execute a calculation. When writing a unit test for ClassB, is it acceptable to use ClassA's transform method to get these transformed bean objects? In other words, use an application class as utility in unit test.

The other option would be to write a util test method which would have same code as ClassA (the transformation is done using an external library, so it's easy to use it in both application class and test utility class)

Android Client using Rest-API: Best way to share URLs between Fragments

I have a Android App that gets its data from a REST-API. The REST-API gives me urls to other subpages of the REST-API. Now, I need to share these urls between different fragments (following MVVM single activity architecture).

I've come up with different solutions:

• Create static variables that save the urls in either the Single Activity or in a static Helperclass

• Save them in SharedPreferences

• Share them via SharedViewModels

Out of these 3 the first one is my favorite since it's not using files like SharedPreferences and not a overkill like SharedViewModels, however, I have the feeling that static url variables might be bad practice. So my question is, which is the best way to solve this issue.

Template method pattern in java

I have assignment in java ,I need help please. I tried to solve it but I have some problem that can't understand them.

Assignment is: In this exercise, use the Template method pattern to define an abstract class Filter with a public method filter (the template method) that calls the method accept (the hook method) that can be implemented in different ways in the different concrete classes. Write a test program by extending the class Filter and defining accept so that only strings of at most three characters are accepted.

enter code here

/*================= Abstract filter class ===================*/

public abstract class Filter<T> {
public abstract T[] filter(T[] list);
public abstract boolean accept(T val);
}

  /*=====================Filter Test class====================*/
   public class FilterTest<T> extends Filter<T>{

   private int capacity = 0;
   public FilterTest(int cap)
   {
   this.capacity = cap;
   }

 @Override
 public T[] filter(T[] list1) {

 @SuppressWarnings("unchecked")
 T[] finalList = (T[])    
     Array.newInstance
 (list1.getClass().getComponentType(), capacity);
  int counter = 0;
 for(T t : list1){
  if(accept(t)){
  finalList[counter] = t;
 counter++;
  }
 }
 return finalList;
}

public void printArray(T[] list2){
for(int i = 0; i < list2.length; i++){
  if(list2[i] != null){
     System.out.print(list2[i] + " ");
     }
 }
     System.out.println();
     }

@Override
public boolean accept(T val) {
if(String.valueOf(val).length() > 0 && String.valueOf(val)
.length()<= 3)
  return true;
  else
  return false;
  }


public static void main(String[]args){
FilterTest<String> filterTest = new FilterTest<String>(8);
String[] lists = {"Hi","here", "is", "the", "AOOP",
"course", "at", "University"};

System.out.print("My original list is: ");
filterTest.printArray(lists);

System.out.print(" The filtered list is: ");
String[] filteredList = filterTest.filter(lists);
filterTest.printArray(filteredList);
 }
 }

Here is comment from my teacher: "not correct, only the accept method should be abstract in the Filter class, the filter method should be already implemented in the Filter class and not be abstract all implementation will be the same, only the accept method changes for different filters)".

I don't understand what should I do now, how the code will be correct. help please, Thanks

What is the best practice: business logic in Verticles or separate?

Recently I started programming in Vert.x with Kotlin, the question is generic for any technology with which we use the Vertx toolkit. I created my verticles, but in these I have business logic, and I would like to know what is the best practice:

1.Separate the logic to an independent class, instantiate it in the verticle and execute its operations, leaving only the verticle to receive and deliver the messages to the eventBus.

2.Implement whenever possible the logic in the same verticle.

Below I show an example of how the code has been, but as you can see is the logic within the verticle itself. It is well like this from the design point of view or you should take it out to an independent class and leave that verticle only for the operations of receiving and sending messages on the bus

class MyAPIAgentImpl(vertx: Vertx) : CoroutineVerticle() {

    var httpClient = HttpClient(vertx)
    var apiConfig: JsonObject = Config.get().getJsonObject("myapi")

override suspend fun start() {
      vertx.eventBus().consumer<JsonObject>(BusChannel.MY_API_CHANNEL) {
        message -> launch { message.reply(findElem(message.body().getLong("Id"),
        message.body().getString("countryCode"))) }
      }
  }

  override suspend fun findElem(Id: Long, countryCode: String): String {

      var hashMap = HashMap<String, String>()
      hashMap.put("Accept", "*/*")
      hashMap.put("Authorization", "Bearer XXXX")

      val baseUrl: String = apiConfig.get("apiBaseUrl")
      val port: Int = apiConfig.get("apiPort")
      val apiRelativeUrl: String = apiConfig.get("apiRelativeUrl")

      val resp: HttpResponse = httpClient.GET(String.format(baseUrl, countryCode), port,
        String.format(apiRelativeUrl, Id), hashMap, apiConfig.getLong("requestTimeout"))

    if (resp.status == HttpCode.OK) {
        return resp.message.get("msg")
      } else {
        logger.error("[HTTP CALL] My API response with error status code: ${resp.status}")
        throw ApiException(ErrorMessage(-1, resp.status, "Error calling external API"))
      }
  }

  companion object {
    private val logger = LoggerFactory.getLogger(MyAPIAgentImpl::class.java)
  }
}

I would like to know your comments and experiences in this regard in the design of applications with Vertx

mercredi 30 octobre 2019

Java's DAO definition of Factory Method

I was reading today, again after many years, the article Core J2EE Patterns - Data Access Object and came across these two definitions of DAO implementations, the first one using Factory Method and the second one using Abstract Factory. Although the article claims the first example to be using factory method, I've started to think that it could just as well be defined as an abstract factory with a single concrete factory implementation.

Example Factory method:

factory method

Example Abstract Factory:

abstract factory

Going back to GoF, we can find arguments as to why it is an abstract factory:

  • Abstract factory creates a factory of related products, which would be the single concrete implementation of the first example.
  • Abstract factory is used, among other things, to create gui toolkit factories for different look and feels that would return different components to be worked on by other classes. These components are closely related. These would be the concrete dao factory implementation itself, which has methods for creating the individual products/daos.

I have also seen many discussions explaining the difference between inheritance (factory method) and composition (abstract factory) but I think that distinction is very ambiguous. In GoF we read that one of the two ways to use factory methods is to Connects parallel class hierarchies which means allowing classes other than the creator (class that implements the factory method) to call these factory methods.

If some class is calling a factory method from another class, using the interface exported by a creator, that is the same thing as calling a method from an abstract factory. Both examples use inheritance to benefit from the polymorfism and both are creating concrete produtcts, based on some abstract product interface. In essence, that means the same UML diagram could describe both patterns.

So in the end, I think it all comes down to whether I'm defining DAOFactory as a creator with multiple factory operations, in the case of factory method or an abstract factory in the case of an abstract factory, which have the following definitions in GoF:

factory method:

- constructor

* declares the factory method, which returns an object of type Product.
Creator may also define a default implementation of the factory
method that returns a default ConcreteProduct object.
* may call the factory method to create a Product object. 

abstract factory:

- abstract factory

declares an interface for operations that create abstract product
objects

So to decide whether the pattern is a factory method or an abstract factory, I need more than just the UML, but the requirement of the application to define what pattern best fits the description of the requirement. And so when I did that, it sounded like abstract factory fit better both examples from Oracle. First because all daos are tightly coupled. I could share the same connection between them right from inside DaoFactory of even share a transaction.

I don't think calling the first example factory method just because there was only one implementation is justification enough.

Have I missed something? Is my view of both patterns up to date or has it changed since GoF?

API calling in MVC, MVP, MVVM and VIPER design patterns

Swift - Where to put API calling in MVC, MVP, MVVM and VIPER design patterns?

What is a good Dart/Flutter pattern for creating multi widget object library?

Since Dart/Flutter uses a composition style approach to building widgets (coupling that with how scoped model operates) what is a good pattern for developing a library of objects that encapsulate widgets?

Assume you have an application that allows you to display a list of objects within a list view that each have their own way displaying their information, but all have the same approach for doing so.

Consider the following pseudo-code, which takes the approach of encapsulating all of the required widgets and other such properties/methods needed for each object to follow.

    abstract class Vehicle {
        int type;
        String name;
        Widget listWidget
        Widget editWidget
        Widget settingsWidget
    }

    class Truck extends Vehicle {
        type = 1
        name = "Truck"
        listWidget = ... My truck widget for within lists...
        editWidget = ... My truck edit widget ...
        settingsWidget = ... My truck settings display ...
    }

    class Car extends Vehicle {
        type = 1
        name = "Car"
        listWidget = ... My car widget for within lists...
        editWidget = ... My car edit widget ...
        settingsWidget = ... My car settings display ...
    }

With that approach, then I would have to create each vehicle type and follow the abstract api pattern and not worry about how it is rendered.

When it comes to displaying the vehicles within a list (ListView for example), this approach would allows the object itself to dictate how it is rendered in that list, and it could be unique to each type of vehicle.

For example:

    Container(
        child: new ListView.builder(
            itemCount: items.length,
            itemBuilder: (BuildContext ctxt, int index) {
                return items[index].listWidget;
            }
        )
    )

Is this a valid Dart/Flutter way of accomplishing this or is there a better pattern that should be followed?

Am I violating Dart recommended coding patterns in that each widget would control it's own display?

The idea behind this is that if a settings panel needed to be formatted differently depending on the type of vehicle, I could do it, rather than trying to figure out how to create a common display pattern for all widgets.

Thoughts?

Read configuration in to a collection of base class objects as child class objects

I have .Net core application, which is using the appsettigs.json file for holding configuration. I need to load a configuration section into a collection, without iterating through them. I know I can use Bind() method to bind the collection into a collection of same type. But here I am trying to get objects of the child class type in the collection, instead of base class type.

"Sections": [
{
  "Name": "Section 1",
  "Type":"type1"

},
{
  "Name": "Section 2",
  "Type":"type2"

},
{
  "Name": "Section 3",
  "Type":"type1"

},
{
  "Name": "Section 4",
  "Type":"type1"

},
{
  "Name": "Section 5",
  "Type":"type2"

}]

I am using the below code to read the config file.

var configBuilder = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json");

        var Configuration = configBuilder.Build();

I know I can use Configuration.Bind()

The classes are

    Public abstract class BaseSection:ISection
    {
    public string Name;
    ..
    }


Public class Type1:BaseSection
{
public string Name;
..
}

Public class Type2:BaseSection
{
public string Name;
..
}

I need to read the configuration from the appsettings.json file to List such that the the for entry in config file with "type=type1" will have type in the collection Type1 obejct and "type=type2" will have type in the collection Type2 obejct.

So my collection from the above config entries should have

[
    Object Of Type1
    Object Of Type2
    Object Of Type1
    Object Of Type1
    Object Of Type2
]

I don't want to read the data once and then type cast it.

Please share views and inputs. Thanks in advance.

Regex: how to return a housenumber value based on a given housenumber and postalcode

Please look at the text example below

Company X
                                                                                                              Fakestreet 97,
This an invoice. Please pay :)                                                                            3000 AB Fakecity

Costs: € 97,-

I am working on a regex pattern (in R) which returns a matching housenumber (97) when a given postal code (3000 AB) matches as well. And not the amount (€97,-)

My current pattern for this match is: \b(97){1}\b((.|\r\n|\r|\n|))*(3000 AB)

Please look at the text example below. At has lot's of spaces between the words. I only want to return the '97' number from 'fakestreet'. But only if a given postal matches as well (3000 AB).

What does my pattern has to look like? My current pattern is giving me problems:

1) It 'goes on' endlessly and won't stop. This probably is because of the ((.|\r\n|\r|\n|))+ pattern.

2) It will return the €97,- amount. I don't want that. Just the housenumber

3) It returns all characters between the postal code and the matched housenumber. I don't want that to happen.

My current pattern for this match is: \b(97){1}\b((.|\r\n|\r|\n|))*(3000 AB)

A breakdown of the 'logic'

find and match the postal code

  • (3000 AB)

Find a specific matching housenr (and no other number), single match and surrounded by 'wordboundaries

  • \b(97){1}\b

'bridge' the spaces between the postalcode and the housenumber found. Right now this returns all characters matched.

  • ((.|\r\n|\r|\n|))*

Any help is much appreciated!

How to replace singleton design pattern

I have my own simple Timer implementation, when a timer is created it register itself at a TimerHandler,

Timer::Timer()
: tick_counter_(0),
  target_tick_(0),
  increment_(false),
  started_(false),
  elapsed_(false) {
  handlers::TimerHandler::RegisterTimer(*this);
}

The function RegisterTimer() is static as you can see and TimerHandler is implemented as a singleton.

As you all known this creates problems at unit testing! Testing the Timer class and the TimerHandler class can be ok and not really hard. But when testing other classes which uses Timer it sometimes become tricky.

I want to get some ideas of how to solve this problem using another kind of design.

My only solution I have come up with currently is to use simple dependency injection by simply passing TimerHandleras an argument everywhere I want to use a Timer. But this will clutter my code badly so I hope to be able to avoid this!

Multiple JSON schemas (products) - how to load correct schema based on keywords?

Question

Where should search keywords and brand names go in a JSON schema (multiple files) in order to search multiple JSON schemas (100-1000s) and select the applicable one?

Background

Not new to programming, I'm relatively new to JSON.

I'm in process of creating a JSON Schema Builder and Form Generator from the schema in Angular - Work In Progress Stackblitz.

I plan to generate a form (from 1 x schema) for approx 100s (potentially 1000s) of products.

Against each product are search keywords and brand names and I plan to use these to search for a product schema (loads the schema hence the form).

Possible ideas:

  1. Keep one huge single JSON file (I want to avoid this)
  2. Keep a meta json schema with keywords in an annotation, load this and use this to select and load correct schema

search-schema.json

{
  "type": "object",
  "properties": {
      "plywood.json": {
          "description": "plywood ply" <---- keywords
      },
      "pens.json": { ...
  }
}
  1. Save schemas to a database and use database functionality to search for correct schema (is this avoidable/desirable/prefered?).

ASP.Net Core API bind model int Ids to custom Id objects

I have structs which represents Id's for different types. That structs have int property "Id", public constructor with (int id) parameter and implements IEquatable interface. I want my ASP.Net Core WebAPI application to somehow bind those structs to incoming integer Ids in query. I know that there are custom model binders, but to use it I need to implement custom model binders for all query models, because marking each key-struct property with custom model binder not enough - I need to register custom model binder provider, where I switch ModelType and return single model binder, like so:

    public class CustomModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (context.Metadata.ModelType == typeof(DogQueryModel))
            {
                return new BinderTypeModelBinder(typeof(DogQueryModelBinder));
            }

So I can't create just one model binder for each Id struct - need to create it for each query model.

To make it clear I will provide some example code of that struct, query model and action:

    public struct DogKey : IEquatable<DogKey>
    {
        public DogKey(int id)
        {
            Id = id;
        }

        public int Id { get; }

        #region IEquatable implementation
        #endregion IEquatable implementation
    }

    public class DogQueryModel
    {
        public DogKey Id { get; set; }
        public SomeOtherKey OtherId { get; set; }
        public string Name { get; set; }
    }

    [HttpGet("dog")]
    public async Task<ActionResult<IList<DogResultModel>>> GetDogs([FromQuery]DogQueryModel dogQueryModel)
    {
        //use dogQueryModel.Id as DogKey struct
    }

I want to query it like this: https://localhost/api/v1/dogs/dog?id=1&otherId=2&Name=dogname

Assign value to variable from ArrayList with regex

this is my first question here and i'm pretty new to programming so sorry for any mistakes.

I need to extract the first 6 characters(ICAO) and assign it to a locale variable from an ArrayList (taken from https://opensky-network.org/apidoc/rest.html) that looks like this:

["1234a5","ABC123","Schlumpfhausen",1572255699,1572255699,8.9886,48.3756,6278.88,false,155.16,216.64,-6.18,null,6484.62,"3026",false,0
"44035c","LDM87NM ","Austria",1572430045,1572430052,9.2009,48.6891,null,true,0,163,null,null,null,"6463",false,0
.
.
.
]

It is required to use java.util.regex to solve this Problem.

String icao=null;

    Pattern icaoPattern = Pattern.compile("([+-]*[a-zA-Z0-9.]*)");
    Matcher matcher = icaoPattern.matcher(sentence.getAircraftJson());

        if(matcher.find()) {
             icao=matcher.group(1);
        }

The outcome should be printed like this:

ICAO: 1234a5 | Callsign: ABC123 | ...
ICAO: 44035c | Callsign: LDM87NM| ...

but all i get is

ICAO: | Callsign: | ...
ICAO: | Callsign: | ...

Thanks

Store a flag for request and user it later for that particular request?

How I can set a flag for whether the request coming from mobile or not So that I can use this flag anywhere for that particular request. I have only access to HttpServletRequest in the start and I don't want to pass it to the calling methods?

mardi 29 octobre 2019

Multiple Conditions and Object Creation using Design Pattern

I am studying design pattern which I can implement to achieve the same purpose as below. However, I am stuck since most of the examples in the net are pretty simple.

I have tried to look at factory method or even strategy method but can't figure out if any of them could be used.

Any suggestion from the guru here?

def checkSomething():
   if ...:
      return True
   else:
      return False

def main(mode, state):
   if checkSomething() == False:
      if mode == False or (mode == True and state == False):
         Class_A().run()
         return False
      else:
         Class_B().run()
         obj_c = Class_C()
         return obj_c

How to properly use transient keyword when de-serializing?

I have the following class

public class Num implements Serializable, Observable {
    private int num; // number which should be serialized

    // listeners who are watching for changes in this Num
    // No need to serialize these -- pointless to do so.
    private transient Set<Observer> listeners = new HashSet<>();

    public void addListener(Observer o) { listeners.add(o); }

    public void removeListener(Observer o) { listeners.remove(o); }

    public void set(int newVal) {
        if (num != newVal) {
            num = newVal; // set the value.
            for (Observer o : listeners)
                o.notify(); // Notify listeners that the value changed.
        }
    }
}

When I serialize this class, it works well and num is saved. When I de-serialize the class, num is loaded but listeners is not and is set to null. My program then crashes on the line for (Observer o : listeners).

I came up with some solutions but they are all terrible solutions.

1) Have a setup method which 'reconstructs' the transient fields.

public void setup() {
    if (listeners != null) throw new Exception("Already setup!");
    listeners = new HashSet<>();
}

This way is annoying through because the de-serialization method needs to remember to setup the object. It's very unintuitive for other people working on the project.

2) Have the set method automatically check and repair itself

public void set(int newVal) {
    if (num != newVal) {
        if (listeners == null) listeners = new HashSet<>();
        ...
    }
}

This way is also bad because the check will keep happening over and over, even though it only needed to be done once.

3) Remove Observable from class Num, get rid of listeners, etc. Then make a non-serializable class which contains a Num instance.

public class Num implements Serializable {
    public int num;
}

public class ObservableNum impements Observable {
    private Num n;

    public ObservableNum() { n = new Num(); } // constructor
    private ObservableNum(Num n) { this.n = n; } // constructor

    ...

    public static ObservableNum loadNum(...) {

        ObjectInputStream ois = ...;
        return new ObservableNum((Num) ois.readObject());
    }
}

But this way also seems needlessly complicated. Surely there must be a better solution? How is transient properly used?

Ant Design + React-table. How can I build the filtering capability of react-table on top of the UI elements provided by Ant Design?

I've been looking at the docs between react-table and Ant Design's table element. It seems that Ant design is a bit opinionated in regards to allowing the developer freedom to add props to either the <table>, <thead>, or <tbody>.

React-table is a headless UI library which provides the developer the React hooks to use with our own UI elements, but my problem at the moment is being able to send those hooks into the core UI elements of AntD's Table element.

Has anyone ever had a problem similar to this? If so, what were your workarounds?

I do not want to resort to taking out chunks of source code from both react-table and Ant Design to eventually building out my own react-table/AntD table hybrid of a solution.

Best way of implementing fan-out pattern with Azure service bus

I'm looking for some best practices on how to implement the following pattern using (micro) services and a service bus. In this particular case Service Fabric services and an Azure service bus instance, but from a pattern point of view that might not even be that important.

Suppose a scenario in which we get a work package with a number of files in it. For processing, we want each individual file to be processed in parallel so that we can easily scale this operation onto a number of services. Once all processing completes, we can continue our business process.

So it's a fan-out, following by a fan-in to gather all results and continue. For example sake, let's say that we have a ZIP file, unzip the file and have each file processed and once all are done we can continue.

The fan-out bit is easy. Unzip the file, for n files post n messages onto a service bus queue and have a number of services handle those in parallel. But now how do we know that these services have all completed their work?

A number of options I'm considering:

  1. Next to sending a service bus message for each file, we also store the files in a table of sorts, along with the name of the originating ZIP file. Once a worker is done processing, it will remove that file from the table again and check if that was the last one. When it was, we can post a message to indicate the entire ZIP was now processed.
  2. Similar to 1., but instead we have the worker reply that it's done and the ZIP processing service will then check if there is any work left. Little bit cleaner as the responsibility for that table is now clearly with the ZIP processing service.
  3. Have the ZIP processing service actively wait for all the reply messages in separate threads, but just typing this already makes my head hurt a bit.
  4. Introduce a specific orchestrator service which takes the n messages and takes care of the fan-out / fan-in pattern. This would still require solution 2 as well, but it's now located in a separate service so we don't have any of this logic (+ storage) in the ZIP processing service itself.

I looked into how service bus might already have a feature of some sort to support this pattern, but could not find anything suitable. Durable functions seems to support a scenario like this, but we're not using functions within this project and I'd rather not start doing so just to implement this one pattern.

We're surely not the first ones to implement such a thing, so I really was hoping I could find some real world advise as to what works and what should be avoided at all cost.

Singleton Pattern is thread-safe

As far as the Singleton pattern is concerned, there are at least three ways of making it thread-safe. Could you explain each of them with examples ?

Design a data source independent application using batch data

We have a legacy application which reads data from mongo for each user (query result is small to large based on user request) and our app creates a file for each user and drop to ftp server /s3.We are reading data as mongo cursor and writing each batch to file as soon it get batch data so file writing performance is decent.This application works great but bound to mongo and mongo cursor.

Now we have to redesign this application as we have to support different data sources i.e mongodb , postgresDB, Kinesis , S3 etc.We have thought below ideas so far-

1.Build data APIs for each source and expose a paginated REST response .This is feasible solution but it might be slow for large query data compare to current cursor response.

2.Build a data abstraction layer by feeding batch data in kafka and read batch data stream in our file generator.but most of the time user ask for sorted data so we would need to read messages in sequence .We will loose benefit of great throughput and lot of extra work to combine these data message before writing to file.

We are looking for a solution to replace current mongo cursor and make our file generator independent of data source.

How to keep data source separate from reusable UserControl in WPF?

I've created a Calendar UserControl by myself. It consists of several sub UserControls. The whole thing is designed to be reusable in other projects. The all containing control that is used and visible from outside (by the user) now has a ViewModel that controls all logic for the Calendar. I think this time I really managed to create a clean, loosely installable control. The only thing I wonder is how to put the required data into the (ViewModel of) the control in a way that is abstract and 'custom implementable'.

I can think of the followong solutions:

  1. Create an interface like ICalendarDataProvider. Then a dependency property on the Calendar control accepts any instance that implements this interface. But a dependency property would be on the codebehind level of the Calendar control, and can only access the DataContext (the ViewModel) of the Calendar by using a dependency property changed callback. This seems ugly, because in that callback I have to cast the dependency object to my Calendar control, get its DataContext property and cast this to the ViewModel type that is the Calendar DataContext. The ViewModel type can not change then, because then the casting in the callback would have to change too. This is actually tight coupling.

  2. Just setting the ViewModel of the Calendar control explicitly from outside by setting the DataContext property. This way the ViewModel can be extended by a data providing class and then set as DataContext of the Calendar. In this class hierarchy the parent class is still a basic class that contains all required logic, and is extended by a class that takes care of the data.

I would like to know how this is done in well MVVM designed projects. Or what's the best practise.

Business layer to handle broken database relationship

There are database tables which store the copies of data and unfortunately the original author of these tables didn't design in using relationship (FK, Guid, etc.) in referring to the data when needed but actually copied over data themselves to other tables.. maybe that was for reducing overhead and making easier to retrieve all necessary information in one query.

And now there comes issues obviously because another person wrote code such, let's say 'data 1' in 'table A' can be modified by user, when that 'data 1' is also in 'table B' and 'table C'. At least it's not totally hopeless because there is another column in 'table A', let's say 'key 1', that can be used paired with 'data 1' when copied over to 'table B' and 'table C' so at least the relationship is not lost when changed by user.

Currently the code uses asp.net MVC pattern and I understand that the fix is probably depending on how code is written and all that, however does anyone know well known fix for issue like this? Design pattern, architecture, etc. Right now redesigning database schema is not an option and needs to be backward compatible, meaning should be able to handle old formats without keys, but the plan is updating already stored data to have keys eventually.

Print the following pattern

I heed help with a pattern.

I've managed to write the code for the top part. I need help with the bottom one.

public class P5na
{
    public static void main()
 {
     System.out.println();
     int i,j;
        for(i=5;i>=1;i--)
        {
            for(j=1;j<=5;j++)
            {
                if(j<=i)
                 System.out.print(j);

                else
                 System.out.print(" ");
            }
            for(j=4;j>=1;j--)
            {
                if(j<=i)
                 System.out.print(j);
                else
                 System.out.print(" ");
            }
            System.out.println();
        }
    }
}

Required Output:

123454321
1234 4321
123   321
12     21
1       1
12     21
123   321
1234 4321
123454321

Initial Output:

123454321
1234 4321
123   321
12     21
1       1

Passing derived class to method as argument which is base class with smart pointer

I have read Head First Design Pattern recently. The book shows related codes in Java. However, I try to convert Java codes to C++. At Observer pattern chapter, I got stuck while converting somewhere. Related codes are follows.

class Subject{ //Publisher
public:
    virtual void registerObserver(ObserverPtr o) = 0;
    virtual void removeObserver(ObserverPtr o) = 0;
    virtual void notifyObservers() = 0;
};
using SubjectPtr = std::shared_ptr<Subject>;

Subscriber class interface:

class Observer{
public:
    virtual void update(double temp, double humidity, double pressure) = 0;
};

using ObserverPtr = std::shared_ptr<Observer>;

Display Element interface:

class DisplayElement{
public:
    virtual void display() = 0;
};

using DisplayElementPtr = std::shared_ptr<DisplayElement>;

and CurrentConditionsDisplay

class CurrentConditionsDisplay : public Observer, public DisplayElement{
    SubjectPtr m_weatherData;
    double temperature;
    double humidity;
public:
    CurrentConditionsDisplay(SubjectPtr weatherData);
    void update(double temperature, double humidity, double pressure);
    void display();

};

using CurrentConditionsDisplayPtr = std::shared_ptr<CurrentConditionsDisplay>;

My question:

At constructor of class CurrentCurrentConditionsDisplay, I would like that Publisher(Subject) registers CurrentCurrentConditionsDisplay.

//constructor
CurrentConditionsDisplay::CurrentConditionsDisplay(SubjectPtr weatherData) :
    temperature(0),
    humidity(0)
{
    m_weatherData = weatherData;

    /* How should I pass 'this' ? */
    m_weatherData->registerObserver(???????); //parameter type is ObserverPtr.

}

How should 'pointer this' is passed due to the fact that parameter type is ObserverPtr?

What is the appropriate design pattern for multiple replacing of specific text or characters

I have a requirement to replace numeric,html tags, and special characters. I have created a method for each purpose. For example I have created methods for ReplaceSpecialCharacters, ReplaceHTMLTags and ReplaceNumeric. And take note there are some additional replace methods that are coming in. My question is what is the appropriate design pattern for this?

sample code
var text="12233333333<body>CLEANTEXT!@#$%^&*()</body>"
var cleanText= ReplaceHTMLTags(text)
    cleanText= ReplaceNumeric(cleaText)
    cleanText= ReplaceSpecialCharacters(cleaText)

Singleton class on http request

I have a question about singleton classes. Suppose, I have a rest api based application and in that application i have created a databases connection class as singleton class. So, wanted to know, when ever a http request comes to fetch the user profile from the db. then on every request it creates a new instance or it uses the same instance for the database. if every time it create a new instance then what is the benefit of singleton class.

How to (lazy) data load the same big dataset from multiple python modules

I have multiple (python) modules where I use the same input data and also the variables have the same names.

I created a module data_loading.py where the variables are instantiated. I then import the variables I need in the data_analysis_xx modules.

For example,

" Module data_analysis_1 "
from data_loading import var_1, var_2,…, var_k 

" Module data_analysis_2 "
from data_loading import var_1, var_3

In this way I avoid to copy-and-paste the same 200 lines of code in every module to load the same or partially the same set of data

First question:

is using a single source module for data loading the right approach? Is there a standard way or anyway a better way for importing the same variables in multiple modules?

In data_loading I also do some basic data manipulation, which can be time consuming, for example integrity check, split, cut, sort, etc. Problem: this can be time consuming. When I import data_loading, all the variables in it are loaded/processed even if I need only one or few variables.

Second question:

how to make the data_loading module work such that only the variables that really need to be loaded/processed are actually processed?

Possible solutions

lundi 28 octobre 2019

Argument Subclassing, static_cast

Let's say I have a class Foo with a virtual method

virtual void initialize(InitParams& params);

Since there will be classes that derive from Foo, is it good practice to also subclass InitParams and static_cast them to the specific InitParams for that class?

Me as a programmer has to ensure that I actually pass the correct InitParams to the method. Are there any other downsides? I want to store multiple Foo instances in a collection so it's important for me to have this generic virtual initialize method.

Open Source Applications that documents their software patterns and architecture

I am looking for an Open Source Application that documents their software development patterns, the architecture and modules well.

Cant really find any projects that directly writes about their patterns, architecture and structure.

Is there a pattern to conversion between classes

I have a class, from a native library, I want to convert to my own type, and I need to do that in several places. I created, then, a static method, so I don't need to repeat the instantiation of the class in so many places, but somehow it doesn't seem right.

What is the best way to do this kind of thing? Is there any known pattern that covers this subject?

class Record
{
  public String Id { get; set; }
  public String FirstName { get; set; }
  public String LastName { get; set; }
  public String FingerPrints { get; set; }

  //
  // This is a simplification of the method and in fact, I created several of
  // them, and the class doesn't look clean anymore.
  //
  public static Record CreateFromMaciRecord(MaciRecord maci)
  {
    return new Record
      {
        Id = maci.GetRecordId(),
        FirstName = Encoding.UTF8.GetString(maci.GetUserDataField("first_name")),
        LastName = Encoding.UTF8.GetString(maci.GetUserDataField("name"))
      };
  }
}

Two tables to one table as relation

I have some troubles to design a part of my database and the relationship between them.

My entities are:

  • Vehicles -> 1:1 -> Prices
  • Bikes -> 1:1 -> Prices

Option A:

Create 2 tables

VEHICLES TABLE

+----------------+---------+
|      NAME      |  TYPE   |
+----------------+---------+
| Id             | uuid    |
| brand          | varchar |
| model          | varchar |
| attribute1     | varchar |
| price          | float   |
| discount float |         |
| locale varchar |         |
+----------------+---------+

BIKES TABLE

+----------------+---------+
|      NAME      |  TYPE   |
+----------------+---------+
| Id             | uuid    |
| vendor         | varchar |
| attribute1     | varchar |
| attribute2     | varchar |
| attribute3     | varchar |
| price          | float   |
| discount float |         |
| locale varchar |         |
+----------------+---------+

Option B

Create 3 tables

VEHICLES TABLE

+----------------+---------+
|      NAME      |  TYPE   |
+----------------+---------+
| Id             | uuid    |
| brand          | varchar |
| model          | varchar |
| attribute1     | varchar |
+----------------+---------+

BIKES TABLE


+----------------+---------+
|      NAME      |  TYPE   |
+----------------+---------+
| Id             | uuid    |
| vendor         | varchar |
| attribute1     | varchar |
| attribute2     | varchar |
| attribute3     | varchar |
+----------------+---------+

PRICES TABLE

+----------------+-------+
|      NAME      | TYPE  |
+----------------+-------+
| vehicle_id     | FK    |
| bike_id        | FK    |
| price          | float |
| discount float |       |
| locale varchar |       |
+----------------+-------+

Option C

create 4 tables

VEHICLES TABLE

+----------------+---------+
|      NAME      |  TYPE   |
+----------------+---------+
| Id             | uuid    |
| brand          | varchar |
| model          | varchar |
| attribute1     | varchar |
+----------------+---------+

VEHICLES_PRICES TABLE

+----------------+-------+
|      NAME      | TYPE  |
+----------------+-------+
| vehicle_id     | FK    |
| price          | float |
| discount float |       |
| locale varchar |       |
+----------------+-------+

BIKES TABLE


+----------------+---------+
|      NAME      |  TYPE   |
+----------------+---------+
| Id             | uuid    |
| vendor         | varchar |
| attribute1     | varchar |
| attribute2     | varchar |
| attribute3     | varchar |
+----------------+---------+

BIKE_PRICES TABLE

+----------------+-------+
|      NAME      | TYPE  |
+----------------+-------+
| bike_id        | FK    |
| price          | float |
| discount float |       |
| locale varchar |       |
+----------------+-------+

NOTE: I really simplify the vehicles & bikes tables (i can't merge this both in one table like 'product')

What we will be the best design for the performance and pattern point of view?

Design pattern: table architecture and polling algorithm for intermediate "pending" states

There are 2 parts to this problem:

  1. Architecture: I have a table that holds "applications". These applications are submitted to a third party service where it takes about a day or two to either "approve" or "deny", the state is "pending" in the meantime. The third-party service has a logging endpoint where they continually publish the status's of applications when they are "approved" or "denied".

  2. Algorithm: The endpoint is queryable by an application request id (int generated upon submitting an application) param and a timestamp, and returns a list of statuses. This list that is returned starts from the closest id/timestamp published, based on the params you hit the endpoint with, and is of a size based on an int you provide to the endpoint: https://endpoint?id=&listSize=&dateTime=

My questions:

  1. Architecture: Should I put all these applications (those with states "pending" and "approved") into 1 table, and have a status column, or should I break this up into 2 tables and have a table for all the "approved" applications and another table for all of the "pending" applications? (And maybe even a table for all of the "denied" application.)

  2. Algorithm: What is the best way (Design pattern) to continuously poll the logging endpoint in order to realize the next state and then perform the necessary update based on the final status of these applications?

Big picture:

Does this design pattern already exist and are there solutions for this?

Does AWS provide something built for this and/or is software like Celery recommended to perform such routine logging and updating tasks?

Design for Angular application

first post here so be nice! I will try to be the most precise and concise possible.

I'm currently developing a GUI in Angular/Typescript which displays the devices and network traffic of the LAN and nearby. I'm having a bit of trouble with the design of my application so far.

I have several device classes:

Device

export class Device {
  _id: string
  _mac: string
  ...
}

LANDevice

export class LANDevice extends Device {
  _firstSeen: Date
  _status: 'reachable' | 'unreachable'
  _services: Service[]
  ...
}

I have other classes to describe other type of devices like Bluetooth, BLE devices etc. I would like to have several components (Summary, Services & vulnerabilities and Activity) that displays some information about those devices.

The problem I'm facing is that, depending on the device type, the information to display will be very different.

How do I design my components and classes to handle this use case ? Should I have a functon in each device class to expose the 'right' model to the concerned component (but I would need to write a function for each component so not a good idea I believe)

Device

export class Device {
  ...
  public toSummary(): SummaryModel {
    icon: this._svgIcon(),
    name: this._hostname,
    content: [
      firstSeen: this._firstSeen,
      network: [ ... ]
    ] 
  }

}

BluetoothDevice

export class Device {
  ...
  public toSummary(): SummaryModel {
    icon: this._svgIcon(),
    name: this._hostname,
    content: [
      lastSeen: this._lastSeen,
      macVendor: this._macVendor
    ] 

  }

}

And in my Summary component have:

SummaryComponent

export interface SummaryModel {
  icon: <Base64>,
  name: string,
  content: []
}


export class SummaryComponent {
  ...

  **Parsing of device.toSummary() function with keys/values with table-like display**
  **Key1: Value1
  **Key2: Value2
  **...

}

Does anyone have better ideas ? The main problem here is that, depending on the device type, I don't want to display the same things. I could chech the device type and handle this in the component or HTML but I believe that a Component in Angular should have a single interface/data model and handle only this.

Thanks for your time :)

dimanche 27 octobre 2019

DESIGN PROBLEM: How to use composition the best

I'm working on a project and have some doubts about it's design. How can I design the following problem the best (in JAVA):

Class A with the following attributes:

  • HashSet of Pixels where each pixel has x,y coordinates and value v between 0-1.
  • instance of class B.

Class B with the following function:

  • a function that gets a Pixel and returns its left neighbor.

When I'm in class A I want to use B.function on each pixel in A and add it to the HashSet only if it's not already there. The problem is that I don't want to send the HashSet to the function, how bad is it to return new instance of Pixel from the function if it might already exist (This function going to run on many pixels and will create many unused instances of Pixel).

What other options do I have?

cmd callendar in python

I just trying to do python challenges. And part of one is cmd callendar looks that:

| M  | T  | W  | Th | F  | S  | Su |
|    |    |  1 |  2 |  3 |  4 |  5 |
|  6 |  7 |  8 |  9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 | 17 | 18 | 19 |
| 20 | 21 | 22 | 23 | 24 | 25 | 26 |
| 27 | 28 | 29 | 30 |    |    |    |

In this case, all months has 30 days. I need to do that in iterative way. I need to keep start day in variable. Start day should be 0-6 when 0 is Monday, and 6 is Sunday. For example, the month from example variable = 2.

I can't do that but i want to understand it. How can I do that in iterarive way?

I tried do that in another way, just using calendar library, but it's not the correct solution.

Can someone help me?

Exchanging different kinds of data between threads in Qt

That's kind of design question. Say, I have a worker thread and a GUI thread. The worker thread does some work and the GUI must show the information about current status of this work (for example, worker can process some files and the GUI must show the number of processed files, having separate counters for different types of files).

In Qt the information exchange between thread should be done via signals-slots mechanism. But if I have a lot of different kinds of information to pass from thread to thread, should I create different signals for each type of information (for example, for each type of file), or it would be better to create one signal (for example, informationUpdated(InfoContainer); with a special struct (InfoContainer), which will store the data I want to pass?

Should i create a Core library for all business applications ? or each one individual?

I was find many companies which creating entities and models for each business applications

So all these apps not reusable.

Now, some clients of the company for example. needs 3 kind of software.

For example [ HR management, Inventory, and Asset management ]

Here's a problems i found.

  1. if i created each project from scratch it will take many time.
  2. each project can't be reusable. so i can't create asset from Inventory project.

So I need to know following :

  1. Should i create a Single Core library which contains Data-Entry controls and so that i can import it in each project ?
  2. A Single Core will make me don't create any new data-entry or addons controls. so i just drag & drop and create a Business App that i need directly. without creating a Models for it. Assuming i Use a Custom Control which have dynamic properties that take ( TableID, FieldID's from currently working Form or screen )

Please, i don't ask because i don't know exactly what done. but i need to hear from People who works in Mid-Scale Business Apps or Large Scale one.

In breifly. Guess that your client asking to make 7 Business Apps. that is separately .

Ex : Financial System, Inventory, HR Management, and so ? now all of them is Data-Entry screens and reports.

What exactly will you thinking or do? to gain more time. and reusable components?

samedi 26 octobre 2019

Discrete Event Modelling - Simpy - how to model complex dependencies?

I am new to Simpy and I am having troubles figuring out how to model a process scheduler that has complex dependencies.

High-level summary of my problem:

  • I have a warehouse that receives boxes containing items through an entrance. The boxes are put in a queue where they wait to be processed.
  • Each box has a destination room and must be shipped there using a conveyor belt. A conveyor belt services multiple rooms.
  • An operator looks at the boxes in the queue and puts a box on the appropriate conveyor belt only if both the belt and the destination room are available. The operator sends the boxes in order but skips the boxes that cannot be processed.
  • Once the box is opened inside a room, it takes a certain amount of time to store the object. During this time, the room cannot receive other boxes.
  • After the object is stored, the empty box is sent to the exit of the warehouse using the same conveyor belt it came in.
  • The operator has knowledge at all times of which conveyor belts and rooms are free.

My question is how to model this operator. I did not find so far an elegant way to do this in Simpy. I essentially want to have a process that wakes up only when the following three conditions hold: a) a room is free; b) there is a box in the queue addressed for this room, and c) the belt for getting to the room is free.

Any idea, advice or pointer to an existing example are greatly appreciated. Thank you!

How does publish-subscribe design pattern establish loose coupling between components? C#

If was going through a C# exam book and I read:

A popular design pattern (a reusable solution for a recurring problem) in application development is that of publish-subscribe. You can subscribe to an event and then you are notified when the publisher of the event raises a new event. This is used to establish loose coupling between components in an application.

It got me wondering that what does this have to do with loose coupling? Is it only because the components are now not interacting directly or do we have more reasons?

How to follow SOLID principles and not break any rules with my application?

So let me first explain how my application is set out, I have many projects that all do their own thing, if a project needs a file from another project then it references that project, but the key thing is you can't reference projects both ways.

Project.Interfaces (Hold interfaces, referenced in most projects)
Project.Something
Project.SomethingElse
Project.Shared (Usually just utilities and helpers)

Now, I've reached a stage in my application where I need to use an enum. I thought cool lets host the enum in Project.SomethingElse where it's most related to - I need my enum in .Interfaces and .SomethingElse and I can't reference these two together. So what am I supposed to do?

I did try and host it in Project.Shared which made sense when I tried it, but .Shared needs .Interfaces - reason being for this is so I'm not referencing concrete types in .Shared.

I know a big question here is going to by why don't I reference concrete types anywhere and that's because I want to make my application as abstract as possible.

My solution was to make another project called Project.Enums and just hold all enums in there and this worked out okay because enums didn't need anything other than themselves.

But I've also been advised to let the .Interfaces project own the enum, but isn't this breaking some sort of SRP rule? I'm just looking for some guidance on what is the correct way to handle this without breaking any rules. Am I overthinking this?

Model structure in CodeIgniter

I've been struggling with an application (model) design problem for the past couple days, and can't really say that I've made much progress. I'm new to PHP frameworks. I've have been using CodeIgniter for last two months. Everything is fine so far, but as the count of entities (tables) in the app increases, I begin to wonder if I'm doing things right.

I'm not quite sure about the difference between Model and a Custom Result Object.

Let's say I have two base tables (users and roles) and an associative table (user_role). For the users table, I want to be able to use the following actions:

  • create, get (user), get (users), update, delete

And for the roles table:

  • create, get (role), get (roles), update, delete

And for the relation between the two user_role:

  • assign role (to a user), remove role, get role

If I were to create a User_model, how should it look? I could define methods such as

public function get_user($user_id) {
    return $this->db->from("users")->where("id", $user_id)->get()->row_array();
}

but I don't want to work with arrays. I mean, then, how do I get the user's role? Another method?:

public function get_user_role($user_id) {
    return $this->db->query("SELECT * FROM roles WHERE id IN (SELECT role_id FROM user_role WHERE user_id = ?)", $user_id)->row_array();
}

I'd have to do:

$this->load->model("user_model");
$user      = $this->user_model->get(1);                     // array
$user_role = $this->user_model->get_user_role($user["id"]); // array

What if I have more entities (that's related to users)?

$user_permissions = $this->user_model->get_user_permissions($user["id"]); // array
$user_products    = $this->user_model->get_user_products($user["id"]);
$user_tasks       = $this->user_model->get_user_tasks($user["id"]);
// etc.

This looks messy, and like a bad design. If I want to use an object that represents a table row, and add all other relations to the object, how would I design it? I mean, should I add every needed properties/methods inside User_model and when I get a row ($this->user_model->get(1)) from the table, return a User_model (with custom_row_object(0, "User_model")) instead of an array (row_array())? Or should the object that represents a table row be a different object than User_model?

For example:

// model is instantited and accessible at $this->user_model
// since it's automatically instantiated (when loaded), it's not linked to any row
// this model could act as a intermediary between the controller and the database/table
// if it will never be linked to a row, there's no reason to have update, delete, etc. methods on the model
// model's role is to insert rows and get objects that represent table rows
$this->load->model("user_model");

// when requested a table row, we return an object that represents a table row
$user = $this->user_model->get(1);  // $user is an object; ...->get()->custom_row_object(0, "UserRow")
$user->get_role();                  // role is accessible at $user->role; (this could just be another object: a role object)
$user->role->delete();
$user->get_permissions();           // again, $this->permissions; (could be an object)

This way, I could collect all other entities that's related to a user in a single object. The problem with this is, should the returned object be the model (custom_row_object(0, "User_model")) or a completely different object, e.g., UserRow (custom_row_object(0, "UserRow"))?

If I use a different object, say UserRow, that means User_model won't have much properties/methods, that it can only be used when inserting a new row, or getting row(s) from the table (+ maybe store helper methods). I could add the update, delete, get (associated entities) methods to the second (UserRow) object.

I'm really at loss here. I need some pointers.


I know this doesn't seem like a real programming question, and probably opinion-based, but I really need help :|

vendredi 25 octobre 2019

How to expose types returned by API in typescript

I am creating a typescript library that can call web services and return data. It provides an API to call the different web services. Each API call returns data of a certain type. In my main module, I export the API.

I can't figure out the best way to expose the types returned by the API. Given that the types have sub-types and so on, there at least 100 types. For readability and abstraction I put them in multiple files.

I thought I could put all the types in the same namespace and then just expose the namespace. I couldn't figure out how to export a single namespace though in typescript. This lead me to believe there is a different way to tackle this problem but I'm not sure what.

Example:

// api.ts
expose function getData(): IData;
expose function getData2(): IData2;
// IData1.ts
export interface IData1 {
    subData: ISubData1;
}

export interface ISubData1: {
    value: string;
}
// IData2.ts
export interface IData2 {
    subData: ISubData2;
}

export interface ISubData2: {
    subSubData: ISubSubData2;
}

export interface ISubSubData2 {
    value: string;
}
// index.ts
import * as api from "./api";
export {api};

// What is the best way to export the type interfaces so that the consumer of this library has type checking?

How do I reduce two almost identical pieces of code into one?

I have almost two identical logic controllers (the differ in external layouts and input data) and I wonder if I could reduce them into one separate file (or some other method - patterns maybe?). The logic includes creating layouts, promises, showing child views in layouts depending on the responses, event calling. Basic controller stuff. And I wouldn't like to pass a controller or view to a separate file (seems unnatural or unsafe? to me). Maybe You guys have some design patterns or tips on how to achieve my goal?

As a last resort I COULD create separate controller just for managing this logic but if there's another way - I want to know it.

I'm working in backbone and marionette in MVC.

Tracing the data flow across Distributed/Legacy systems

I have 2 Microservices [A, B] and the service [B] has integration with legacy system [C]. The service [B] usually generates unique-identifier and includes it in the flow into [C], also passes it back to [A]. In that way reconciliation was handled between the systems.

The problem really started when there is a need for a service [D] that [A] has to invoke in parallel to inform [C].

While it makes some sense to have [A] generate the unique-identifier and send it to both [B] and [D] to solve the problem, its not that easy because of the cost of change in [C]. So we still somehow need to have the [B]’s unique identifier available for [D] to marry the data in [C].

Appreciate if someone can guide me if there is tactical pattern to solve this problem.

A data design question of labeling sides in a battle game

I am designing a chess-like game but I believe this question can be extend to all games that have battle.

So my question is, how should I properly label an object as a friend object or an enemy object in a battle game?

Take chess for example. If player W plays white pieces, then W's opponent, player B, plays black pieces.

For W, all white pieces are friend objects and black pieces are enemy objects, while player B has black friends and white enemies. So here my labeling problem can be simply solved by using colors. When you try to calculate the possible moves of a piece and decide if you can take out a piece, you can basically check if they have the distinct colors.

However, what if two players have the same view? For example, a game can color all friends as black while color all enemies as white, and the players start their games with their pieces all at the bottom. In this sense of speaking, indeed, pieces can be viewed as the attributes of the player. So the coloring of black and white is based on whether a piece has an owner id that is the same as yours.

Here comes a problem:

Although I can decide the color by comparing the ids, what if I want to know whether a friend piece enters the enemy region?

The definition of enemy region could be the upper part of the board. Since board is not part of the player (while pieces can be), it is not possible to use the previous id solution.

So one possible solution I can think of is to make the board an attribute of the player. However, there are two players, this doubles the data storage because we have actually only one board from an objective perspective. And any moves and further changes on a piece requires operations on two boards, which is also time consuming.

In order not to double the board, I try use to another strategy, which is to use a landscape view. What I mean is that, the data doesn't take sides as players. Players view the board from bottom to top, while data can be viewed from left to right/right to left like what a just referee observes. So the data becomes objective here. But the problem is how to present the objective data in a subjective manner to players? And it is still not easy to know if a piece enters enemy region.

So my question is, how should I properly design the data structure, so that it does not doubles or triples or copies multiple times of the data, and in the meanwhile, it is also easy to know the labels of a public area? In my question, the public area is a chess board, where all pieces should fight on this single board. I call it public because both players can move their pieces to everywhere on the board, and third parties can also see what's going on the board. But the labels of pieces are just subjective attributes, personal private thoughts.

I am not sure if I can properly explain/phrasing my question well so I didn't search for a similar question. Sorry for my laziness. If there is a duplicate question that has been asked, please guide me to it.

jeudi 24 octobre 2019

Singleton Pattern: getInstance() vs Passing the singleton object?

What is the right / most popular way to utilize the Singleton Pattern.

  1. Limit the no. of calls to getInstance(), preferably call it only once, and pass the object around to other classes during their instantiation?
class SingletonClass {
// Implementataion
}

class MainClass {
    private SingletonClass singletonClassObject;

    public MainClass() {
        singletonClassObject = SingletonClass.getInstance();
        new SomeClass(singletonClassObject).doSomething();
        new SomeOtherClass(singletonClassObject).doSomethingElse();
    }
}

class SomeClass {
    private SingletonClass singletonClassObject;

    public SomeClass(SingletonClass singletonClassObject) {
        this.singletonClassObject = singletonClassObject;
    }

    public void doSomething() {
        System.out.println(singletonClassObject.getStuff());
    }
}

class SomeOtherClass {
    private SingletonClass singletonClassObject;

    public SomeOtherClass(SingletonClass singletonClassObject) {
        this.singletonClassObject = singletonClassObject;
    }

    public void doSomethingElse() {
        System.out.println(singletonClassObject.getStuff());
    }
}

  1. Don't pass the singleton object around. Rather call get the object reference in each class and save the reference as an instance variable and use it wherever required.
class SingletonClass {
// Implementataion
}

class MainClass {
    public MainClass() {
        new SomeClass().doSomething();
        new SomeOtherClass().doSomethingElse();
    }
}

class SomeClass {
    private SingletonClass singletonClassObject;

    public SomeClass() {
        singletonClassObject = SingletonClass.getInstance();
    }

    public void doSomething() {
        System.out.println(singletonClassObject.getStuff());
    }
}

class SomeOtherClass {
    private SingletonClass singletonClassObject;

    public SomeOtherClass() {
        singletonClassObject = SingletonClass.getInstance();
    }

    public void doSomethingElse() {
        System.out.println(singletonClassObject.getStuff());
    }
}

  1. Don't even save the reference as an instance variable, rather use SingletonClass.getInstance() everywhere you need the object.
class SingletonClass {
// Implementataion
}

class MainClass {
    public MainClass() {
        new SomeClass().doSomething();
        new SomeOtherClass().doSomethingElse();
    }
}

class SomeClass {
    public SomeClass() {
    }

    public void doSomething() {
        System.out.println(SingletonClass.getInstance().getStuff());
    }
}

class SomeOtherClass {
    public SomeOtherClass() {
    }

    public void doSomethingElse() {
        System.out.println(SingletonClass.getInstance().getStuff());
    }
}

How do these approaches compare with each other w.r.t. better design, testability etc? Which is better and why?

How Can I Draw Using Stars To "W" Letter With C

how can i draw a "W" pattern using only stars and with height input? For example: height of stars input: 5 output picture: https://i.ibb.co/47T7896/Ekran-Resmi-2019-10-25-00-20-04.jpg

Here is my code (it's working but input is broken and first star line are not including spaces):

#include<stdio.h>
#include<conio.h>

int main()
{
    int i,j,k,l,m,step=1;;
    printf("height of stars:");
    scanf("%d",&i);
    for (i=0;i<=4;i++)
    {

        for(j=0;j<=2;j++)
        {
            printf("*");
        }


        for(k=3;k>=i;k--)
        {
            printf(" ");
        }

        for(j=0;j<=2;j++)
        {
            printf("*");
        }

        for(l=1;l<=i;l++)
        {
            printf("  ");
        }

        for(j=0;j<=2;j++)
        {
            printf("*");
        }

        for(m=3;m>=i;m--)
        {
            printf("  ");
        }

        for(j=0;j<=2;j++)
        {
            printf("*");
        }
        step+=2;
        printf("\n");
    }
    return 0;
}

How to determine what "best practice" would be in general when implementing in Java?

I just came across another question asking about the best practice in dealing with issue XY. The intention of the OP might have been to get some viable practices (all the replies answer to that one in the example), but I found it still desirable to come up with a response about "best practice"- desirable but not really feasible.

While it is still possible to reply to a question, whether some approach is "clean" (just scan the writings of M.Fowler (inventor of the term) and R.Martin (evangelist of the attitude)), I'm at a loss with "best practice". If you search for the term you get a zillion arbitrary blogs announcing their insights (e.g. [1], [2]) with some of the recommendations probably harking back to "Structured Programming" by Dahl/Dijkstra/Hoare from 1972. Then there is J.Bloch's "Effective Java" an the Nth edition (promising "best practices for the Java platform" on the cover) and the whole pattern zoo, starting with GOF's "Design Patterns", with another zillion posts where for each pattern you can find a claim that it is an anti-pattern (e.g. [3], [4].

Is there any common frame of reference at the moment, or at least accepted fragments of one, against which a reply to such a question could be set? It would be a frustrating state of affairs, to label all of them "opinion based" wholesale ("The question you're asking appears subjective and is likely to be closed").

c# which desgin pattern is used

I got this simple task to figur out what design patterns are being used on each class and to explain pros and cons. I'm quite weak on this subject and wish someone would help me with this and eventually tell me where to read more about this subject and when to use each pattern or which one is mostly used out there in the real world?

Here is the code: Pattern A:

class PatternA
{
    private static PatternA _instance;
    private PatternA()
    {
    }

    public static PatternA GetInstance()
    {
        if (_instance == null)
            _instance = new PatternA();

        return _instance;
    }

    public void DoWork()
    {
        throw new NotImplementedException();
    }
}

Pattern B

 public abstract class SomeObject
{
}

public class ConcreteSomeObject : SomeObject
{
}

public abstract class PatternB
{
    public abstract SomeObject Create();
}

public class ConcretePatternB : PatternB
{
    public override SomeObject Create()
    {
        return new ConcreteSomeObject();
    }
}

Pattern C:

public abstract class Foo
{
    private readonly List<Bar> _list = new List<Bar>();

    public void Attach(Bar bar)
    {
        _list.Add(bar);
    }

    public void Detach(Bar bar)
    {
        _list.Remove(bar);
    }

    public void Notify()
    {
        foreach (var o in _list)
        {
            o.Update();
        }
    }
}

public abstract class Bar
{
    protected readonly Foo Foo;

    protected Bar(Foo foo)
    {
        Foo = foo;
    }

    public abstract void Update();
}

Is there any creational pattern to encapsulate the creation of a concrete class?

I find myself in the situation that many times I would like to encapsulate the logic for the creation of an object in an specific class and I don't know if there is any pattern that matches what I want to do. This is, always creating from some input parameters the same type of object, without need for dynamically configuring options.

The three candidates I consider are Factory (all it's variants), Builder and Mapper.

In general, all factory patterns state that a factory does not return an specific class but an interface, is then a sub-class or the class that implements the factory the one that decides which class that implements the interface should instantiate. I would like to create always the same class type so I don't need to many subclassses or implementations that would return different types of implementations of an interface, that's why I think it's not a factory.

Builder pattern peculiarity is to use methods to be able to expose multiple configuration options, and finally creating the object after doing all the configuration. I don't need this because I would just need a Create method that would always do the same without configuration possibilities.

A Mapper I understand only maps between different properties from one object to another, when the creation of the object is more complex and involves logic or calls to external components I would not refer to it as a mapper because it would be confusing and may lead to confusion expecting to have a simple mapping on it.

I think it's very common to face this situation and I'd like to know if there is some pattern that describes exactly what I do, or which one is usually used for this purpose.

Static factory methods instead of constructors

I've been researching this after I read Joshua Block's Effective Java Book, Item 1, about using factory static methods instead of constructors. There in the text he defends the use, whenever possible and cites, among other justifications, the possibility of implementing the Singleton or Flyweight standards. It also cites the case of the Boolean class, which wisely uses Flyweight through the valueOf (boolean) method:

public static Boolean valueOf(boolean b) {
return b ? Boolean.TRUE : Boolean.FALSE;
}

My question is: I understand the advantages of using these patterns, but could not be implemented in the constructor itself? Their use alone does not justify the creation of a static factory method.

How to design the back-end for an online carom board?

How to design the back-end for an online carom board? Max of 4 players can play the game.

A Design pattern suitable for the case

I have the UML diagram below (sorry if the picture does not have many informations).

enter image description here So what I have is

IRE Interface which is implemented by RE class. IRD Interface which is implemented by RD class (and this latter extends RE). IRM Interface which is implemented by RM class (and this latter extends RE).

So is there a suitable Design Pattern to represent this digaram?

Thank you in advance.

call an instance method from an interface class

I am looking for a way to call an instance method from an other class and I wondered if/how I could could do the following

goal and context

The class I am writing is a data formater whose __rshift__ method should be able to adapt the format of a data batch to many data base clients without the user needing to change the method used. Here is how I would like the >> method to be called

batch  = SomeExtractor(config).extract("some")
db_client = InfluxDBClient()
# this would be awesome
DataFormater(batch)>>db_client.write_points

the DataFormater

class DataFormater(object): 
  def __init__(self, batch: Batch): 
    self.batch = batch

  @abstractmethod
  def __rshift__(self, db): 
    db_client = some_way_to_get_the_called_client(db)
    method = some_way_to_get_the_method(db)

    if method == InfluxDBClient.write_points:
      db_client.write_points({"measurement": self.batch.origin, 
                "time" : self.batch.date, 
                "tags": dict(zip(self.batch.dimensions_names, row["dimensions"])),
                "fields": dict(zip(self.batch.metrics_names, row["values"])}
                for row in self.batch.rows))

Googling my problem, added stack = inspect.stack(db) in the __rshift__ method and got the following but I am not sure how to use it

frame = <frame at 0x7f6c2a1515c0, file '/usr/src/collector/collector.py', line 95, code __rshift__>
context = <bound method InfluxDBClient.write_points of <collector.InfluxDBClient object at 0x7f6c2a131510>>

How can I do this?

Question on adding value in an array to another array for counting c++

Here's the situation:

User can choose up to 4 dices on the table with a range[1-12] faces they want (Yes, 1 face dice is a THING here). Then the program will calculate all the outcome possibilities.

For example: 2 dices, 1st with 6 faces, 2nd with 2 faces.

Output:

Sum of 2 = 1

Sum of 3 = 2

Sum of 4 = 2

Sum of 5 = 2

Sum of 6 = 2

Sum of 7 = 2

Sum of 8 = 1

I have found out the pattern to calculate with all of the possibilities with different of no. of dices and faces they have, here's the illustration:

4 dices with faces [6, 2, 3, 4] respectively

Click here to check the pattern

Blue area is a dice with 6 faces Green area is 6 faces with 2 times Yellow area is green area loop with 3 times Read area is yellow area loop with 4 times

The numbers aside are the count of the appearance of each sum and it's correct all the time no matter what inputs are.

However, I've attempted many times and still cannot find the correct way to implement this pattern into c++ program.

My codes are like this:

// Calculate the first iteration of dices

for (int k = 0; k < faces[2]; k++) {
        for (int j = num + k; j < (num + faces[1] + k); j++) {
            tempCount[j]++;
        }
    }

    // Copy results into counter1[]

    for (int i = num; i <= faceCounter; i++) {
        counter1[i] += tempCount[i];
    }

    // Find out the remaining dices

    for (int i = 2; i < num; i++) {
        for (int k = 0; k < faces[i+1]; k++) {                          // Calculate the count range
            for (int j = num + k + 1; j < (num + faces[i] + k); j++) {  // Add the previous counter's value into temp counter
                tempCount[j] += counter1[i];
            }
            if (k == faces[i + 1] - 1)                                  // Make sure finished the for loop first then to final addition, won't duplicate data
                finished = 1;
        }

        //Load results back to counter, which will using it back in loop for further counting

        for (int i = num; (i <= faceCounter) && (finished = 1); i++) {
            counter1[i] += tempCount[i];
        }

        finished = 0;
    }

This is not working though.

How can I change it?

mercredi 23 octobre 2019

Nested Webservice Calls Design Pattern

I have an array of complex objects that I am sending over to a web service. I have to send them individually, it's just the way they have built it their end, and it currently looks a real mess because it is a bunch of nested ifs checking the responses back from the service and then taking a course of action dependent on that. Here's an example of how it looks:

var req = Requests.GetInsertServiceRequest(billingReq, userName, contractNo);

result.Add(Connector.CallWebService<Service>(req, "return", errorMessage));
  if (errorMessage.HasError) {
    if (errorMessage.Error.StartsWith("Entity not found: [GSM]")) {
      //make a call to correct this error and then try the original call again
    } elseif (errorMessage.Error.StartsWith("some other expected error")) {
      //do something else to correct the error and call the original request again
  } else //successfully called adding the service so call the service on some of the nested objects
  {
    foreach(var associatedItem in billingReq.associatedItems){
      var subReq = Requests.GetInsertAssocatedItemRequest(associatedItem, userName, contractNo);
      result.Add(Connector.CallWebService<AssociatedItem>(subReq, "return", subErrorMessage));
      if(subErrorMessage.HasError) {
        and so on

I can see that this is a terrible design. Teh method is getting really long and I know I need to break it up into more atomic methods. I just wondered if anyone had any ideas on what best pattern to use to solve handling different error messages coming back and then trying alternative requests and the initial request again, and then all of the sub requests on the objects within the parent object.

I am using a C# class library to call the service but this could be any language really.

Thanks in advance for any help.

Which pattern is followed for the following folder structure? ( Python Project )

enter image description hereThe following structure is followed to write python code. It just grab the data from database and hit several api. Can anyone please explain the structure which has been followed here ?

What's the design philosophy of netty class ChannelDuplexHandler?

This is what ChannelDuplexHandler javadoc said:

ChannelHandler implementation which represents a combination out of a ChannelInboundHandler and the ChannelOutboundHandler.

and the class definition as below:

public class ChannelDuplexHandler extends ChannelInboundHandlerAdapter implements ChannelOutboundHandler

ChannelDuplexHandler extends ChannelInboundHandlerAdapter to use all of its template methods, while Java not supports multi inheritance, so (maybe in a compromise way?) ChannelDuplexHandler implement ChannelOutboundHandler and overrides every methods which are exactly the same with ChannelOutboundHandlerAdapter implementation.

Is this redundant work fragile? As someday once decide to change the ChannelOutboundHandler template behavior, I have to change the ChannelDuplexHandler implementation mirroring?


So my questions are:

  1. Why extends ChannelInboundHandlerAdapter but not ChannelOutboundHandlerAdapter? only because ChannelOutboundHandler have fewer method to override?
  2. Why not use some smart ways to avoid this? (agency or warp patterns? I don't know if I pull the concept right)
  3. If the ChannelOutboundHandler add some new interface method, you have no choice but only to write the same code twice in ChannelOutboundHandlerAdapter and ChannelDuplexHandler? (or somewhere else maybe)

convert mysql database to dynamodb model

I'm new to dynamoDb and I'm trying to get the hang of it but I'm not getting how to store 'master' table details in single table dynamoDb.

For example, take this movie database.

category table(refer this as a master table)
+----+----------+
| id | category |  
+----+----------+
| 1  | thriller | 
+----+----------+
| 2  | horror   | 
+----+----------+
| 3  | romantic |
+----+----------+

movie table (category_id is FK)
+----+-----------+-------------+
| id | name      | category_id |  
+----+-----------+-------------+
| 1  | gone girl | 1           | 
+----+-----------+-------------+
| 2  | get out   | 1           |
+----+-----------+-------------+
| 3  | seven     | 1           |
+----+-----------+-------------+
| 4  | us        | 2           | 
+----+-----------+-------------+
| 5  | it        | 2           |
+----+-----------+-------------+

how to model this in dynamoDb and what would be the query if I want to get all the possible categories. Consider there are few more Fk's in the movie table.

How to transpose a matrix in Ocaml

I am trying to transpose a matrix using pattern matching in Ocaml, I can't use any modules or map function, any advice on how to approach this?

Splitting a stream with more than one consequtive delimiter including pipe [duplicate]

This question already has an answer here:

Spliting a stream containing "&|&" as delimiter

I have a stream containing more than one element and using the following separator "&|&"

String user="White, John&|&false&|&true";

I try to create an array:

final String[] elementFilters = user.split("&|&");

but it take the both pipes as one of the array elements.

I get the following elements:

elementFilters[0]="White, John";

elementFilters[1]="|";

elementFilters[2]="false";

elementFilters[3]="|";

elementFilters[4]="true";

but I just require 4 elements and pipe should not be elements of the array. Any idea?

Dynamic auth with strategies in an angular application

I know it's a pretty general question but hopefully it makes sense.

There are a few auth strategies in the app I'm working on. And depending on whether a user wants to login through some social media or using their own email and password one of those strategies is set for the auth service. The auth service has a few methods like login, logout and a few others and they are called on the strategy, something like this this.strategy.logout().

Everything works nice until the user reloads the page or tries navigating to some page by typing its full url then everything is reset.

Storing the strategy name in the localStorage doesn't look like a good idea. I don't really know how best to go about it.

Should EF entites contains additional fields?

I'm using EntityFramework as my DAL, where I have for example entity:

public class UserEntity
{
    public int WorkingDays {get;set;}
    public int PayPerDay {get;set;}
}

I'm getting this entity in my services layer by repository, and that's the place i need to calculate for example his salary:

public ???? GetUserWithPayments(int id)
{
    var userEntity = _userRepository.GetUser(id);
    var salary = userEntity.WorkingDays * userEntity.PayPerDay;

  //*what should i return??*//
}

And now I have no idea what should I return from this method? I see 2 options:

1.) Add salary field to UserEntity, and returns UserEntity. This field will be skipped when I save UserEntity to database.

2.) Create UserDto with UserEntity fields and one more Salary

This service is called by UserController where the result will be mapped to GetUserDetailsViewModel

Builder design pattern, returns null in a multi threaded environment

I was reading about the pattern here:

https://www.geeksforgeeks.org/builder-pattern-in-java/

the last part demonstrates how to use the pattern, I tried to copy the code into my IDE & run it but it returns null,

the code:

 final class Student {

    // final instance fields
    private final int id;
    private final String name;
    private final String address;

    public Student(Builder builder) {
        this.id = builder.id;
        this.name = builder.name;
        this.address = builder.address;
    }

    // Static class Builder
    public static class Builder {

        /// instance fields
        private int id;
        private String name;
        private String address;

        public static Builder newInstance() {
            return new Builder();
        }

        private Builder() {
        }

        // Setter methods
        public Builder setId(int id) {
            this.id = id;
            return this;
        }

        public Builder setName(String name) {
            this.name = name;
            return this;
        }

        public Builder setAddress(String address) {
            this.address = address;
            return this;
        }

        // build method to deal with outer class
        // to return outer instance
        public Student build() {
            return new Student(this);
        }
    }

    @Override
    public String toString() {
        return "id = " + this.id + ", name = " + this.name + ", address = " + this.address;
    }
}

// Client Side Code 
class StudentReceiver {

    // volatile student instance to ensure visibility
    // of shared reference to immutable objects
    private volatile Student student;

    public StudentReceiver() {

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                student = Student.Builder.newInstance().setId(1).setName("Ram").setAddress("Noida").build();
                System.out.println(student.toString());
            }
        });

        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                student = Student.Builder.newInstance().setId(2).setName("Shyam").setAddress("Delhi").build();
                System.out.println(student.toString());
            }
        });

        t1.start();
        t2.start();
    }

    public Student getStudent() {
        return student;
    }
}

// Driver class 
public class BuilderDemo {
    public static void main(String args[]) {
        StudentReceiver sr = new StudentReceiver();
        System.out.println("sr " + sr.getStudent());
    }
}

When I remove the threads and run it without them it works, anyone has an idea of why it returns null instead of one of the student objects ?

Qt "passthrough" or "container" widget

In Qt / PySide2, is there such a thing as a Qt widget that simply passes through to a wrapped widget, without adding any extra layers of layout etc.

I'm coming from a web frontend background, so my mental model is of a React container component that adds some behavior but then simply renders a wrapped presentational component.

However, there doesn't seem to be a way of doing this sort of thing in Qt without at least creating a layout in the wrapping widget, even if that layout only contains one widget. I could see that this could lead to multiple layers of redundant layout, which could be inefficient.

I acknowledge that it may be better to not try to replicate React patterns in Qt, so any suggestions of equivalent but more idiomatic patterns would also be welcome.

mardi 22 octobre 2019

Algorithm for n players, 5 games and 10 rounds

Looking for a mathematician who can figure out the algorithm or grid/matrix shift system for n number of players, 5 games and 10 rounds where n can be any number of players 20 or greater, each game has 4 players (2 on 2) each round has all tables filled no one plays with a partner more than once and every one plays each game twice.

Leftovers players should be on a bye (take a break) only once

What GOF pattern is implemented for the code?

Is there any matching GOF pattern in the code below?

The sense is that there will be 2 consumers and a lot of workers. ConsumerA will use only DoA() method, ConsumberB will use only DoB() method . inputA and inputB will be different classes that have some key property.

interface IWorker()
{
    DoA(object inputA);
    DoB(object inputB);
}

class ConcreteWorker1 : IWorker
{
    DoA(object inputA){}
    DoB(object inputB){}
}

class ConcreteWorker2 : IWorker
{
    DoA(object inputA){}
    DoB(object inputB){}
}

class ConsumerA
{
    HandleA(object inputA)
    {
        var worker = factory.GetByKeyA(inputA.Key);
        worker.DoA(inputA);
    }
}

class ConsumerB
{
    HandleB(object inputB)
    {
        var worker = factory.GetByKeyB(inputB.Key)
        worker.DoB(inputB)
    }
}

How to load entity from multiple tables with Dapper?

In my app i use Entites as Tables in database representation.

I have an OrderEntity, that have fields like ProductEntity, CustomerEntity, then CustomerEntity has fields like AddressEntity etc.

Now I try to get OrderEntity filled with all the entity-type properties and so on. It looks like I have to load data from 8 tables.

I just have no idea how to do it properly. I have a OrderRepository with Get method, wher I want to return OrderEntity. So should I create SQL with 7 joins, one class with all the columns from the SQL and then after executing SQL create manually OrderEntity etc. in this repository's Get method?

Using repository etc. is easy when I have to get/update 1 table, but when the model is built of more than 1-2 tables, It's becomming really tough for me.

Regexp used in pattern meta-annotation for email works does not work but does somewhere else

I want to validate a list of emails with a regexp thru Spring's bean validation. A valid list of email is like follows:

  • someone@mail.xxx, someother@mail.xxx, anotherone@mail.xxx
  • someone@mail.xxx, someother@mail.xxx, anotherone@mail.xxx,
  • someone@mail.xxx , someother@mail.xxx,
    anotherone@mail.xxx

An invalid list may look like:

  • some one@mail.xxx someother@mail.xxx, anotherone @mail.xxx
  • , someone@mail.xxx someother@mail.xxx, anotherone @mail.xxx

The username of a valid email is a sequence of characters other than space and new line. The same aplies for the domain name and the domain suffix.

Additionally, the number of spaces or new lines between the actual email and its preceding or following comma does not matter, but there cannot be spaces nor new lines in the actual emails.

I follow the suggestions of other really helpful answers to provide a custom validator and I have this one:

@Email(message = "Please provide a list of valid email addressess")
@Pattern(regexp = "([^ \\n]+@[^ \\n]+\\.[^ \\n]+(^( |\\n| \\n)$)*(,)*(^( |\\n| \\n)$)*)+", flags = Flag.CASE_INSENSITIVE, message = "Please provide a list of valid email addresses")
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE })
@Retention(value = RetentionPolicy.RUNTIME)
@Constraint(validatedBy = {})
@Documented
public @interface ExtendedEmailListValidator {
    String message() default "Please provide a list of valid email addresses";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};
}

However, all email lists do not match except the case of a list with just one element.

Tried to at least prove some basic lists with a pattern/matcher set like so:

String input = "";
Matcher m = null;
Pattern p = Pattern.compile("((( |\\n| \\n))*[^ \\n]+@[^ \\n]+\\.[^ \\n]+(( |\\n| \\n))*,*(( |\\n| \\n))*)+");

input = "someone@mail.xxx";
m = p.matcher(input);
System.out.println(input + ": " + m.matches());

input = "someone@mail.xxx, anotherone@mail.xxx";
m = p.matcher(input);
System.out.println(input + ": " + m.matches());

input = "someone@mail.xxx,anotherone@mail.xxx";
m = p.matcher(input);
System.out.println(input + ": " + m.matches());

input = "someone@mail.xxx, an other one@mail.xxx";
m = p.matcher(input);
System.out.println(input + ": " + m.matches());

input = "someone@ma      il.xxx, anotherone@mail.xxx";
m = p.matcher(input);
System.out.println(input + ": " + m.matches());

and the output is as expected:

someone@mail.xxx: true
someone@mail.xxx, anotherone@mail.xxx: true
someone@mail.xxx,anotherone@mail.xxx: true
someone@mail.xxx, an other one@mail.xxx: false
someone@ma      il.xxx, anotherone@mail.xxx: false

What am I doing wrong or what is missing in order for the custom validator to work? Thanks in advance!