mardi 31 octobre 2023

circular dependencies when trying to separate functionality (webservice sync)

I am contacting you today regarding a recent problem with circular dependencies. It's about a Spring boot application that accepts data via a Rest API and then forwards it to an internal Spring service. When a new vehicle is to be created, then first a CarDto is submitted via Rest. The controller uses a car mapper (Mapstruct) to create a car object from it and passes it to the CarService. However, the CarService cannot save the object immediately. First, the object is enriched with further information. This information comes from a web service. If an error occurs during the retrieval (e.g. because the manufacturer is not known to the web service), an exception is thrown and the CarService does not perform persistence. However, if the web service receives a result, it expands the object using the vehicle mapper (also a map construct) and returns the object to the service. The service can now save the object. For its functionality, however, the mapper absolutely needs access to the CarService to retrieve further information from the database in order to extend the Car object.

Now comes the difficult point: the information from the web service can change in principle. This means that the information in the database must be regularly compared with the web service. For this purpose, the following steps must be taken:

  • Pull all car objects from the database (due to the quantity with paging).
  • Synchronize objects with web service
  • Update objects in case of changes
  • then persist them again

Currently I have this functionality stuck in the VehicleService. To fetch the elements and save them, however, it needs the CarService (circular dependency). I could now put the sync function in the CarService, but then the question is when the translation from the Vehicle to the Car object should take place. If the translation should take place within the VehicleService, then I need the VehicleMapper in the VehicleServices. However, the VehicleMapper needs the CarService again. If I want to map the returns of the web service to a Car object in the VehicleService, I only need a DTO for the transfer of the information from the Car to the VehicleService. I don't really like that either.

I have hope that you guys have tips. Gladly also with the consequence eiens Refactorings.

For better illustration I have created a small class diagram. Please forgive me if not all characters fit perfectly - unfortunately I am not an uml expert.

https://i.stack.imgur.com/YRmdO.png

lundi 30 octobre 2023

Qt - Connect()ing Many Ui Objects

I'm currently trying to create a single window/page Qt application which has many interacting widgets (important to note), however I'm having difficulty finding a good way to structure the project.

As the title implies and is often suggested, I've tried using the "Promote To" feature in QtDesigner, as well as creating new Qt Designer Form classes for each individual widget to modularize and keep the code clean (is this even a good idea?), however there is no good way to use the QObject::connect method in this case that I am aware of, as you must pass both widgets as arguments, which you cannot do with separate designer form classes, unless you include the generated ui_*.h file, or use something such as a singleton/monostate to create a new object and access it that way, if Qt would even jive with that.

The only other option(s) I am aware of with my current knowledge is to make everything a function member of MainWindow, which seems like a terrible idea, or I could discard designer forms altogether and create widgets entirely in code (undesirable, but I will if needed), and instantiate and connect them in MainWindow.cpp, but seems like it will lead to a single monolithic MainWindow file over time.

I find example code of my problem to be difficult to find. Other projects don't seem to have such issues as they are (seemingly) mostly standalone, isolated widgets. In the end I'm leaning towards the latter option of foregoing the ui files and instantiating & connecting most of the widgets in MainWindow.cpp, but I'm not sure if this is the best solution. Here is a basic flowgraph of my problem: https://albumizr.com/a/a35j

How should multiple microservices interact with shared data?

I'm new to microservices but one thing I understand (at least as a principle) is that each microservice should be independent.

Interactions between microservices should only happen through well defined interfaces, preferably APIs and not a shared database.

Let's say I have a simple web app which displays some content to public users. Internal users (admins) access an internal web interface and write stuff into a database table. If they "approve", the whole content of the table can be made public.

Now, without microservices I could do a lot of stuff.

For example, I could have both services point to the same table and add a "public" flag.

Or I could set up two tables, one "public" and one "private", and ensure that the approval process copies the private table into the public one.

But all these solutions imply that both services access the same database or, at least, that they interact via SQL queries and not REST APIs.

I would be tempted to bundle everything in a single microservice.

But it doesn't feel right: the public service may have different requirements in terms of scalability and so on. And if the "internal" website stops working it shouldn't necessarily disrupt the existing public app. So why couple those components?

This example may be too specific but I suspect the underlying issue is applicable to many use cases.

Display list on a screen with three options

I am working with a database containing people, each having an isRetired parameter.

By default, I retrieve non-retired people, but I need to implement functionality on the screen to display people in three ways:

  • Active (non-retired people only),
  • Retired (retired people only), and
  • All (both retired and non-retired people).

How can I achieve this functionality in my application?

There is the problem, that i can retrieve data only by retired false or true. I thought by adding new parameter "ShowAll" and add if statement to service method(like is ShowAll=true then query without retired), but it seems confusing for me as when someone will debugging he could see like wow: ShowAll is true but Retired is false or true. What is going on and what data should be received? Does C# have any feature for this?

Here is my DTO I`m working with

public class PeopleDto
{
    public string Name { get; set; }
    public bool Retired { get; set; }
}

My Controller

[HttpGet]
public ActionResult<PaginatedResult<People>> GetAll([FromQuery] PeopleDto peopleDto) => Ok(_peopleService.GetAll(peopleDto));

Here is my Service method

public PaginatedResult<People> GetAll(PeopleDto peopleDto)
    {

        var peopleList = _dbContext.People
            .Where(people => String.IsNullOrEmpty(peopleDto.Name)
                                    || people.Name.Contains(peopleDto.Name))
            .IsRetired(peopleDto.Retired)
            .OrderBy(people => people.Id)
            .ToList();

        int totalItems = _dbContext.People
            .IsRetired(peopleDto.Retired)
            .Count(people => String.IsNullOrEmpty(peopleDto.Name)
                                    || people.Name.Contains(peopleDto.Name));
        
        var paginatedPeople = new PaginatedResult<People>
        {
            Items = peopleList,
            TotalCount = totalItems,
        };

        return paginatedPeople;
    }

public static class QueryableExtensions
{
    public static IQueryable<T> IsRetired<T>(this IQueryable<T> query, bool isRetired) where T : People =>
        query.Where(people => people.Retired == isRetired);
}

dimanche 29 octobre 2023

Prevent input validation on an input prarameter of a method

Currently:

`void deleteCase(caseId, version){ var case = getCase(caseId); if(case is null) throw ArgumentNullException(caseId);

if(verifyVersion(case, version) == false) return;

return delete(case); } bool verifyVersion(case, version){ if(version is null) throw ArgumentNullException(version);

// call db to verify the version is mathching

}`

deleteCase(1, null) => it throws an exception as version cannot be null

Question: now we have a situation we can delete a case without providing its version, it means being able to call deleteCase without providing version.

Solution 1: add an optional flag indicating no need to check version `void deleteCase(caseId, version, checkVersion = true){ var case = getCase(caseId); if(case is null) throw ArgumentNullException(caseId);

if(checkVersion == true AND verifyVersion(case, version) == false) return;

return delete(case); }`

old calls: deleteCase(1, null) => works as expected before since checkVersion is by default true deleteCase(1, "1.0") => works as expected before since checkVersion is by default true new calls: deleteCase(1, null, true) => works as expected before deleteCase(1, null, false) => works as we want deleteCase(1) => works as we want

The problem with that is we've added a new parammer to control another parameter => not accepted. And also we should not be able to do deleteCase(1, "1.0", false) which version is redundant

Solution 2: overload deleteCase to not having version parameter

`void deleteCase(caseId){ var case = getCase(caseId); if(case is null) throw ArgumentNullException(caseId);

return delete(case); } void deleteCase(caseId, version){ var case = getCase(caseId); if(case is null) throw ArgumentNullException(caseId);

if(verifyVersion(case, version) == false) return;

return deleteCase(caseId); }`

Now any deleteCase calls wrok as expected. But the only problem is getCase gets called twice if pass version which makes it anti performant.

Any idea what can we do to make one call?

Architecture of C++ matrix classes: inheritance or specialisation?

I would like to define a class : template <class T, std::size_t M, std::size_t N> class Matrix with simple and classic methods applied to any matrix (std::array<std::array<T, N>, M> m_data;).

I then want to have specialised classes such as: template <class T> class Matrix<T, 2, 2>. Ideally I want to be able to use the generic methods of the first class in the specific class. To do this I was thinking of creating a template class <class T> class Matrix2x2 : public Matrix<T, 2, 2> to have heritage. The problem is that to use for example the method class Matrix<T, M, N>::transpose() from Matrix2x2 I have to cast the value returned in Matrix2x2, something I'd rather avoid. Matrix2x2<T> and Matrix<T, 2, 2> are completely equivalent in practice, so using class specialisation seems appropriate, but then you have to rewrite all the methods and either duplicate some code or create an instance of the non-specialised class and I want some specific methods for specific dimension (e.g. rotation) in each corresponding method.

I've tried using inheritance, it works but I have a lot of code duplication, I'd like to refactor all the code. What's the best design? Is there a better solution?

Thank you for your help.

Best algorithm for planning a trip between two places that completes the most errands along the way?

I am given a list of errands to complete. Each errand has a duration and location. A location is open/closed depending in the time and day of the week.

On a given day, I will take a trip from an origin to a destination. The earliest departure and latest arrival times are defined by depart_after and arrive_by.

I want to plan the a route that covers as many errands as possible along the way while still arriving at my destination on time.

At a high level, how would you approach solving this problem? I am thinking Dynamic Programming, but am not sure if there is an even more efficient way.

I plan on leveraging googlemapsapi distance_matrix(locations, departure_time) which returns a matrix of travel times for a list of locations. I would like to minimize calls to this function.

Example input:

trip_info = {'day': '2023-02-28',
             'origin': 'Work', 
             'destination': 'Home',
             'depart_at': '9:30', 
             'arrive_after': '12:00'}

errands = {'Drop off dry cleaners': {'duration': "10mins",
                                     'location': "Mikes Dry Clean",
                                     'opening_close_hours': {'Mon-Fri': [('07:00', '20:00')],
                                                             'Sat': [('09:00', '18:00')]}},
           'Buy groceries': {'duration': "45mins",
                             'location': "Midtown Market",
                             'open_close_hours': {'Mon-Fri': [('07:00', '20:00')],
                                                  'Sat-Sun': [('10:00', '19:00')]}},
           'Refill gas': {'duration': "20mins",
                          'location': "Springfield Costco",
                          'open_close_hours': {'Mon-Wed': [('07:00', '20:00')],
                                               'Fri': [('09:00', '18:00')]}}}

Sample output:

best_route=(
    {'location': "Work", 'errand': None, 'arrive': None, 'depart': '10:00'},
    {'location': "Springfield Costco", 'errand': 'Refill gas', 'arrive': '10:23', 'depart': '10:43'},
    {'location': "Midtown Market", 'errand': 'Buy groceries', 'arrive': '11:00', 'depart': '11:45'},
    {'location': "Home", 'errand': None, 'arrive': '12:00', 'depart': None}
) 

samedi 28 octobre 2023

Linux - Strip lines with zero at end

I have a last hurdle to solve, but my pattern matching isn't yet up to the task. I have a report and I want to strip out lines with 0 at the end of them... eg.. strip the first line, but leave the second in the output.

196 Reallocated_Event_Count 0x0032   100   100   000    Old_age   Always       -       0
199 UDMA_CRC_Error_Count    0x000a   200   200   000    Old_age   Always       -       22

Tried various sed combinations and failed.

Preserve order of inputs to outputs, while each output comes from a file that should get read once

I'm struggling to come up with the best way to structure my program, regarding a specific function.

Here are some details:

  • The input to the function is a vector of (latitude, longitude) coordinates
    • These can be in whichever order the user supplies
  • The output of the function should be the elevations at the input coordinates, in the same order as the inputs
  • The elevations are retrieved by accessing pixel values in TIFF files that are named by whole number latitude, longitude coordinates, e.g. n40w106, n40w107, ...
    • This number represents the top left corner, for example:
      • (39.5, -105.5), (39.8, -105.2) would both be in n40w106.tif
      • (40.3, -106.1), (40.5, -106.9) would both be in n41w107.tif
    • This means that multiple points in different spots in the input vector could need to be retrieved from the same file
  • I already have the all of the functionality to take input points and retrieve the elevation from the corresponding files

What I am struggling with is these extra requirements that I want to ensure:

  • Each file should only get loaded once
  • Only store the file's data in memory if it is being used currently (so I don't think caching will work)
  • The order of the outputs should correspond to the order of the supplied inputs

Is there some existing paradigm or concept in CS that achieves what I want?

I'm also interested in if there is a model that works well with concurrency. For reference, I am using the Rust programming language.

Batch workloads vs calls to microservices

This is quite a general question. I am quite new to all of this and I am having trouble deciding if something should be considered a batch job or a simple request to a microservice.

Let's say users can upload 30-second videos to S3 and we want to, for some reason, process every video such that the individual images of the video are extracted and stored in S3 again. Also, we do not really care about the latency, and minimizing compute costs, i.e., the cloud bill, is more important.

Would you use something like AWS Batch? Or would you deploy a set of microservices that do the processing by responding to API service calls, possibly with a messaging queue between S3 and the microservices?

Both options seem to do the job, but what is the right or correct way to approach such a problem?

I have read over https://docs.aws.amazon.com/batch/latest/userguide/best-practices.html. For short jobs, it says that you would need to merge jobs such that they run, ideally, 3 to 5 minutes each. However, it does not really talk about what should not be considered a batch job.

I feel like this question should be googleable, but I might just be missing the right terminology here.

vendredi 27 octobre 2023

Design pattern for supporting transferring data from multiple sources to destinations

I am working on a small program - the main feature of the program it to 'transfer' 'data' from one 'place' to another, and also record stats (like timestamps, success or not, etc.) to sqlite db. Besides, the program should be able to retry for a few times if transfer fails.

Currently, the assumptions for 'data', 'place' and 'transfer' is simple:

  • the data can only be a file in the host machine
  • the destination can be a location in the host machine or a remote server
  • the methods for transferring the data can only be 'rsync' (which uses rsync command in the host machine)

I have 2 main questions:

  1. What is an appropiate design pattern for this program, if the program may scale in the future. There could be more methods for transferring data such as ftp, cloud server command line tools, etc. The program may need to handle if the the data is a directory (in which case, it will transfer the entire directory to the destination). The database it records stats to could be other types like mysql or postgres.
  2. How should 'record stats to sqlite db' be related to the transfer feature? Is it better to separate them?

jeudi 26 octobre 2023

Why to use factory pattern

I am trying to understand the Factory Method design pattern and i have come across multiple questions similar to the one on my mind but my question still remains unanswered.

this is the article I am referring in my question

In the example mentioned in above article why do we need a concrete factory of HtmlDialog and WindowsDialog and at the main method choose one of the implementations of Dialog, instead of directly choosing the implementation of Button from the available HtmlButton and WindowsButton

Designing a Platform to Serve Multi-Tenancy with Processing data from Batch, REST and Queues

I m trying to design a Platform which can have multiple Publishers and Consumers. It can expose the Layer on REST API as well as GRAPHQL. Now if we want to have an Orchestration or Workflow layer which supports following things

  1. SAGA base Message Processing.
  2. REST API based Step by Step execution
  3. REST API based Orchestration

with keeping all the Microservices decoupled and Transformation; Routing done through the Workflow/Orchestrator itself. Any Tool or Framework in market can help such as NETFLIX Conductor. Need Suggestions on this how can move forward.

At the end it needs to

  1. Easy to Configure -- while adding new API; New services.
  2. Support Observailibility
  3. Plug and Play configuration
  4. Things such as Service discovery and Cloud Agnostic if required

mercredi 25 octobre 2023

Mmapping shared memory in C giving Invalid argument error when I change the offset to anything nonzero

I'm trying to open a shared memory file, write in it, fork to new processes, then call execl to run other components, then in those components I want to access the shared memory created in the parent. But I dont want the entire structure, only part of it. So I use offsetof to find the offset and pass that into mmap. Problem is, it gives an Invalid argument error when I change the offset to anything other than zero. It works fine with zero.

I've made a minimal dummy program with the same error, and the code for the larger program is too big. `

#include<stdio.h>
#include<unistd.h>
#include<sys/mman.h>
#include<stddef.h>
#include<fcntl.h>

typedef struct test
{
    int moo;
    char hello;
}Lil;


typedef struct bigstruct
{
    int a;
    char cow;
    Lil lil;
}Big;

int main()
{
    int fd = shm_open("/moomor", O_CREAT | O_RDWR, 0666);
    if(fd == -1)
    {
        perror("shmopen");
        return 1;
    }
    ftruncate(fd, sizeof(Big));
    Big * big = (Big *)mmap(NULL, sizeof(Big), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
    if(big == MAP_FAILED)
    {
        perror("mmap");
        return 1;
    }
    big->lil.hello = 'h';
    printf("hello: %c\n", big->lil.hello); //prints correctly
    munmap(big, sizeof(Big)); //tried it with this in and out

    int offset = offsetof(Big, lil); //gives offset of eight
    printf("Offset: %d\n", offset);
    Lil *lily = (Lil *)mmap(NULL, sizeof(Lil), PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
    if(lily == MAP_FAILED)
    {
        perror("mmap"); //this causes an error
        goto cleanup;
    }
    printf("HH: %c\n", lily->hello);
    munmap(lily, sizeof(Lil));

    cleanup:
    shm_unlink("/moomor");
    close(fd);
}

PHP facade pattern object reuse

for performance reasons, im trying to reuse facade object which is passed to provided handler, there is a simplified demonstration of what im trying to achieve:

class A
{
  public $b,$f;
  function __construct($f)
  {
    $this->b = new B($this);
    $this->f = $f;
  }
  function invoke()
  {
    ($this->f)(new B($this, 1)); # this works
    ($this->f)($this->b->set(1)); # this fails
  }
}
class B
{
  function __construct(
    private $a,
    private $i=0
  ) {}
  protected function set(int $test): self
  {
    $this->test = $test;
    return $this;
  }
  function get() {
    return $this->i;
  }
}
$a = new A(function(object $b) {
  $b->get();# OK
  $b->set(2);# FAIL, kind of protected
});
$a->invoke();

i tried inheriting both classes from an empty abstract object, but without luck.

im expecting that there is some language feature that makes friendly objects or approach im unaware of.

Creating a Dual-Package Design System Library for JSF and Angular/PrimeNG: Is it Feasible?

I am embarking on a project to develop a design system library which caters to both JSF and Angular/PrimeNG frameworks. The idea is to have two separate packages within the library - one dedicated to JSF components and the other to Angular/PrimeNG components. The goal is to make this library flexible enough to be integrated into either a JSF project or an Angular/PrimeNG project seamlessly.

Here’s a rough outline of how I envision the library structure:

Design System Library

  • Package 1: JSF Components
    • Contains reusable JSF components adhering to the design system guidelines.
  • Package 2:
    • Angular/PrimeNG Components Contains reusable Angular components with PrimeNG, also adhering to the same design system guidelines.

Each package would be independently usable but adheres to the same design principles and guidelines to ensure consistency across projects, regardless of the framework being used.

I aim for a setup where developers can choose the relevant package based on the framework they are working with, and have a consistent design experience.

Here are some specific areas where I could use some guidance:

  • Is this dual-package structure a feasible approach for creating a design system library that serves both JSF and Angular/PrimeNG projects?

  • Are there any existing tools or practices that could facilitate the management and distribution of these packages?

  • Are there any examples of similar dual-package design system libraries, especially those serving different frameworks, that I could look at for reference?

what's the different between render props pattern and custom hook pattern?

here's render props pattern

export const flip = () => ({
  flipResults: Math.random(),
});

export const CoinFlipLogic = ({ children }) => {
  const [state, setState] = useState(flip());
  const handleClick = () => setState(flip());

  return children({
    rerun: handleClick,
    isHeads: state.flipResults < 0.5,
  });
};

export const CoinFlip = ({ showLabels, showButton }) => {
  return (
    <CoinFlipLogic>
      {({ rerun, isHeads }) => (
        <>
          {showButton && <button onClick={rerun}>Reflip</button>}

          {isHeads ? (
            <div>
              Head
              {showLabels && <span>Heads</span>}
            </div>
          ) : (
            <div>
              Tails
              {showLabels && <span>Tails</span>}
            </div>
          )}
        </>
      )}
    </CoinFlipLogic>
  );
};

and here is custom hook pattern

export const useCoinFlipLogic = () => {
  const [state, setState] = useState(flip());
  const handleClick = () => setState(flip());

  return {
    rerun: handleClick,
    isHeads: state.flipResults < 0.5,
  };
};

export const CoinFlip = ({ showLabels, showButton }) => {
  const { rerun, isHeads } = useCoinFlipLogic();
  return (
    <>
      {showButton && <button onClick={rerun}>Reflip</button>}
      {isHeads ? (
        <div>
          Head
          {showLabels && <span>Heads</span>}
        </div>
      ) : (
        <div>
          Tails
          {showLabels && <span>Tails</span>}
        </div>
      )}
    </>
  );
};

IMO, I prefer custom hook since I think it's more readable.

my question is:

what's the main different between those two design patterns and how should I choose which one to use when it comes to design my react component, and which pattern is used more in real world?

lundi 23 octobre 2023

Abstracting and connecting 2 external libraries

I'm writing the UI layer for my embedded C++ project. For graphic manipulation, I wanted to use the Adafruit_GFX library. I've created an interface

class IRenderer {
public:
    virtual void drawPixel(int16_t x, int16_t y, uint16_t color) = 0;
    virtual void drawCircle(
            int16_t x0,
            int16_t y0,
            int16_t r,
            uint16_t color
        ) = 0;
    };
    ...

and connect my interface via bridge with actual library:

class AdafruitRendererBridge : public IRenderer {
private:
    Adafruit_GFX &gfx;

public:
    virtual void drawPixel(uint16_t x, uint16_t y, uint16_t color) {
        gfx.drawPixel(x, y, color);
    }

    ...

    AdafruitRendererBridge(Adafruit_GFX &_gfx) : gfx(_gfx) {}
};

That way, I'm making my code independent of the external library API. Also, I'm making my code testable, as now I can create mock implementing this interface and run unit tests on my host machine without the actual hardware environment that this library needs. Now I'd like to use another external library, ArduinoMenu, that would create a UI for me using provided renderer. The problem is that this library needs a concrete object of the Arduino_GFX type. I've abstracted it and just used my interface. What would be the solution here to initialize ArduinoMenu while using my interface?

I think using template here is an option; however, I'd like to get an explicitly defined set of methods that need to be present, like interfaces do.

Other option is to create some kind of revered bridge:

class RendererAdafruitBridge : public Adafruit_GFX {
private:
    IRenderer &renderer;

public:
    virtual void drawPixel(int16_t x, int16_t y, uint16_t color) override {
        renderer.drawPixel(x, y, color);
    }
   
    ...

    RendererAdafruitBridge(IRenderer &_renderer) : renderer(_renderer) {}
};

However, not every method in Adafruit_GFX that I would need is marked as virtual. Also, there are a lot of methods in Adafruit_GFX and I would need to list them all twice. First in IRenderer and now in this reversed bridge kind of thing.

To build a REST API using Generics? What design pattern can I use?

I'm creating a system. However, I'm unsure of how I can build it following a certain pattern. What would be the most suitable one considering a more secure system?

I'm trying to find a design pattern and wanting to use Generics to write an article using Spring Security and Java 17.

How do I disable the 'uncategorized' block pattern category in WordPress?

I want to disable the uncategorized block pattern category in WordPress, how do I achieve this?

I have used the following code and it doesn't work, what do I do, any suggestions would be appreciated:

function remove_uncategorized_pattern_category() {
    unregister_block_pattern_category( 'uncategorized' );
}

add_action( 'init', 'remove_uncategorized_pattern_category' );

Multiple Originators in Memento

I have been given code for a game. My assignment is now have button to save the state of this game and to restore it this saved state. In the code there is a Game Window and there is a Game Engine (main loop and logic).

I want to apply the memento pattern here. Initially, I thought that I could make the game engine the originator since here the references to classes that need to be reset are stored (e.g. Player): in this class is my save memento where I copy the variables and set it in the memento + restores memento where I reset the variables from the memento.

However, in Game Window there now also appears to be some variable stored that I need to save and reset in the Memento. Therefore, I now am wondering if I could have multiple originators: so both classes save to the memento and both restore? I still would have one memento class and one caretaker.

Now, I am wondering if it is possible in the memento pattern to have multiple originators and if this seems like a good design? Or otherwise what are other options I can do?

dimanche 22 octobre 2023

Cart Implementation - is it ok to do a server call on each CRUD operation?

I am watching a tutorial about ECommerce Website with .Net Core - and the project is of type Web Assembly Blazor and I checked the .NET CORE Hosted, so the project spited to Client, Server and Sheared.

And the Cart model is consists of CartId, ProductId and UserId.

    public class CartItem
    {
        public int CartId { get; set; }
        public int UserId { get; set; }
        public int ProductId { get; set; }
        public int Quantity { get; set; } = 1;
    }

When the instructor implemented the Cart Model he was using the local storage only on the client side and he gets the Product details with a one server Call

Server service

    public interface ICartService
    {
        Task<ServiceResponse<List<CartProductResponse>>> GetCartProducts(List<CartItem> cartItems);
    }

Client service

    public interface ICartService
    {
        event Action OnChange;
        Task AddToCart(CartItem cartItem);
        Task<List<CartItem>> GetCartItems();
        Task<List<CartProductResponse>> GetCartProducts(); 
        Task RemoveProductFromCart(int productId, int productTypeId);
        Task UpdateQuantity(CartProductResponse product);
    }

So until now every thing make sense in my brian, all CURD operations are mainly on the Client side. But after he did the migration of local storage to the database. The CRUD operations are on both client and server side

Server service

    public interface ICartService
    {
        Task<ServiceResponse<List<CartProductResponse>>> GetCartProducts(List<CartItem> cartItems);
        Task<ServiceResponse<List<CartProductResponse>>> StoreCartItems(List<CartItem> cartItems);
        Task<ServiceResponse<int>> GetCartItemsCount();
        Task<ServiceResponse<List<CartProductResponse>>> GetDbCartProducts();
        Task<ServiceResponse<bool>> AddToCart(CartItem cartItem);
        Task<ServiceResponse<bool>> UpdateQuantity(CartItem cartItem);
        Task<ServiceResponse<bool>> RemoveItemFromCart(int productId, int productTypeId);
    }

Client service

public interface ICartService
{
   event Action OnChange;
   Task AddToCart(CartItem cartItem);
   Task<List<CartProductResponse>> GetCartProducts();
   Task RemoveProductFromCart(int productId, int productTypeId);
   Task UpdateQuantity(CartProductResponse product);
   Task StoreCartItems(bool emptyLocalCart);
   Task GetCartItemsCount();
}

My questions is:

Is that Ok/practical? having a call to the server on each cart change/update?

My suggestion:

if we could update the server side on section ends or on checkout only, but i have no idea if this possible or not

samedi 21 octobre 2023

React paradigm: props vs useImperativeHandle

I was discussing with one of my team members about the design pattern for React components. I am a little perplexed about whether we should use props to pass down what we need or encapsulate the component and expose interfaces externally (more like an OOP concept). Here is the StackBlitz demo. If someone could give some advice or share any articles/documents online, that will be really appreciated. https://stackblitz.com/edit/stackblitz-starters-j6pvsq?file=src%2FApp.tsx

I have both approaches implemented in the StackBlitz. Please refer to that.

Compound with Render Props pattern TypeScript issue

I defined BodyProps type in Table.Body component where I know for now that I will receive two interfaces of data - Cabin and CabinReservation. I defined in BodyProps, data as a union of those two interfaces as I assumed it would guarantee safety and as the Compound component is highly reusable it will accept those two interfaces in different situations without any problems. Now in the BookingTable when I'm passing into render prop pattern how I would display the passed data using BookingRow component where inside of it I defined its BookingRowProps type interface where booking is assigned to CabinReservation as I will only use this data here, it spits error in previously mentioned render that passed booking prop is Type 'CabinReservation | Cabin' is not assignable to type 'CabinReservation'.. Do I need to also define a union in BookingRow to pass the issue or is there a different, better approach? I still learning best practices in defining types with TypeScript so every piece of advice will be appreciated.

Type 'Cabin | CabinReservation' is not assignable to type 'CabinReservation'.
  Type 'Cabin' is missing the following properties from type 'CabinReservation': startDate, endDate, numNights, numGuests, and 4 more.ts(2322)

BookingRow component

type BookingRowProps = {
  booking: CabinReservation;
};

function BookingRow({
  booking: {
    id: bookingId,
    created_at,
    startDate,
    endDate,
    numNights,
    numGuests,
    totalPrice,
    status,
    guests: { fullName: guestName, email },
    cabins: { name: cabinName },
  },
}: BookingRowProps) {
  const statusToTagName = {
    unconfirmed: 'blue',
    'checked-in': 'green',
    'checked-out': 'silver',
  };

  return (
    <Table.Row>
      <Cabin>{cabinName}</Cabin>

      <Stacked>
        <span>{guestName}</span>
        <span>{email}</span>
      </Stacked>

      <Stacked>
        <span>
          {isToday(new Date(startDate))
            ? 'Today'
            : formatDistanceFromNow(startDate)}{' '}
          &rarr; {numNights} night stay
        </span>
        <span>
          {format(new Date(startDate), 'MMM dd yyyy')} &mdash;{' '}
          {format(new Date(endDate), 'MMM dd yyyy')}
        </span>
      </Stacked>

      <Tag type={statusToTagName[status]}>{status.replace('-', ' ')}</Tag>

      <Amount>{formatCurrency(totalPrice)}</Amount>
    </Table.Row>
  );
}

export default BookingRow;

BookingTable component

function BookingTable() {
  const { bookings, isLoading } = useBookings();

  if (isLoading) return <Spinner />;
  if (bookings.length === 0) return <Empty resourceName="bookings" />;

  return (
    <Menus>
      <Table columns="0.6fr 2fr 2.4fr 1.4fr 1fr 3.2rem">
        <Table.Header>
          <div>Cabin</div>
          <div>Guest</div>
          <div>Dates</div>
          <div>Status</div>
          <div>Amount</div>
          <div></div>
        </Table.Header>

        <Table.Body
          data={bookings}
          render={booking => <BookingRow key={booking.id} booking={booking} />}
        />
      </Table>
    </Menus>
  );
}

Table Compound component

type StyledCommonRow = {
  columns: string | null;
};

type TableProps = {
  columns: string;
  children: React.ReactNode;
};

type HeaderProps = {
  children: React.ReactNode;
};

type RowProps = {
  children: React.ReactNode;
};

type BodyProps = {
  data: Cabin[] | CabinReservation[];
  render: (data: Cabin | CabinReservation) => React.ReactNode;
};

export default function Table({ columns, children }: TableProps) {
  return (
    <TableContext.Provider value=>
      <StyledTable role="table">{children}</StyledTable>
    </TableContext.Provider>
  );
}

function Header({ children }: HeaderProps) {
  const { columns } = useTableContext();

  return (
    <StyledHeader role="row" columns={columns} as="header">
      {children}
    </StyledHeader>
  );
}
function Row({ children }: RowProps) {
  const { columns } = useTableContext();

  return (
    <StyledRow role="row" columns={columns}>
      {children}
    </StyledRow>
  );
}

function Body({ data, render }: BodyProps) {
  return <StyledBody>{data.map(render)}</StyledBody>;
}

How I do a nice design of a hardcoded list in Java? [closed]

In java I have a list of object in code, I need to know what is a nice design to do that, eg: I had an ideia like a config file in this all companies in json format, but i don't if it is really worth.

public List<Company> getAllCompany() {
 
 List companies = new ArrayList<>();
 
 companies.add("Facebook","Silicon Valley","www.facebook.com");
 companies.add("Google","Silicon Valley","www.google.com");
 companies.add("Intel","Silicon Valley","www.intel.com");
 companies.add("Nvidia","Silicon Valley","www.nvidia.com");

 return companies;

}

I need to improve my design, wanna just know the possibilities and how other people think about it.

vendredi 20 octobre 2023

Why is the Open/Closed Principle in software development implemented using abstract classes?

enter image description here

Please look at the code above. The teacher told us that abstract classes can be used as a tool to implement the Open/Closed Principle in software development. The code above is used as an example to illustrate this. The teacher said that common methods for all vehicles, such as Stop and Fill, are encapsulated in the Vehicle class. Different implementations of these methods are achieved in Car and Truck classes through override. I understand this approach, but I don't think it's necessary to use abstract classes. We can achieve the same with regular classes, right?

Set Vehicle as a regular class, implementing only the Stop and Fill methods within it. Then, let Car and Truck inherit from Vehicle and implement their respective Run methods. At the beginning of the program, use

Var v = new Truck()

or

Truck v = new Truck() 

and still be able to use

v.Run()

So, I don't understand the necessity of using abstract classes?

Nestjs execution after pipe but before the method handler

Can I add any execution after all pipes transform but before the method handler? enter image description here

How to limit the number of selected tags displayed in the Select component in chakra ui

Did Chakra UI's Select component have a maxTagCount prop like in Antd i wante to move up from this Design enter image description here to this one enter image description here

Did anybody have idea

<Select size="sm" isMulti placeholder='Brand' />

jeudi 19 octobre 2023

Why do I need the "Iterator pattern" for parallel iteration over a collection?

E.g. the following code allows parall iteration over a list without throwing an exception. So why do I need the Iterator pattern for parallel iteration?

    public static void main(String[] args) {

    List<Integer> myList = Lists.newArrayList();
    for (int i = 0; i < 1000; i++) {
        myList.add(i);
    }

    new Thread(new Runnable() {
        @Override public void run() {
            for (final Integer integer : myList) {
                System.out.println("Thread-A");
            }
        }
    }).start();

    new Thread(new Runnable() {
        @Override public void run() {
            for (final Integer integer : myList) {
                System.out.println("Thread-B");
            }
        }
    }).start();
}

mercredi 18 octobre 2023

Print Pattern in java [closed]

I I'm working on a pattern program in [programming language] and I'm running into some issues. I want to create a specific pattern, but I'm having trouble achieving it. Here's what I'm trying to want to generate a pattern that looks like this:

10
4 9
3 5 8
1 2 6 7

mardi 17 octobre 2023

SSRS Report Design : Present Rows of data in a column of database

I would need help in design of a table with rows of data from a column called txtColumn.

Adding this to my table, repeats the 1st row multiple times in my report.

It has to list different rows in order of listing.

Can you please guide how to use Visual studio to get this SSRS report fully functional please?

Added a table to the SSRS report and added txtColumn to a row.

Result on run is to find row1 repeated multiple times.

Which class implements the factory method?

Is the factory method in the factory method pattern part of a dedicated factory object or part of the business object where I want to use the method?

Basically, will I need to inject a factory object from where I create objects or does the object become a factory itself and I simply call the implemented method to create an object?

In the first case I don't see the advantage of a factory method over a simple factory object where I can e.g. animalFactory.createDog().

Is this Command Pattern or Strategy Pattern?

UML-diagram of a pattern

This is an image from an old exam I'm working through. Through the UML-diagram, as seen above, how can I determine if this is Command Pattern or Strategy Pattern?

The answer to the question is that is is Command Pattern and Composite Pattern. Clearly, it is Composite because of Block have multiple aggregations for Statement. I understand that it is Command Pattern since they use execute() in an interface which then is implemented in several subclasses, altough couldn't this technically also be seen as Strategy Pattern?

I don't really understand the difference between the two of them in concrete code, as I tend to see it as the same code just used in different ways, thus an UML-diagram would therefore be able to be either Pattern. In this case though, answering Strategy would give less points than Command Pattern.

How to conditionally select concrete implementation for strategy pattern using Dependency Injection C#

I am trying to understand the Strategy Pattern in order to utilise it for a problem I have.

The current code looks as such where I have an amount that I want to process based on a payment type.

public class PaymentProcessor {
    private PaymentType paymentType;

    public void processPayment(double amount) {
        if (paymentType == PaymentType.CREDIT_CARD) {
            Console.Writeline("Processing credit card payment of amount " + amount);
        } else if (paymentType == PaymentType.DEBIT_CARD) {
            Console.Writeline("Processing debit card payment of amount " + amount);
        } else if (paymentType == PaymentType.PAYPAL) {
            Console.Writeline("Processing PayPal payment of amount " + amount);
        } else {
            throw Exception();
        }
    }

    public void setPaymentType(PaymentType paymentType) {
        this.paymentType = paymentType;
    }
}

enum PaymentType {
    CREDIT_CARD,
    DEBIT_CARD,
    PAYPAL
}

So based on the strategy pattern I would need to create an interface for all payments

public interface IPaymentStrategy {
    void processPayment(double amount);
}

then i need to create concrete implemtations for each class I will only give an example of one but you get the idea.

public class CreditCardPaymentStrategy :  IPaymentStrategy {
    public void processPayment(double amount) {
        Console.Writeline("Processing credit card payment of amount " + amount);
    }
}

So all the payment strategies will have a concrete implemntation like above.

Finally using Dependency injection and Dependency Inversion I refactor the payment processor to look like this

public class PaymentProcessor {
    private PaymentStrategy paymentStrategy;

    public PaymentProcessor(PaymentStrategy paymentStrategy) {
        this.paymentStrategy = paymentStrategy;
    }

    public void processPayment(double amount) {
        paymentStrategy.processPayment(amount);
    }
}

But heres the bit im missing. Where and how do I implement the conditional logic to select the correct concrete implementation to register against the payment strategy based on a payment type?

I have tried looking online. All the examples I see seem to have another class like a factory that news up the concrete version and passes it into the interface. But Im not sure thats the right way to do it as i dont feel like I should be newing up classes that arent POCOS as my DI container should be doing that. So what am I missing in the strategy to conditionally select the concrete type based on the Payment type? Am i even using the right pattern here as i have seen people compare the strategy pattern to Depedency injection. If thats the cose what pattern is better for the conditional selection rather than registering a concrete class with the interface and having to manually change it in the registration every time I want to use a different payment strategy, but be able to switch between strategies at runtime?

lundi 16 octobre 2023

Decorator pattern without base class

How would I implent the decorator pattern without the base class / concrete component? Basically I only want the decorator part of the decoration pattern, in order to build a nested structure to extend my functionality with each nesting. Problem is, what do I pass to the innermost object of the nested structure (where you normally pass the base class)? A null object and specifically check for it?

E.g.

ICondition: boolean isFulfilled()
ConditionA implements ICondition
ConditionB implements ICondition

ICondition nestedConditions = new ConditionB(new ConditionA))

public boolean isFulfilled() {
   boolean isFulfilled = //algo for this condition
   return condition.isFullfilled && isFulfilled; //check if the condition of the injected and this condition is fulfilled
}

Is it acceptable to store state events in addition to action events with the event sourcing pattern?

Considering the following scenario:

An event sourced aggregate manages the transport of a package It can receive commands such as "Package loaded at 5AM", "Package stopped here at 7AM", etc....

The aggregate creates events corresponding to these actions, and from those it computes states like "Package itinerary", "Current location of the package", etc... (those states are also used as building blocks for other states)

Those events are dispatched to read models, but states derived from those events are not.

If I want a read model API to fetch a package itinerary there seems to be two options:

  • Share/duplicate the code between the read model and the aggregate, so that given the same events they can compute the same states.

  • Have the aggregate work as a state machine so that when the itinerary changes it creates an "Itinerary updated" event with the itinerary attached to it.

    • The event log would look like "tracking created", "some_itinerary_unrelated_event", "package loaded", "itinerary updated", "package stopped here", "itinerary updated", etc....

The second solution seems more practical to me and avoids having to maintain a "shared interpretation" of events between write and read which can become complex if states are built on to of other states.

However this means writing "state events" and seems to go against the "event sourcing is replaying actions to compute states".

What do you think ?

dimanche 15 octobre 2023

Methodology for real-time voice-animated assistants

Introduction: I am doing the project on AI voice assistance with character animation, it includes voice conversation, chat box and acting virtual character. It's welcome to provide any insight, architecture, project design.

Project: We have installed IOT sensing equipment to detect environmental factors such as temperature and humidity.

For our project, we need to get the IOT parameters and report the environmental conditions to the user through voice assistant and virtual character's dialog.

The key point is how to express the data in a humanized way after getting the data. For example Q: What is the temperature in the exhibition hall? Answer: There are about 30 people in the exhibition hall and the temperature is 23°, so please pay attention to keep warm.

This project emphasizes, real-time conversations and virtual character animation to make it feel like a video call. We hope that we can realize the technology of talking with virtual characters.

The process and logic I expect:

  1. Record the user's voice
  2. Voice to Text
  3. Read IOT environment parameters.
  4. Access to ChatGPT API
  5. Convert ChatGPT answer to voice.
  6. Synthesize the voice and virtual character picture into a video that matches the mouth shape.
  7. Broadcast the video.

Optional:
8. Ensure the speed of speech in the video is synchronized with the pop-up subtitles. 9. Handle streaming technology

Difficulty:

  • Lack of comprehensive API services for animation and voice.
  • The synthesis of voice and character animation takes a long time to compute, resulting in a round of dialog that can take up to several minutes.
  • Difficulty in finding as free (or low-cost) and natural voice generation libraries as possible (need to cover Asian languages such as Cantonese HK).
  • It may be necessary to explore the architecture and how to deploy it

Others
It will also help me to calculate the cost of the services involved according to the methodology provided by you.

database design for booking system for a barber shop

I want to design an appointment barbershop site. and I'm a newbie to database design. This is my target for design: After registering on the site, a user can can select the hairdresser who wants to dress his hair. (A user can't reserve any time for any hairdresser when he reserves time for any hairdresser.) after schedule shows and select time between empty times that are not reserved. This is the same table that I want!

                               2023-2-2  to  2023-2-9
Sunday Monday Tuesday Wednesday Thursday Friday Saturday
9:00 AM 9:00 AM 9:00 AM 9:00 AM 9:00 AM 9:00 AM 9:00 AM
9:15 AM 9:15 AM 9:15 AM 9:15 AM 9:15 AM 9:15 AM 9:15 AM
9:30 AM 9:30 AM 9:30 AM 9:30 AM 9:30 AM 9:30 AM 9:30 AM
9:45 AM 9:45 AM 9:45 AM 9:45 AM 9:45 AM 9:45 AM 9:45 AM
10:00 AM 10:00 AM 10:00 AM 10:00 AM 10:00 AM 10:00 AM 10:00 AM
... ... ... ... ... ... ...
5:15 PM 5:15 PM 5:15 PM 5:15 PM 5:15 PM 5:15 PM 5:15 PM
5:30 PM 5:30 PM 5:30 PM 5:30 PM 5:30 PM 5:30 PM 5:30 PM

admin of barbershop can modify interval between time (for example, change interval from 15 minutes to 30 minutes). and perhaps for some special time, for example, on Friday between 3 p.m. and 6 p.m., the user must pay a higher Price despite other days (admin can change this time).

                        this is  my template page for booking

template

My main question is: How can I handle this schedule?

I want best practices for designing this site; perhaps a barbershop has 2000 users!

I must create fixed table for time in database?

samedi 14 octobre 2023

Why does class inheritance and interface implementation involve objects?

It's also important to understand the difference between class inheritance and interface inheritance (or subtyping). Class inheritance defines an object's implementation in terms of another object's implementation. In short, it's a mechanism for code and representation sharing. In contrast, interface inheritance (or subtyping) describes when an object can be used in place of another.
---《Design Patterns: Elements of Reusable Object-Oriented Software 1st Edition》

  1. Inheritance, isn't it simply about subclasses 'inheriting' properties and methods from the parent class. How does it become 'an object's implementation in terms of another object's implementation'? When I implement class B inheriting from class A in my code, I don't instantiate any objects at all!

  2. Isn't an interface just a special kind of abstract class? (In comparison to abstract classes, interfaces only declare methods and don't declare properties or fields.) When a concrete class implements an interface, isn't it simply a class inheriting the 'interface' and implementing the methods declared in the interface? How does this turn into 'an object can be used in place of another'? When I make class B implement interface A in my code, I don't instantiate any objects at all!

API Gateway vs Web Servers

This question was asked from in recent system design interview. I got stumbled while explain the difference. In my design i created like that, client --> load balancers --> worker nodes server and databases(server handling business logic and data stores).

Interviewer asked what do you know about web servers ? Will you be adding them here if yes/no why ? I simply told them after using layer 4 load balancer and api gateway we will not be needing the web server. But was unable to provide the rationale behind it as i was not clear. Please provide some insights on actual use of web server in our design.

Any help would be much appreciated.

vendredi 13 octobre 2023

How to call singleton method inside another singleton in C++?

First the design of singletons used are from How do you implement the Singleton design pattern?. The program:

person.hpp:

#include <string>
#include <ostream>

class Person {
public:
    Person(const std::string& name, int age);

    friend std::ostream& operator<<(std::ostream& os, const Person& person);

private:
    std::string name;
    int age;
};

person.cpp:

#include "person.hpp"

Person::Person(const std::string& name, int age) : name(name), age(age) {}

std::ostream& operator<<(std::ostream& os, const Person& person) {
    os << "name: " << person.name << " age: " << person.age;
    return os;
}

singleton_1.hpp:

#include "person.hpp"

class Singleton1 {
public:
    Singleton1(const Singleton1&) = delete;

    void operator=(const Singleton1&) = delete;

    static Singleton1& getInstance();

    const Person& getPerson() const;

private:
    Singleton1();

    Person person;
};

singleton_1.cpp:

#include "singleton_1.hpp"

#include "singleton_2.hpp"

Singleton1::Singleton1() : person({"William", 45}) {
    Singleton2::getInstance().foo(); // calling this from second singleton, causes __gnu_cxx::recursive_init_error
}

Singleton1& Singleton1::getInstance() {
    static Singleton1 s;
    return s;
}

const Person& Singleton1::getPerson() const {
    return person;
}

singleton_2.hpp:

#include "singleton_1.hpp"

class Singleton2 {
public:
    Singleton2(const Singleton2&) = delete;
    void operator=(const Singleton2&) = delete;
    static Singleton2& getInstance();
    void foo() const;
private:
    Singleton2();
    const Person& person;
};

singleton_2.cpp:

#include "singleton_2.hpp"

#include <iostream>

Singleton2::Singleton2():person(Singleton1::getInstance().getPerson()) {}

Singleton2& Singleton2::getInstance() {
    static Singleton2 s;
    return s;
}

void Singleton2::foo() const {
    std::cout << person << std::endl;
}

main.cpp:

#include "singleton_1.hpp"

int main(){
    Singleton1::getInstance();
}

Now as to why I have done this. I had database manager. Which is appropriate for singleton (in this case it was for sqlite, one file, one connection, perfect candidate for singleton). And so why the second one? I made PersonDao for handling sql commands and decided to make it singleton as well even though I was not sure about that decision, but I knew that I am not going to subclass that dao and I have not seen any reason why to create more then one instance of it in PersonModel (specifically I am talking about qt). Anyway this is just simplification and minimal reproducible example. Taken as an experiment, and with singleton design from that link, is there a way to avoid the recursivness here (error:

terminate called after throwing an instance of '__gnu_cxx::recursive_init_error'
  what():  std::exception
Aborted (core dumped)

)? Or is the only option just undo singleton pattern for dao and make normal class and instances of it?

Why can I replace the underlying implementation after extracting the interface?

the following is the original text of the book 《The Art of Unit Testing, Second Edition》: Extract an interface to allow replacing underlying implementation

  • In this technique, you need to break out the code that touches the filesystem into a separate class. That way you can easily distinguish it and later replace the call to that class from your tests (as was shown in figure 3.3). This first listing shows the places where you need to change the code.

Listing 3.1 Extracting a class that touches the filesystem and calling it

public bool IsValidLogFileName(string fileName)
{
 FileExtensionManager mgr =
 new FileExtensionManager();
 return mgr.IsValid(fileName);
}
class FileExtensionManager
 {
 public bool IsValid(string fileName)
 {
 //read some file here
 }
 }
  • Next, you can tell your class under test that instead of using the concrete FileExtensionManager class, it will deal with some form of ExtensionManager, without knowing its concrete implementation. In.NET, this could be accomplished by either using a base class or an interface that FileExtensionManager would extend.The next listing shows the use of a new interface in your design to make it more testable. Figure 3.4 showed a diagram of this implementation.

Listing 3.2 Extracting an interface from a known class

public class FileExtensionManager : IExtensionManager
 {
 public bool IsValid(string fileName)
 {
 ...
 }
 }
public interface IExtensionManager
 {
 bool IsValid (string fileName);
 }
//the unit of work under test:
public bool IsValidLogFileName(string fileName)
{
 IExtensionManager mgr =
 new FileExtensionManager();
 return mgr.IsValid(fileName);
 }
  • You create an interface with one IsValid (string) method and make FileExtensionManager implement that interface. It still works exactly the same way, only now you can replace the “real” manager with your own “fake” manager, which you’ll create later to support your test.You still haven’t created the stub extension manager, so let’s create that right now.It’s shown in the following listing

Question: I don’t understand why adding an interface makes it easier to distinguish and replace class calls later? Is this question in the scope of design patterns? Should I learn some design patterns to better understand this question?

jeudi 12 octobre 2023

Creating a pattern in a sequence for groupby in pandas

I am having A dataset of Three columns ID , 'sort_seqandlevel. basically i want to identify id wise level sequence sort by sort_seq. please suggest any optimal code other then for loop` because it is taking longer time with dictionary and appending in list.

Input Dataset

    import pandas as pd
import numpy as np
data = {'id': [1, 1, 1, 1,2, 2, 3, 3, 3, 3, 4, 5, 5, 6],
        'sort_seq': [89, 24, 56,  8,  5, 64, 93, 88, 61, 31, 50, 75,  1, 81],
        'level':['a', 'a',  'b', 'c', 'x', 'x', 'g', 'a', 'b', 'b', 'b', 'c', 'c','b']}
df = pd.DataFrame(data)

Expected Output

enter image description here

Tried Code

collect = []
for ij in df.id.unique():
  idict = {}
  x =  df[df['id'] == ij]
  x = x.sort_values(by='sort_seq',ascending=True)
  x = x.reset_index()
  idict[ij] =  x['level'].tolist()
  collect.append(idict)
collect

Sellect the best suitable design pattern for monitoring real time torque

This is my problem: I am planning to make a software that will monitor servo motor torque, position and report by graph in real time. This torque data will be analyzed by a Machine Learning Model to detect abnormal or overload. Abnormal will be reported to engineer by email.

Torque data is only 1 aspect to detect abnormal. I will add more parameter as running time, etc in the future.

So please suggest me some design pattern that will fit with my software. And any Machine Learning Model for detect abnormal

I attached sample data enter image description here

Suitable design pattern and Machine Learning Model

Static functions in Symfony Entities, while passing EntityManagerInterface?

I'm currently designing my own service using Symfony, Doctrine and MySQL. I have several Entities, which allow fast database interaction. The project is for creating and managing sports tournaments with group system and finals. For this I for example have the Matches.php Entity, which has the normal Entity structure. From there on I added several static and non-static functions, related to the Matches entity. Here are 2 examples:

// Non-static function for getting TeamB's points. 
public function getPointsTeamB(): int
{
    $score = $this->getScore();
    if($score["team_a"] < $score["team_b"]) return 3;
    if($score["team_a"] == $score["team_b"]) return 1;
    return 0;
}

// Static function to getting the next games in the match plan.
public static function getNext(EntityManagerInterface $entityManager, int $amount): array
{
    ->createQueryBuilder("m")
    ->select("m.id", "IDENTITY(m.team_a) AS team_a", "IDENTITY(m.team_b) AS team_b", "m.started_at", "m.ended_at", "m.paused_at", "m.paused_for")
    ->where("m.started_at is NULL AND m.ended_at is NULL")
    ->orderBy("m.id", "ASC")
    ->setMaxResults($amount)
    ->getQuery()
    ->getResult();
    return $entityManager->getRepository(Matches::class)
}

I access these functions for example here:

#[Route('/ajax/matches/get_next/{amount}', name: 'app_ajax_match_get_next', requirements: ['match_id' => '\d+'], methods: ["GET"])]
    public function app_ajax_match_get_next(int $amount, RequestStack $requestStack, EntityManagerInterface $entityManager): Response
    {
        $req = RequirementsCheck::create($requestStack, $entityManager, permissions: [Permission::VIEW_DASHBOARD]);
        if(!$req->isAllowed()) return $req->getResponse();
        $matches = Matches::getNext($entityManager, $amount);
        return new JsonResponse(APISerializer::serializeDoctrineObjects($matches, $entityManager));
    }

As you can see I just use call the function using Matches::getNext()

Now I was talking to someone, who told me that I should rewrite my code because of this 'bad habit'. As you can see I pass the EntityManagerInterface whenever needed in the function. They said that Entities should primarily represent the data and state of an object and should not be tightly coupled with database-specific operations and that there will be Testing and Reusability issues. Is that true and if yes, where should I put these functions? Should I rewrite my code or just change my design next time?

Thanks in Advance :)

Overlapping reservations in hotel with variable number of rooms

So I am creating a MERN app where people can book a room in a hotel for a given date range. So the schema looks like this

Table Hotel {
  id: bigint,
  numberOfRooms: int,
}

Table Room {
  id: bigint,
  hotelId: bigint,
}

Table Booking {
  id: bigint,
  hotelId: bigint,
  roomId: bigint,
  checkIn: Date,
  checkOut: Date
}

Now the javascript code that I wrote is

async function bookRoomInHotel(hotelId, from_date, to_date) {
  const availableRooms = await findAvailableRooms(hotelId, from_date, to_date);
  if (!availableRooms) {
    throw new Error('No room available');
  }

  const bookRoom = availableRooms[0];

  const booking = await createBooking(bookRoom._id, from_date, to_date, hotelId);

  return booking;
}

Now because of the nature of how Javascript handles promises, it can be seen that 2 different users making a resevation for overlapping date range can result in confirming booking for the same room. And in other cases, it is possible that there are more confirmed bookings in a hotel than the available rooms.

Solutions I found:

  1. Use a bull queue to handle booking requests one by one. Cons: Reservations for different hotels will get delayed and too many queue jobs when there are many users.
  2. Row lock the hotel. Cons: High chances of dead locks
  3. Fetch list of all available rooms in the hotel and try booking them one by one. The booking table will have a constraint for avoiding overlapping dates like shown here. Cons: First come, first serve basis will not be followed as responses from database may come in different orders. Deadlocks may arise (as said in the comments in the link).
  4. Distributed locks can be used. Cons: First come, first serve basis will be not followed again as client request will be rejected if lock is already acquired and the waiting clients will keep retrying to get the lock.

How should I design my backend if I want to successfullt implement anything near as good as Airbnb and other websites.

Grouping tiles in a mesh to roughly rectangular shapes

I am trying to write a program which produces a word cloud from a given image similar to:

enter image description here

I have split up my image using thresholding, and created a mesh / tile grid using kmeans:

enter image description here

I can't think of a good algorithm to group together tiles so that they form approximatley rectangular shapes.

I have an algorithm which warps rectangles to fit distorted polygons, so I just need a way of grouping tiles together.

My current method just places the word polygons (rectanglular) and finds the position with the most tiles covered:

enter image description here

Is It Possible to Set a std::function out of Class which need to Access private class member in C++

I'm writing a Priority Queue, here is my code


#include <iostream>
#include<vector>
#include <functional>

template <class T>
class MaxPQ
{
public:
    MaxPQ(size_t size): container(size)
    {
    }

    MaxPQ(std::vector<T>& Raw)
    {
        //hard-code set it inside of class
        //this->setWrapper([=](size_t x, size_t y) -> bool { return this->container[x] < this->container[y]; });

        container.clear();
        for (const auto& val : Raw)
        {
            this->insert(val);
        }
    }

    MaxPQ(): container(0)
    {
    }

    ~MaxPQ()
    {
        container.clear();
    }

    void setWrapper(std::function<bool(size_t, size_t)> input)
    {
        compare_wrapper = input;
    }

    void insert(T newEle)
    {
        container.push_back(newEle);
        swim(container.size() - 1);
    }

    T delMax()
    {
        T result = max();
        swapByIndex(0, container.size() - 1);
        container.erase(container.end());
        sink(0);
        return result;
    }

    inline T max()
    {
        return container[0];
    }

    void swapByIndex(size_t Left, size_t Right)
    {
        using std::swap;
        swap(container[Left], container[Right]);
    }


    inline size_t left(size_t parent)
    {
        return parent * 2 + 1;
    }

    inline size_t right(size_t parent)
    {
        return parent * 2 + 2;
    }

    inline size_t parent(size_t child)
    {
        return (child - 1) >= 0 ? (child - 1) / 2 : -1;
    }

    void print()
    {
        using std::cout;
        for (const auto& val : container)
            cout << val << " ";
        cout << std::endl;
    }

private:
    std::vector<T> container;
    std::function<bool(size_t, size_t)> compare_wrapper;

    void swim(size_t targetIndex)
    {
        while (targetIndex > 0 && compare_wrapper(parent(targetIndex), targetIndex))
        {
            swapByIndex(parent(targetIndex), targetIndex);
            targetIndex = parent(targetIndex);
        }
    }

    void sink(size_t targetIndex)
    {
        while (left(targetIndex) < container.size())
        {
            size_t maxIndex = left(targetIndex);
            if (right(targetIndex) < container.size() && compare_wrapper(maxIndex, right(targetIndex)))
            {
                maxIndex = right(targetIndex);
            }
            if (compare_wrapper(maxIndex, targetIndex))
            {
                break;
            }
            swapByIndex(targetIndex, maxIndex);
            targetIndex = maxIndex;
        }
    }
};


int main()
{
    std::vector<int> temp{1, 8, 0, 9, 12, 4};
    auto myPQ = new MaxPQ<int>(temp);
    myPQ->setWrapper([=](size_t x, size_t y) -> bool
    {
//error here, trying to access private member `container`
        return myPQ->container[x] < myPQ->container[y];
    }); //set it out of class
    myPQ->print();
}

all code works pretty fine when I hard-code compare to bool less(int,int)() bool less(int,int)() is a private (because there is no need to let other call it) member function which will access private member container but others may want to custom the function I guess it looks like a function come from outside, but can act like a member function (which could access private member)

so How could I do so(to set such wrapper function by using lambda function or std::function), where should I write the setWrapper funtion, and where should I call it

is this a good design?

how does std::for_each set its function wrapper?

I'm new to STL, I may have some term or concept wrong, and English is not my first language, please forgive me.

thanks in advance

mardi 10 octobre 2023

Instantiate several children with similar arguments

I have the class Base, and the classes A, B, C, D, ... that extend this class. Base has a constructor with too many parameters (bad practice, but I can't change that). Most of the children classes have only these parameters, but some children classes can have 1 or 2 more arguments. Something like this:

class Base {
   private readonly string _arg1;
   private readonly string _arg2;
   (...)

   public Base(string arg1, string arg2, string arg3, ..., string arg_n) {
       _arg1 = arg1
       _arg2 = arg2
      (...)
   }
}

class A : Base {
   public A(string arg1, string arg2, string arg3, ..., string arg_n) : 
       base(arg1, arg2, arg3, ..., arg_n)
   }
}

class B : Base {
   private readonly string _arg_m;

   public B(string arg1, string arg2, string arg3, ..., string arg_n, string arg_m) : 
       base(arg1, arg2, arg3, ..., arg_n)
       _arg_m = arg_m;
   }
}
etc...

I want to instantiate one element of each class, using the same instances for the arguments. Something like:

var arg1 = "something";
(...)
var arg_n = "something";

var a = new A(arg1, arg2, arg3, ... , arg_n);
var b = new B(arg1, arg2, arg3, ... , arg_n, "foo");
(...)

I would like to do it without repeating the code too much. I though I could create a factory:

class Factory {
    Factory(string arg1, string arg2, string arg3, ..., string arg_n) {
       (...)
    }

and then reuse these parameters. My original code would be simplified to

var arg1 = "something";
(...)
var arg_n = "something";
var factory = new Factory(arg1, arg2, arg3, ... , arg_n);

var a = factory.GetA();
var b = factory.GetB("foo");
(...)

but then the factory would contain all the new A(list of arguemnts) for all the children. So, basically, I'm not reducing code but moving it.

Is there a pattern to create all these children without so much verbosity? Thanks.

How can I add more types easily in the future

Imagine I have this data structure:

const elements = [
    { type: 'text', value: '' },
    { type: 'text', multiple: true, value: ['', ''] },
    { type: 'select', value: '' },
    { type: 'select', multiple: true, value: ['', ''] },
    { type: 'date-range', value: { from: '', to: '' } },
    { type: 'date-range', multiple: true, value: { from: '', to: '' } },
    { type: 'area', value: { lat: '', long: '', rad: '' } },
];

Now, I created a Form using React/Typescript and Formik in order to submit this data to an API endpoint. But I feel that my solution is not scalable and I also had the type some props with any.

As you can see, I need to check for the type of the element but also if it's multiple or not. Making my code a bit hard to follow.

You can see my WIP solution in this codesanbox

The core component is this one:

const Field = ({
  element,
  onChange
}: {
  element: Element;
  onChange: (value: any) => void;
}) => {
  return (
    <Box>
      {element.type === "text" && (
        <Text
          value={element.value as any}
          isMultiple={element.multiple}
          onChange={onChange}
        />
      )}
      {/* Here I will add more types */}
      {element.type !== "text" && (
        <div key={element.id}>{JSON.stringify(element, null, 4)}</div>
      )}
    </Box>
  );
};

Basically, what I want to achieve is a way to have multiple components depending on their type, and how to handle the onChange methods without using 'any' (if that's possible). And a way to add more component types in the future.

Thanks a lot

My WIP solution => https://codesandbox.io/s/xenodochial-mopsa-vgkm2c?file=/src/App.tsx

Need suggestion for suitable Design Pattern or approach on described type of application

im trying to develop a application ( based on react flow on Ui and spring boot on backend) where each action performed by user on UI eventually gets performed on server and the modified state is given by to UI to render.

Consider following example:- A node based UI where user adding a SQL table on the UI.

  • case 1 :- On every column addition on UI -> it gets validated on backend -- >table with some validation errors will be returned.
  • case 2:- on marking the column as primary key on ui--> not null constraints gets added after a server trip as only seever know what needs to be added additionally

due to this nature of application, almost all actions are supposed to be triggered on backend.

Should we send the current state as payload on each action and then server modifies it ?

or is there any design pattern which fits this case perfectly

i was exploring CQRS design pattern. but i felt like its too much complex for such applications. another straight forward way which i can think of is sending the UI state back to server .. and then server modifying it as per the need and returning the modified state back.

Hi guys, just studied for test and found this question. Been trying to find the solution but still stuck. can anybody help me

enter image description here

Can anybody find the pattern? I am still canfused by the way they change position. It looks like they change in order of front to back. Been trying to find the solution but still stuck. can anybody help me ?

lundi 9 octobre 2023

How can i program a c++ code where it does a pattern of diamonds

This is a practice lab where i have to use loops like for, while, do while. and with the loops im supposed to output a pattern with * like triangle shapes made out of * but on this one, it looks like i have to make hollow diamonds but more than just one this is how the output of the code should look like

so far i havent gotten far ahead since i have to make diagonal lines to make a diamond shape instead of simply just making a diamond shape heres the code of what i have so far

#include <iostream>

int main() {
    const int size = 30;
    const int distance = 10;

    for (int i = 0; i < size; i++) {
        for (int j = 0; j < size; j++) {
            if ((i - j) % distance == 0) {
                std::cout << "*";
            } else {
                std::cout << " ";
            }
        }
        std::cout << std::endl;
    }

    return 0;
}

What is good pattern in python for returning value [closed]

Recently, I became curious about what is a good pattern for the form of return value.

Which do you think is a good pattern among numbers 1 and 2 below?

1)

def test():
    a = get_some_value()
    return a
    def test()
        return get_some_value()
    

    I want to know what good pattern in.

    dimanche 8 octobre 2023

    Which design pattern does MVC pattern leverage to protect model from client of view? (Head First Design Pattern)

    There’s a great design pattern that allows you to adapt an interface to provide only a subset. Can you think of it?

    On the Head First Design Pattern, book's implementation of MVC pattern gave the view full access to the model, so the author added that it can be fixed by restricting the view's access to only subset of the model.

    But they didn't mention which pattern it is.

    I don't think it is the Facade pattern, in that it merely provides a simplified interface to the underneath classes, still allowing the client to directly access them.

    What is the right design pattern for executing code per number of classes? [closed]

    I am writing a console app to migrate data from one system to another. I have an interface and implementation for each entity type. I would like the app to execute code in each implementation, so if at the start I have 10 interfaces/implementations the 10 types are executed/migrated. The design should support adding more types and the execution should just scan or know another was added...so forth and so on.

    I understand this is a loaded question, but I am on my way. It is a .NET 6 console app. I am using Microsoft DI Container. I just dont want to physically call code in each implemented class.

    I've been writing code for some time, but learning DI now (unfortunately late to the game, but nonetheless here now). Thanks for the tips!

    samedi 7 octobre 2023

    How to refactor these Nest.js lines using high abstraction

    I want to refactor these lines. Any advice would be appreciated. The MondayController and ZohoController are almost same. The MondayService and ZohoSerivce have almost same interface. But these two services have different implementations. I got stuck refactoring these lines of code.

    I think SOLID principle, KISS and DRY principles should be applied here.

    @Controller('monday')
    export class MondayController {
      constructor(private readonly mondayService: MondayService) {}
    
      
      @Get()
      async getPortals(@AuthContext() { user }: Passport) {
        return this.mondayService.getPortals(user.id);
      }
    
      @Get('projects/all')
      @UseGuards(IsAuth)
      async getAllProjects(@AuthContext() { user }: Passport) {
        return this.mondayService.getAllProjects(user.id);
      }
    }
    
    @Controller('zoho')
    export class ZohoController {
      constructor(private readonly zohoService: ZohoService) {}
    
      @Get()
      async getPortals(@AuthContext() { user }: Passport) {
        return this.zohoService.getPortals(user.id);
      }
    
      @Get('projects/all')
      @UseGuards(IsAuth)
      async getAllProjects(@AuthContext() { user }: Passport) {
        return this.zohoService.getAllProjects(user.id);
    }
    
    
    @Injectable()
    @UseGuards(IsAuth)
    export class ZohoService {
      private readonly baseUrl = 'https://projectsapi.zoho.com.location/restapi';
    
      constructor(
        @Inject(forwardRef(() => ZohoAuthService))
        private readonly zohoAuthService: ZohoAuthService,
      ) {}
    
    
      async getPortals(userId: string): Promise<AxiosResponse<any>> {
        const MAX_RETRY = 2;
        let retryCount = 0;
        ... content A
     }
    }
    
    @Injectable()
    @UseGuards(IsAuth)
    export class MondayService {
    
      constructor(
        @Inject(forwardRef(() => MondayAuthService))
        private readonly mondayAuthService: MondayAuthService,
      ) {}
    
      async getPortals(userId: string): Promise<AxiosResponse<any>> {
        const MAX_RETRY = 2;
        let retryCount = 0;
        ... content B
      }
    }
    

    I tried to define BaseService, implement MondayService and ZohoService implementing it.

    import { AxiosResponse } from 'axios';
    import { User } from '../../user/entities/user.entity';
    
    export interface BaseService {
      getTasks(userId: string, projectId: string, portalId: string): Promise<any>;
    
      getProjects(userId: string, portalId: any): Promise<any[]>;
    
    }
    
    import { IntegrationPlatforms } from "../../platform-integrations/domain/integration-platforms.enum";
    import { ZohoService } from "./zoho.service";
    import { BaseService } from "./base.service";
    import { MondayService } from "./monday.service";
    import { Injectable } from "@nestjs/common";
    
    @Injectable()
    export class IntegrationFactory {
      private static services: Map<IntegrationPlatforms, BaseService> = new Map<IntegrationPlatforms, BaseService>;
      
      constructor(zohoService: ZohoService, mondayService: MondayService) {
        if (!IntegrationFactory.services) {
            IntegrationFactory.services = new Map<IntegrationPlatforms, BaseService>;
        }
        this.register(IntegrationPlatforms.ZOHO, zohoService);
        this.register(IntegrationPlatforms.MONDAY, mondayService);
        console.log('platform registered');
      }
      
      register(platform: IntegrationPlatforms, service: BaseService) {
        IntegrationFactory.services.set(platform, service);
      }
      
      get(platform: IntegrationPlatforms) {
        const service = IntegrationFactory.services.get(platform);
        if (!service) {
          throw Error(`${ platform } Platform Service Not Found`);
        }
    
        return service;
      }
    }
    
    

    vendredi 6 octobre 2023

    Is there any Graphic Designer?

    Here I'm join newly. Finding some graphics designer like as me. If there anyone, response to build a team.

    I believe that every project is an opportunity to push boundaries and explore new horizons. Whether it's creating a captivating brand identity, designing eye-catching marketing collateral, or crafting engaging digital content, I approach each endeavor with enthusiasm and dedication, striving for excellence in every pixel.

    To build a team. That's why finding team-member.

    Parallel http requests to google platforms with rate limit

    From the design aspect, we like to have a backend connector that place parallel http requests to google drive platform

    This platform has rate limit on the number of incoming requests per user.

    Retry after header in the http response with status code 429 will help the connector to delay in invoking next http request, but this is synchronous behavior.

    Using Retry after header, how do we achieve parallelism? By minimising number of 429 http responses that inturn improves responsiveness in front end


    Is there an industry proven algorithm that can allow parallel http requests with minimum 429 response?

    How do I create a function that converts a string to a number(like float). I need to write it by myself

    I was given a task of creating a function that can convert an input string to a very accurate number (e10000) to then use in quadratic equation. In short, it is a float function but must be made by myself.

    Honestly, I have no idea how to make such a function. I'm only starting and it is my enrolling project for a uni course.

    Could use any help, thanks!

    Pattern for doing a different thing based on which subclass is received?

    Currently I have something similar to the following data classes and I want the receiver of CreateScheduledEventRequest to perform different actions when ScheduleInfo is a RepeatingTask versus when it is a OneShotTask:

    public record CreateScheduledEventRequest
    {
        public ScheduleInfo ScheduleInfo = new OneShotTask();
    }
    
    public abstract record ScheduleInfo;
    
    public record RepeatingTask : ScheduleInfo
    {
        public TimeSpan RepeatEvery;
    }
    
    public record OneShotTask : ScheduleInfo
    {
        public DateTimeOffset RunAt;
    }
    

    As an exercise in OOP-design I would also like to implement this without introspecting which subclass I have received. I tried naively to just create overloaded methods for each subclass, but I didn't manage to please the type-checker when calling them with the base class.

    I'm hoping there is a way for me to write one method that takes a RepeatingTask, and another that takes a OneShotTask, and then somehow using C# language features dispatch to the correct implementation. I suspect maybe a strategy pattern can be used, but I'm worried that is a bit heavy for this little thing.

    jeudi 5 octobre 2023

    Is Outbox Pattern necessary in sycnchronous API call

    Suppose I have an API endpoint which calls directly to this service.

    class MockService {
       private final SomeRepository someRepository;
       private final MessageBroker messageBroker;
    
       @Transactional(rollbackFor = { SomeRelatedException.class })
       public void sendReq() {
          Data data = new Data();
    
          someRepository.save(data);
    
          messageBroker.publish(new Message(data));
       }
    }
    

    I wonder if outbox pattern is still necessary here because in case of message broker failure Spring will automatically rollback the transaction so the data will never save to the db and the user will get the response code like 50x error and so on.

    OOP - Is there a name for the design pattern of using class properties or lambdas to wrap static methods (of the same name)?

    I'm working with a C# class at the moment that exposes some lambda [instance] methods which serve as wrappers for static methods of the same name.

    Here is an example snippet:

    public class UserUI : DataUI
    {
      // FYI: the `Context` object here is inherited from the `DataUI` base class
      public string GetUserId() => GetUserId(Context);
    
      public static string GetUserId(IDataUIContext context)
      {
        // ... logic here for pulling id from `context` ...
        return userId;
      }
    }
    

    I'm wondering: is there a name for such a design pattern as this?


    Additionally, would it be possible to accomplish the same functionality using a class property here rather than an instance method / lambda?

    Like so:

    public class UserUI : DataUI
    {
      public string GetUserId => GetUserId(Context);
    
      public static string GetUserId(IDataUIContext context)
      {
        // ... logic here for pulling id from `context` ...
        return userId;
      }
    }
    

    And, if so, is there any discernible difference btw using a property / getter instead? (other than the method having to be invoked as opposed to being accessed like a field, obviously)

    Which possible architecture should I use if I working on Micro-Frontend and Micro-Services?

    I decided to create a project for insurance domain and in that project, I defined 15-20 micro-services.

    Back-end

    • Micro-Service_1
    • Micro-Service_2
    • Micro-Service_3
    • Micro-Service_n

    Front-end

    • Micro-Front-end_1
    • Micro-Front-end_2
    • Micro-Front-end_n

    Refer following diagram is just an example of how micro-services will communicate to each other.

    enter image description here

    Each micro front-end will communicate with each micro-service.

    • micro-fronted 1 ----> micro-service 1
    • micro-fronted 2 ----> micro-service 2

    enter image description here

    The scope of the project is wide.

    So while working with micro-fronted and micro-service which architecture should I prefer?

    Here I'm not expecting exact match of architecture instead of that looking for possible architecture that should I use over micro-services.

    mercredi 4 octobre 2023

    Simple Terminal Command Parser Design Issue

    BRIEF EXPLANATION.
    I am implementing a very simple command parser that requires me to handle a few commands: pw path, mv source destination, help, and some others. The commands always start with the command name, and then there are either 0, 1 or 2 strings after that. I do not exclude that the number of strings may change in the future, but the structure is always the same (as it is now).

    I thought I could use the command pattern for this. Everything seems good in my schema. However, when I attempted to implement it, I realized that there's a flaw.

    I currently pass the necessary informations to the constructors of each Command (each command has its own class as the design pattern suggests). For example, the CdCommand constructor takes the FileSystem and a String Path, the MvCommand takes the FileSystem and String source, String dest, while the HelpCommand only takes the FileSystem. The issue is that I only know the inputs after I have called the constructors. That's because in my design I initialize the HashMap inside CommandExecutionController at the beginning of the program, by hardcoding the command names and passing in the correct command objects.

    I could solve this by mandating that all Command classes have a String... parameter in their execute() method. But this would also forse commands that don't require any string (such as the help command) to have this unnedeed parameter.

    I am looking for ways to mitigate this issue in practice. I've seen multiple times that the Command Pattern might be a fair solution for this, but haven't yet found any thread that explains what exactly could be done to solve the issue I'm experiencing.

    Ideally I would want to follow this pattern and avoid if-else or switches (because they're not scalable), and especially avoid the String... parameter (because not all concrete command classes require it).

    ACTUAL CODE.

    CommandExecutionController:

    public class CommandExecutionController {
        private final HashMap<String, Class<? extends CommandInterface>> commandList;
        private final FileSystemModel fileSystemModel;
    
        public CommandExecutionController(final FileSystemModel fileSystemModel) {
            this.commandList = new HashMap<>();
            this.fileSystemModel = fileSystemModel;
        }
    
        public void register(final String commandName, Class<? extends CommandInterface> commandClass) {
            commandList.put(commandName, commandClass);
        }
    
        public CommandInterface getDispatchedCommand(final String commandName, final String... arguments)
                throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException
        {
            if (commandList.containsKey(commandName)) {
                Class<? extends CommandInterface> command = commandList.get(commandName);
                return command.getConstructor(FileSystemModel.class, String[].class).newInstance(fileSystemModel, arguments);
            }
            throw new IllegalArgumentException("Command NOT found: " + commandName);
        }
    

    CdCommand:

    public class CdCommand implements CommandInterface {
        private final String path;
        private final FileSystemModel fileSystemModel;
    
        public CdCommand(final FileSystemModel fileSystemModel, final String... arguments) {
            this.path = arguments[0];
            this.fileSystemModel = fileSystemModel;
        }
    
        @Override
        public String execute() {
           return fileSystemModel.cd(path);
        }
    }
    

    How I'm currently calling it:

    text = text.trim();
            final String[] commandParts = text.split("\\s+");
            final boolean isCommandCorrect = commandParts.length > 0 && checkCommandExistence(commandParts[0]);
    
            // Test dispatching
            if (commandParts.length > 0) {
                try {
                    final CommandInterface command = commandExecutionController.getDispatchedCommand(commandParts[0],
                            String.join(" ", Arrays.copyOfRange(commandParts, 1, commandParts.length))
                    );
                    return command.execute();
                } catch (NoSuchMethodException | InvocationTargetException | InstantiationException |
                         IllegalAccessException e) {
                    throw new RuntimeException(e);
                }
            }
    

    I've looked up other stack overflow threads regarding this question and the command pattern, but found no solutions for my current issue.

    mardi 3 octobre 2023

    design pattern to write a software development layer in go

    I am attempting to create an API layer or software development kit (SDK) on top of an existing library in Golang. My goal is to make it highly flexible and extensible in Go so that we can add or extend new functionality without altering the existing codebase. For example, if I'm implementing a send_msg() function, it should be capable of sending different types of messages based on the message type specified as a parameter.

    eg if I am implementing a generic api to send msg based on specific msg as below

      send_msg(msg_type M1, param1....paramN);
      send_msg(msg_type M2, param1....paramN);
      send_msg(msg_type M3, param1....paramN);`
    

    to implement that i can simply write a function like below (pseudu code) in go

    func send_msg(mst_type int, param1 type1.....paramN typeN) 
    {
        case: msg_type M1
              perform msg processing and sending based on M1;
        case: msg_type M2
              perform msg processing and sending based on M2;
        case: msg_type M3
              perform msg processing and sending based on M3;
    
        default:
              other type processing
    }
    

    But the above code may not be highly extendable. For instance, if we wish to introduce new msg_type and its corresponding processing, we would need to modify the existing send_msg() function. Are there any better design patterns that support extensible plugins or do you have any other design pattern or design suggestions to address this?