vendredi 30 juin 2023

I am doing an inner join and a GroupJoin and I have the following error

I have the following code in C# doing some inner join

public class Complaints : BaseDomainModel 
    {
        public string CaseNumber { get; set; }
        public int ClassificationId { get; set; }      
        public int PriorityId { get; set; }
        public bool Anonymous { get; set; }
        public int StatusId { get; set; }
        public int ReferralChannelId { get; set; }
        public DateTime EntryDate { get; set; }
        public DateTime EntryDateManagement { get; set; }
        public virtual Parameter Classification { get; set; }
        public virtual Parameter Priority { get; set; }
        public virtual Parameter Status { get; set; }
        public virtual Parameter ReferralChannel { get; set; }
    }

public  class ComplaintsRequeriments : BaseDomainModel
    {
        public int ComplaintsId { get; set; }
        public string Requeriments { get; set; }
        public int TypeId { get; set; }
        public virtual Parameter Type { get; set; }
        public virtual Complaints Complaints { get; set; }
    }
  public class ComplaintPerson : BaseDomainModel
    {
        public int PeopleId { get; set; }
        public int ComplaintsId { get; set; }
        public int TypePersonId { get; set; }
        public People People { get; set; }
        public Complaints Complaints { get; set; }
        public Parameter TypePerson { get; set; }
    }
 public class Parameter : BaseDomainModel
    {
        public int ParameterTypeId { get; set; }
        public string Value{ get; set; }
        public virtual ParameterType ParameterType { get; set; }
        
    }

 public class People : BaseDomainModel
    {     
        public int DocumentTypeId { get; set; }
        public string Number { get; set; }
        public string Name { get; set; }
        public string Surnames { get; set; }
        public virtual Parameter DocumentType { get; set; }    

    }
  public class User : BaseDomainModel
    {
        public int PermissionId { get; set; }
        public string Email { get; set; }
        public string Name { get; set; }
        public string Surnames { get; set; }
        public int? ImageUploadId { get; set; }
        public virtual Permission Permission { get; set; }
        public virtual FileUpload? ImageUpload { get; set; }

        public virtual ICollection<RequestAssignment> Assignments{ get; set;}
    }

GetAllById

 public IQueryable<TEntity> GetAllById(Expression<Func<TEntity, bool>> predicate, 
bool withTracking = false, bool withSplitedQuery = false)
        {
            var query = _dbset.AsQueryable().Where(predicate);

            if (withSplitedQuery) query = query.AsSplitQuery();
            else query = query.AsSingleQuery();

            if (withTracking) return query.AsTracking();

            return query.AsNoTracking();
        }

Join

var r = _unitofwork.Complaints.GetAllById(a => !a.DeletedRecord, true, true).ToList()
                 .Join(_unitofwork.IComplaintsRequeriments.GetAllById(a => !a.DeletedRecord, true, true).ToList()
                 , Complaints => Complaints.Id, Requeriments => Requeriments.ComplaintsId
                 , (Complaints, Requeriments) => new
                 {
                     Complaints,
                     Requeriments
                 })
                 .Join(_unitofwork.ParameterRepositories.GetAllById(a => !a.DeletedRecord, true, true).ToList()
                 , Requeriments => Requeriments.Requeriments.TypeId, ParameterRepositories => ParameterRepositories.Id
                 , (Requeriments, ParameterRepositories) => new
                 {
                     Requeriments,
                     ParameterRepositories
                 })
                 .GroupJoin(_unitofwork.ComplaintPerson.GetAllById(a => !a.DeletedRecord, true, true).ToList()
                 , Person => Person.Requeriments.Complaints.Id, ComplaintPerson => ComplaintPerson.ComplaintsId
                 , (Person, ComplaintPerson) => new
                 {
                     Person,
                     ComplaintPerson
                 })
                 .Join(_unitofwork.IPeople.GetAllById(a => !a.DeletedRecord, true, true).ToList(),
                  personUser => personUser.ComplaintPerson.Select(a => a.PeopleId), user => user.Id
                 ,(personUser, user) => new 
                 {
                     personUser,
                     user
                 });

Severity Code Description Project File Line Suppression State

Error CS0411 The type arguments for method 'Enumerable.Join<TOuter, TInner, TKey, TResult>(IEnumerable<TOuter>, IEnumerable<TInner>, Func<TOuter, TKey>, Func<TInner, TKey>, Func<TOuter, TInner, TResult>)' cannot be inferred from the usage. Try specifying the type arguments explicitly. Application C:\Users\asbel\Desktop\RepositoryDGII\Backend\DDD.Application\Features\Complaints\AdminInputFlag\Querys\AdminInputFlag\AdminInputFlagHandler.cs 59 Active

 

I hope to bring the different join and group join of the different models

How to handle different input type and single output type in a single function in android kotlin

I have two enum classes and data class as below :

NamesEnum.kt

enum class NamesEnum(
    val option : String
) {
    AAkASH("Aakash Gupta"),
    ADITI("Aditi Deshpande")
}

StateEnum.kt

enum class StateEnum(
    val option : String
) {
    KAR("Karnataka"),
    MAH("Maharashtra")
}

StudentData.kt


data class StudentData(
    var student1: String = "",
    var student2: String = "",
    var state1: String = "",
    var state2: String = "",
   
){
    companion object{
        private var EMPTY_OBJECT: StudentData? = null
        fun getInstance(): StudentData? {
            if (EMPTY_OBJECT == null) EMPTY_OBJECT = StudentData()
            return EMPTY_OBJECT
        }
        fun clearReference(){
            EMPTY_OBJECT = null
        }
    }
}

I have to go through each enum classes and update the data in the data class:


fun updateData() : List<String>
{
  val list = NamesEnum.values()
        val nameList = ArrayList<String>()
        for (item in list){
            nameList.add(item.option)
        }
        return optionList
}

I want the same functionality as in updateData() function but without repeating the logic for every Enum class. Which design pattern do I have to choose to implement this?

jeudi 29 juin 2023

A screen to accommodate AND/OR type of questions

I need to design an architecture that can accommodate AND/OR questions based on categories. An admin can configure the questions each quarter. Current architecture supports multiple questions for a category but requirement is to support AND/OR type of questions.

Category Personal :

  1. What is your name?
  2. What is your current address?
  3. What is your permanent address?

New requirement :

  1. What is your name?
  2. What is your current address?
    OR
    What is your permanent address?
  3. What is your home phone number?
    OR
    What is your cell phone number?

It should also update UI to accept such questions. The current UI :

enter image description here

What design pattern would be most appropriate here

We have a main service class in which we initializes many primitives and non-primitive(objects) variables, via calling other downstream services or forming these variables on the fly as they are required later in the logic. Controller class this main service class.

At the end of main service class, after calling all downstream services and initializing these variables. We call a loggingService class, which needs all those variables that we initialized and make a loggingObject and push this to downstream service for tracking purpose. The structure of this loggingObject is very dynamic and keep changing at any time(fields will get added anytime anywhere in the structure).

Problem Desc: loggingMethod (method in loggingService) arguments are keep growing as going forward more intermediate objects and variables will be added dynamically and we have to send them all to downstream service for tracking purpose. As we believe there should not be too many params to a functions (we are keeping in our codebase <= 4).

We thought of initializing one global object(An aggregate GOD object) for a request, that should be accessible everywhere in the codebase (OR we keep passing this object in every downstream service method), and we add all those intermediate objects/variables in this global object and send this global object in the loggingMethod.

Using global object might be an anti-pattern here. Would this be the right approach to tackle this problem, OR there could be a better design pattern to solve this, keeping in mind that we want to keep it extensible for future field additions.

Application is written in spring-boot(Java-11).

Efficient thread safe observer design pattern without expensive copying

What's the efficient way to implement a thread safe observer design pattern ?

Using the following code:

#include <mutex>
#include <vector>

class Subject {
public:
    void addObserver(Observer* observer) {
        std::lock_guard<std::mutex> lock(mutex_);
        observers_.push_back(observer);
    }

    void removeObserver(Observer* observer) {
        std::lock_guard<std::mutex> lock(mutex_);
        // Remove the observer from the vector
    }

    void notifyObservers() {
        std::lock_guard<std::mutex> lock(mutex_);
        for (Observer* observer : observers_) {
            observer->update();
        }
    }

private:
    std::mutex mutex_;
    std::vector<Observer*> observers_;
};

it's not recommended to hold a lock and call a callback ! Also coping the list of observers each time I send a notification I not efficient also.

Is there an efficient way to achieve thread safety.

mercredi 28 juin 2023

C How to make use of a fixed hierarchy of classes for various similar entities like employee-Manager for company 123

Difficult to give appropriate title to this question Let me explain the scenario.

I have a class say Employee and a subclass (of Employee) say Manager.

There are various methods (and data member) in Employee class related to payroll, employee details, appraisal, etc. Similarly for Manager there are various methods.

class Employee {
    string name, address, empId;
    int salary;
    Dept dept;
public:
    void [Get/Set]Name();
    void GetEmpid();
    void SetSalary();
    virtual void StartOnboarding();
    virtual void startOfboarding();
    virtual void startAppraisal();
};

class Manager : public Employee {
    list teamList;
    int appraisalBudget;    
public:
    int [Get/Set]AppraisaBudget();
    int [Add/Delete]EmployeeInTeam(emp);
    void StartTeamAppraisal();
};

Scenario is that I have many companies says Company1, Company2, etc. and more can be added in future. An employee or manager can be of company 1, company2, etc.

Employee and Manager for company1 will have similar relationship as above, same for company2. But they will have different ways to handle methods available. Like startOnboarding() for employee of company1 will be different than employee of company2, similarly StartTeamAppraisal() for manager of company1 will be different than manager of company2.

Now one way to model this scenario is to create different sub-classes of Employee for every company like EmployeeCompany1, EmployeeCompany2, and similarly sub-classes of Manager for every company like ManagerCompany1, ManagerCompany2, etc.

Employee classes for different company -

class EmployeeCompany1 : public Employee {
    int tasksDone;
    int clientsMeetingsDone;
    int appreciationsReceived
public:
        // Company1 specific implementation of following
    virtual void StartOnboarding() { ... }
    virtual void startOfboarding() { ... }
    virtual void startAppraisal()  { ... }
};

class EmployeeCompany2 : public Employee {
    int bugSolved;
    int featureDeveloped;
public:
        // Company2 specific implementation of following
    virtual void StartOnboarding() { ... }
    virtual void startOfboarding() { ... }
    virtual void startAppraisal()  { ... }
};

But in above case EmployeeCompany[1,2,..] will be subclass of Employee and Manager is already a subclass of Employee but they both(EmployeeCompany[1,2..] and Manager) are not on the same level as per the behaviour is considered. So there is some flaw in the design.

If we do similar for ManagerCompany1, than It has to be a subclass of EmployeeCompany1, but it also has to be a subclass of Manager, like below -

class ManagerCompany1 : public EmployeeCompany1, public Manager {
protected:
    int company1specificData;
public:
    virtual void StartTeamAppraisal() {
    // make use of data member of EmployeeCompany1 and other things specific to company1
    }
};


class ManagerCompany2 : public EmployeeCompany2, public Manager {
protected:
    int company2specificData;
public:
    virtual void StartTeamAppraisal() {
    // make use of data member of EmployeeCompany2 and other things specific to company2
    }
};

  1. I feel my design is having flaws and the scenario I described would be a well defined scenario in object oriented design literature.

  2. I am looking for community's help for a better design approach to model above scenario in c++.

  3. May be You can also suggest a better title for this question.

Merge private attributes in Python

I know that private attributes are loosely defined in Python, but I'm trying to figure out what would be the most lean way of implementing a method to merge together private attributes.

Class Event:
  target_time: datetime
  _names: set

I'm thinking of having a static method to merge together two Events.

@staticmethod
def merge(event1: Event, event2: Event) -> Event:
  new_event = Event()
  new_event = event1._names + event2._names
  return new_event

But I'm unsure if this breaks some good design patterns about private attribute since they are private.

mardi 27 juin 2023

Is the combination of Repository and Data Mapper patterns necessarily inefficient?

There's been a variety of questions here that pop up from time to time regarding these two common design patterns for describing a persistence (data storage) layer in an object-oriented program: Repository and Data Mapper, with some wondering whether there's a difference at all.

What exactly is the difference between a data mapper and a repository?

Repository and Data Mapper pattern

and so forth. I have another, though, that none of these seem to answer. In particular, regarding the difference between the two, I've found the best answer looks to be that a Data Mapper simply does what it says on the name - its Single Responsibility is to map objects to and from a database, i.e. CRUD objects to/from the DB, so that the DB type used in the back is hidden from the higher-up logic. This makes good sense. Whereas the Repository is apparently over the Data Mappers and permits more complex querying, for example, methods like "getAllCarsWithEngineType".

Trouble is, what I'm wondering is how then does the Repository actually work. In particular, to do a query, if all it can see is Data Mapper, and all Data Mapper does is the 4 CRUD methods (with perhaps one more method to get all the keys available), then it seems the only thing Repository can do is dig up the entire database into memory as objects, and then scour them for the right ones. This seems like an awful waste of performance, especially when you can run an SQL query directly that should be far more efficient since you're then letting your DB engine handle all that search stuff and it likely has lots of tricks up its sleeve to make such things fast.

But that would seem to have no other logically possible way to happen than either to add (a likely escalating number of) query methods to the Data Mapper, which breaks the spirit and once more dissolves the distinction, or you have to have some other "thing" the Repository uses to do this, or else, Repository has to interact directly with DB, putting low level SQL (or whatever) queries and stuff directly in the Repository itself, and that sounds pretty bad (clashing high and low abstraction levels, for one) esp. given if it still relies on an injectable Data Mapper for some of the functionality you could easily mismatch the two.

So can you, and if so, how do you, build queries into a Repository/Data Mapper combo in an efficient/performant manner while maintaining the spirit of the patterns?

Foreign Key usage in Low-Moderate Complexity DB System Design

I'm trying to (re-)design a low-moderate complexity database schema and I'm stuck on trying to decide how many foreign keys to include or not include in reference to other tables.

Is it generally better to have a great many foreign keys densely connecting entities/tables to each other, or is it preferable to have as few foreign keys connecting entities/tables together as possible? Where do you draw the line? Many of the current foreign key columns are optional which means I can't rely upon them to actually return all relevant data so I originally erred towards a dense graph of foreign key relationships to prevent an intermediate entity's lack of a valid foreign key relation causing problems retrieving data on the 'other side' of that intermediate entry, but that's caused its own issues with difficulty maintaining the foreign keys in all of these different entities.

About The System

This is a pharmacy benefit related system. The simple way to think about the system is that there is a bunch of standards-based data and tables and that data is being collected and presented to a staff member. The staff member examines this data and creates an Analysis; and then based on that analysis they create a Suggestion.

From a CRUD perspective, there are few requirements. I see no reason why I can't have as many Foreign Keys as I want from a performance perspective.

From a Query perspective, we want to query to gather all pertinent information for an Analysis all at once. This is the problematic part because so much of the data being queried is related. I've included a list of some of the tables I want to pull data from in this query below.

Table Name Number of (potential) foreign keys to other tables in this list
Claim 9
Prescription 6
Pharmacy 4
Prescriber 2
Plan 4
Plan Member 8
Formulary 3
Formulary Row 4
Analysis 5
Suggestion 5

The issue I'm encountering is that so many of these tables are related to each other. For example, Prescription is related to Claim and Pharmacy and Analysis and Suggestion. Another example: Plan is related to Plan Member, Formulary, Claim, Analysis.

Original Code Smell Problem

As I have built out the system, the number of tables - and therefore the number of table joins needed to perform the get all data related to this analysis query - has grown. I now have a large Postgres View which encompasses many tables and the view is only going to get bigger as I improve the system. I don't like having to write and maintain this single extremely large and long query. Some pieces of data I need to pull are easy to get in the query and require only a single join, but others require joins on joins on joins. That seems like code smell to me for a system with this few tables.

Thoughts

If I try to set up and maintain all of these foreign key relationships then I can get faster queries, but when the system receives new data that data is not always complete and when it gets updated it seems like I'd have to re-perform the foreign key linking for all of that entities related entities, and all of their relations, etc. It's certainly possible to do that, but it would require some careful coding and inevitably something will go wrong; so I'll have to write code to allow re-calculating all entities' relationships when an update occurs. But if I do that, it would perhaps invalidate the Analysis and Suggestion table's entries based on the changing data upon which those entries were based which would cause other business problems where the Analysis was created based on data from time T0 and then at T1 the underlying data is updated, and when someone views the data and analysis at T2 they make a Suggestion based on the analysis created at T0 which was made invalid by the update at T1. And the problem would cascade out into the non-digital world. One way around that would be to preserve all data used to make an Analysis at T0, or at least do a time-based query and highlight that the underlying data upon which the analysis at T1 was made has changed... but that now requires me to keep track of such data as well. It's doable, but a pain.

Potential Solutions

Input-driven Approach

Try to segment the data by the data source and write services and queries to pull data from those data sources separately.

The problem with this approach is that although the data is coming from different sources, the data itself is inter-related across sources and there is a direct foreign key relationship between data from those sources.

Domain Driven Approach

This doesn't solve the code smell. All of this data is in the same domain.

Hub and Spoke

I tried to divide the data where I put one table containing primarily foreign keys in the middle (a hub), and referenced some other tables containing primarily foreign keys (a hub), and attached these tables to the hubs and the hubs to each other. This was done to try to reduce the number of foreign keys present in each table.

This didn't work because the relationships between entities in different hubs were stronger than the relationships between entities within the same hubs. Claim-Prescription-Pharmacy-Prescriber-Plan-PlanMember-Formulary-FormularyRow-Analysis-Suggestion are all inherently extremely related to each other so I would need to build a single hub and put all of these entities as spokes on that hub. That's dumb.

Messy Graph

I currently have a messy graph of entity relationships. I think this is producing code smell in my queries, but maybe the actually-correct way to deal with this is to, well, just accept it?!? Maybe this system is just more complicated than I would like and there's no way around that.

lundi 26 juin 2023

Django DRF integration with HDFS using a singleton pattern for resource efficiency and performance

I am trying to integrate Django DRF (Django REST Framework) server with HDFS (Hadoop Distributed File System).
However, I couldn't find any official libraries that provide direct integration between Django and HDFS.

Therefore, I am considering using native Python libraries for HDFS.
However, these libraries typically require creating a client and making calls, which could potentially result in resource wastage and performance degradation.

To address this concern, I have implemented a singleton pattern as shown in the code snippet below.

from django.http import HttpResponse
from hdfs import InsecureClient


class HDFSClient:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)
            cls._instance.client = InsecureClient('http://localhost:9870', user='root')
        return cls._instance

    def read_file(self, file_path):
        with self.client.read(file_path) as reader:
            file_contents = reader.read()
        return file_contents


def read_hdfs_file(request):
    hdfs_client = HDFSClient()
    file_path = '/test.txt'
    file_contents = hdfs_client.read_file(file_path)
    return HttpResponse(file_contents)

I have implemented a singleton pattern to ensure that only one instance of the HDFS client is created and used throughout the Django application.

This approach aims to minimize resource wastage and improve performance.

However, I am unsure if this solution effectively resolves the resource and performance concerns.

I would like to know if there are better alternatives or approaches to address these issues.

EUDRACT Pattern check

I want to do a pattern check in informatica(iics) preferably under CDQ than CDI 'YYYY-NNNNNN-CC

The EudraCT number has the format YYYY-NNNNNN-CC, where: YYYY is a year after 1990. NNNNNN is a six digit sequential number. CC is a check digit. For the other ones, no specific control"

I guess this cant be achieved via REGEX, Please give your expert opinions to tackle this check.

I had tried multiple REGEX options, and still pondering over to find the right appropriate approach to solve the requirement

How to elegantly define shortest happy path between start and end state in a State Pattern design implementation?

When using state pattern, one is delegating behaviour of the Entity to the current State. I have prepared SSCCE that I pasted below. We have an Entity which can transition between states : StartState, StateA, StateB, EndState. The happy path is simply the shortest path between StartState and EndState.

In this particual example the shortest happy path is: StartState->StateA->StateB->EndState

I find it hard to express what is the happy path, so I can return the order to the frontend but also be able to navigate myself through. State pattern uses methods not dicitonaries to store nodes end edges, right? I want to avoid just List<string>. I'm looking for an elegant solution.

I want to be able to know upfront what is the order of the states in the happy path.

  1. Dynamically calculate the shortest path for that class structure? XOR
  2. Because dynamic calculation is probably hard or very hacky, what is the most elastic/convienient to use way to describe statically the shortest happy path in this state graph?

namespace States
{
    public class Entity
    {
        public int Id { get; private set; }
        public State CurrentState { get; private set; }
        public void Action1() => CurrentState = CurrentState.Action1() ?? CurrentState;
        public void Action2() => CurrentState = CurrentState.Action2() ?? CurrentState;
        public void Action3() => CurrentState = CurrentState.Action3() ?? CurrentState;
    }

    public abstract class State
    {
        protected Entity _entity;

        public State(Entity entity)
        {
            _entity = entity;
        }
        //They return new state or null if transition is illegal
        public abstract State Action1();
        public abstract State Action2();
        public abstract State Action3();
    }

    public class StartState : State
    {
        public StartState(Entity entity) : base(entity) { }
        public override State Action1() => new StateA(_entity); //moves workflow forward
        public override State Action2() => null;
        public override State Action3() => null;
    }

    public class StateA : State
    {
        public StateA(Entity entity) : base(entity) { }
        public override State Action1() => null;
        public override State Action2() => new StateB(_entity); //moves workflow forward
        public override State Action3() => new StartState(_entity); // goes back to StartState
    }

    public class StateB : State
    {
        public StateB(Entity entity) : base(entity) { }
        public override State Action1() => new EndState(_entity); //moves workflow forward to EndState
        public override State Action2() => null;
        public override State Action3() => new StartState(_entity); // goes back to StartState
    }

    public class EndState : State
    {
        public EndState(Entity entity) : base(entity) { }
        public override State Action1() => null;
        public override State Action2() => null;
        public override State Action3() => null;
    }
}

dimanche 25 juin 2023

use grep to find an entry in the $PATH variable

I have found many answers to using grep to search for the value in a variable within the contents of a file but not finding a particluar string in the actual contents of the $PATH variable. I'm on a mac and was trying to determine if "brew" was in my PATH and thought surely I can just use grep to do this... and I'm sure it's possible but nothing I've tried works so can someone please enlighten me? The following was what I thought would work but it just lists the contents of the PATH variable.

grep brew "${PATH}"

I also tried

grep brew -- "${PATH}"

which just did the same thing. What am I missing?

How to register classes without modifying main.cpp in C

I have a feature registration implementation, wherein new features can be added to the registry with a simple macro.

However, I want to follow Open-closed principle and NOT have to change the the main.cpp whenever a new feature is created, as their implementation details are not relevant for main.cpp.

The issue lies in the #include directive: If a feature file is not #included, the index for it does not exist in the scope. This is because each TYPE##Registered value exists only inside each header file, not inside the Register.h. But how can I get around this limitation?

To reiterate the question, How can I register features without modifying main.cpp for every new feature added?

main.cpp:

#include "Foo.h" // Must include, otherwise won't show up in registry!
#include "Bar.h"


int main()
{
    for (auto it : FeatureRegistry::GetInstance().GetFeatureRegistry())
    {
        printf(" registry: %s", it.first);
    }

    return 0;
}

Registry.h:

#pragma once

#include <cstddef>
#include <map>
#include <utility>


#define TYPE_REGISTER_ERROR 255 // Value not found in TypeRegistry

// Registers type into GlobalTypeRegistry
#define ENGINE_REGISTER_FEATURE(TYPE) class TYPE; static bool TYPE##Registered = \
    (FeatureRegistry::GetInstance().GetFeatureRegistry()[#TYPE] = \
    FeatureRegistry::GetInstance().GetFeatureRegistry().size(), true);

class FeatureRegistry
{
public:
    static FeatureRegistry& GetInstance()
    {
        static FeatureRegistry Instance;
        return Instance;
    }

    std::map<const char*, unsigned char>& GetFeatureRegistry()
    {
        static std::map<const char*, unsigned char> Registry;
        return Registry;
    }

    // Returns the value of the type in TypeRegistryMap
    unsigned char GetTypeIndex(const char* Classname)
    {
        auto it = GetFeatureRegistry().find(Classname);
        if (it != GetFeatureRegistry().end())
        {
            return it->second;
        }
        // Return a default value if the type is not found
        return TYPE_REGISTER_ERROR;
    }
};

#define TypeIndex(TYPE) \
    ([] { \
        class TYPE; \
        return FeatureRegistry::GetInstance().GetTypeIndex(#TYPE); \
    })()

Foo.h (Bar.h is identical)

#pragma once

#include "Register.h"

ENGINE_REGISTER_FEATURE(Foo)
class Foo
{

};

Need help using match_recognize in Oracle 21c

I truly hope I can find understaning here as to what is wrong with this code. I have some equipment that send event data as event tags to a database; each timestamped with the time of the equipment of origin.

There is a problem with an equipment's peripheral, and as a consequence these affected equipment sent the relevant event tags, exactly 16 of them, everytime, chronologically ordered. Searching the data manually on the table, it does contain the pattern, coming from different equipment ID.

The purpose is to quantify how many times this problem (pattern) happpens, and on which equipment.

As I was researching what function could help me, I came across Oracle MATCH_RECOGNIZE as a possible tool to obtain a solution. If I am not mistaken, this function uses or emulates regex of some sort (I am not an regex expert). I haven't been able to fine tune the code to show me if it can pick the pattern. I was using inside the PATTERN clause either a '+' (one or more -- plus quantifier), or '*' (zero or more -- star quantifier). If I use +, the result is zilch. If I use * I get data, but there also appears other tags with do not belong to the pattern.

What I would like is to make the code obtain the pattern, with no other event tag.

Below I am sharing the code.

--DROP TABLE TESTPATTERN
SELECT
TO_char(EventDateTime, 'YYYY-MM-DD HH:MM:SS')AS EventDateTime,
EqpID,
EventTag
FROM TESTPATTERN 
MATCH_RECOGNIZE (
 PARTITION BY EqpID
 ORDER BY EventDateTime
    MEASURES
        FIRST(EventDateTime) AS start_date,
        LAST(EventDateTime) AS end_date,
        FIRST(EventTag) AS first_tag,
        LAST(EventTag) AS last_tag
ALL ROWS PER MATCH
AFTER MATCH SKIP PAST LAST ROW 
PATTERN (EventTag1+ EventTag2+ EventTag3+ EventTag4+ EventTag5+ EventTag6+ EventTag7+ EventTag8+ EventTag9+ EventTag10+ EventTag11+ EventTag12+ EventTag13+ EventTag14+ EventTag15+ EventTag16+ EventDateTime1+)
 DEFINE
EventTag1 AS EventTag = 'THOR',
  EventTag2 AS EventTag = 'MJOLNIR',
  EventTag3 AS EventTag = 'LOKI',
  EventTag4 AS EventTag = 'HULK',
  EventTag5 AS EventTag = 'HAWKEYE',
  EventTag6 AS EventTag = 'CAPNAMER',
  EventTag7 AS EventTag = 'FURY',
  EventTag8 AS EventTag = 'STARK',
  EventTag9 AS EventTag = 'FURY',
  EventTag10 AS EventTag = 'STARK',
  EventTag11 AS EventTag = 'THOR',
  EventTag12 AS EventTag = 'MJOLNIR',
  EventTag13 AS EventTag = 'LOKI',
  EventTag14 AS EventTag = 'HULK',
  EventTag15 AS EventTag = 'HAWKEYE',
  EventTag16 AS EventTag = 'CAPNAMER',
  EventDateTime1 as EventDateTime > prev(EventDateTime)
) MR
WHERE 1=1
AND (START_DATE IS NOT NULL OR END_DATE IS NOT NULL OR FIRST_TAG IS NOT NULL OR LAST_TAG IS NOT NULL)
AND (START_DATE IS NOT NULL OR END_DATE IS NOT NULL OR FIRST_TAG IS NOT NULL OR LAST_TAG IS NOT NULL)

Thank you.

Prototype pattern instead of assigning the oject?

What is the deal with prototype pattern? Couldn't we just assign like done below?

Object x=y;

I understand prototype usage in pass by reference languages but, in most cases, it looks like it overcomplicates something that is easy.

Which design patterns should I use for storing in BD managing and displaying dynamic typed data?

I often have to store/display/manage data which type isn't determined and can be changed by user, by external data providers or by whatever at runtime.

For example: I'm gathering some data about work that is completed (say it's sort of report which customer wants to see online). Different kinds of job have their own set of data fields, some of them can be stored in one common field (like a date when it was done, cost, person who is responsible for it, and so on), some of them can't (like distance for transporting service, or maybe type of some materials used during this work, which doesnt suit all kinds of jobs, just one particular one).

So, what approaches I tried:

  1. the worst one (imho) is to use only one table and to create dedicated field for each type of data. The fastest one to implement, but increases amount of columns drastically (especially if I create new ones dynamically while importing new data via API). Can be used only if we are 200% sure that the project will never ever grow.

  2. acceptable one is to store the most commonly used data in main table (like cost, date and so on) and to make table like (main_record_id, field_type, field_value) which stores all other fields.

but the question now is how to manage it better in PHP.

  • approach I often use for small applications - is just to have some const-set or enum to define type, and a bunch of case-like logic that validates, stores, displays and elseway-uses the value according to particular type. it is fast to create and quite clear to read while project is quite small.

  • approach I tried to use as well is to define a contract and then create a separate class for each data type that incapsulates all the logic (validation, storing, even displaying sometimes) connected to this type. seems a bit more complicated at startup, but should (I hope) help me to avoid over-complicating my app in future... BUT! It seems to break the single-responsibility rule, and, which makes me worry way more, I feel that it can be affected by fragile-abstract problem, and a tiny error at the beginning may cause huge problems in future.

So, my question is: what approach would you use in such circumstances? which pattern is practically proved to be reliable when your project grows more than it was expected? What patterns sould I consider to learn to better see possible ways to be able to make a better choice?

samedi 24 juin 2023

Java | OO Design | How to map target field from multiple source fields depending on different business conditions?

Context: I am working on a Java Spring Boot backend service, related to e-commerce domain. My service gets data from Order-Service(OS), and I have to extract some data to send it further. Extracted data class looks something like:

class TargetDTO {
    String orderId;
    String shipmentId;
    String trackingUrl;
    String deliveryDate;
    // so on..
}

The source data, which I get from OS is contained in a JsonNode , and hence is of free form or no defined schema as below:

class OSResponseDTO {
   String field1;
   String field2;
   JsonNode sourceData; // this is of our interest for this problem
   // so on..
}

There are 2 dimensions in mapping the data :

  1. Mapping criteria from source to target:

    • The data can be directly extracted from source field, e.g. orderId <=> sourceData.orderId
    • The data can be a combination of more than one field, e.g. shipmentId <=> sourceData.orderId + sourceData.shipments.number.
    • We may need to apply some logic, and using one or more source fields, e.g. map deliveryDate from sourceData jsonNode and convert to specific format as per geographical region.
  2. Same target data can be mapped from different json paths of sourceData , based upon business conditions, such as orderPlacedOnline, orderPlacedOffline, orderPaidOnline, orderPaidCash, orderPaidCard, orderOutForDelivery, orderDelayed, etc. There are, as of now, about 200 such conditions, which can be grouped in 8-10 schemas. For e.g. trackingUrl <=>

if(orderOutForDelivery) {
  trackingUrl = sourceData.orderDetails.url;
} 
else if(orderPlaced) {
  trackingUrl = sourceData.url;
}
.
.
.
else if(orderShipped) {
  trackingUrl = sourceData.shipments.url;
}
else {
}

Question: What possible design I can go with to implement this?

What I have tried One approach I could think of was - Having strategies for mapping each target attribute, and creating a Map of condition and strategies, as:

interface OrderIdStrategy {
  void mapOrderId();
}
class OrderIdStrategy1 implements OrderIdStrategy {
}
class OrderIdStrategy2 implements OrderIdStrategy {
}

interface TrackingUrlStrategy {
  void mapTrackingUrl();
}
class TrackingUrlStrategy1 implements TrackingUrlStrategy {
}
class TrackingUrlStrategy2 implements TrackingUrlStrategy {
}

class DataExtractor {
  Map<String, Set<String>> businessCaseAndUsedStrategiesMapping;

  @PostConstruct
  init() {
     businessCaseAndUsedStrategiesMapping.put("orderPlacedOnline", Set.of("OrderIdStrategy1", "TrackingUrlStrategy2"));
     businessCaseAndUsedStrategiesMapping.put("orderOutForDelivery", Set.of("OrderIdStrategy2", "TrackingUrlStrategy2"));
  // so on
  }

  mapOrderId(String businessCase) {
     businessCaseAndUsedStrategiesMapping.get(businessCase).mapOderId();
  }

  mapShipmentId(String businessCase) {
     businessCaseAndUsedStrategiesMapping.get(businessCase).mapShipmentId();
  }

  mapTrackingUrl(String businessCase) {
     businessCaseAndUsedStrategiesMapping.get(businessCase).mapTrackingUrl();
  }
}

But the unhappy part of this approach is that I have to create a map for all those 200 business cases; and these business conditions are likely to grow with future.

How to combine the three-layer architecture with the unit of work in C#

I use three layer and Unit of work Design pattern together but project have credential bug!

data Read from database but does not save in it. Context Class Can't get changes and current transaction is null.

Current Transaction

architecture in the left of image

How can I fix this bug?

I create Repository in Data project(second image) and create Unit of Work in BLRazor project(second image) I test read data from database and correctly it work but add to database does not work correctly!!!

vendredi 23 juin 2023

how to solve design patterns and palindrome in javascript [closed]

"What are some commonly used design patterns in JavaScript development that help improve code organization, maintainability, and reusability? Examples could include Singleton, Observer, Factory, and MVC. How do these design patterns address specific challenges and enhance the overall architecture of JavaScript applications?"

How to split pandas column in 2 with varying pattern

I have fetched dataframe from site with selenium and one of a columns in a table has a name and serial number in one cell. In frontend it looks fine cause serial number is put in but when i fetch it into pandas dataframe it fetching it in 1 cell, pattern of serial number is vary. The pattern can look like b05/124125 or either f07/d05/f95/10581

I've been searching for some implementation in internet and looks like "column.str.split()" doesnt feet the situation i have.

I getting table from html file with pd.read_excel

how to avoid circular dependency in requiring files

I am making a inventory management system. I have two models sales and orders. Sales contain bill data and each product purchased is in orders model. I want to use pre update hook to update orders and vice versa

// fileName sale.model.js

const ordersModel = require("./orders.model")
const connection = require("./database/connection")

const SaleSchema = new mongoose.Schema(
  {
    store: { type: mongoose.Types.ObjectId, required: true, ref: "stores" },
    customerName: { type: String, required: true },
    customerPhone: { type: String, required: true },
    totalDiscount: { type: Number },
    orders: [{ type: mongoose.Types.ObjectId, ref: "orders" }],
   
  },
  {
    timestamps: true,
  }
);

saleSchema.post("save",async function(doc){
 //some actions on order model
 const order = await ordersModel.findOne({doc.orders[0],{})
})

module.exports = connection.model(saleSchema)

//file name : orders.model.js

const salesModel = require("./sales.model")
const connection = require("./database/connection")

const ordersSchema = new mongoose.Schema(
  {
    orderNumber : {type : String}
   
  },
  {
    timestamps: true,
  }
);

ordersSchema.post("save",async function(doc){
 //some actions on sales model
 const sale = await sales.findOne({order : doc._id},{})
 //send email for this sale
})

module.exports = connection.model(saleSchema)

Now since sale.model is requiring orders.model file and orders.model file is requiring sales.model file I am getting a circular dependency error and my question is what pattern can I use to avoid that

Wrap a loosely typed interface and make it strongly typed

There is an external API that I have to use with the following signature:

class Item {
    String type;
    String name;
    ///...setters, getters
}

interface ItemFinder {
     List<Item> getItemsByType(String type);
}

In my application,

If I call getItemsByType("vegetables"), then I receive List(Item(type="vegetables", name="Lettuce"), Item(type="vegetables", name="Tomato"))

If I call getItemsByType("berries"), then I receive List(Item(type="berries", name="Strawberry"), Item(type="berries", name="Cranberry"))

If I call getItemsByType("shapes"), then I receive List(Item(type="shapes", name="Square"), Item(type="shapes", name="Triangle")) etc... and there are dozens of types like this.

I want to avoid common type errors, I.e. avoid assigning berries to vegetables.

What is the best way to wrap this loosely typed interface, to make it more strongly typed? I.e. what is the best way to implement something like the following:

class Vegetable /* maybe extends something ? */ {
    String name;
}
class Berry /* maybe extends something ? */ {
    String name;
}
class Shape /* maybe extends something ? */ {
    String name;
}
...
List<Berry> berries = getStronglyTyped(Berry.class); // maybe some factory here instead of a class ?

jeudi 22 juin 2023

Generic Repository using EF

I'm trying to build generic repository which I will use to get data with or without includes, add data, update data, delete data. I searched a bunch of websites, but still nothing to match my requests.

I have following code which has problem saying that I should be explicit about the type of set and it can't be generic. Do you guys have any ideas on how to build the thing I'm asking for?

public class BaseRepository<T>
{
    private readonly InstagramDbContext _context;

    public BaseRepository(InstagramDbContext context)
    {
        _context = context;
    }

    public IQueryable<T> FindBy(Expression<Func<T, bool>> predicate, params Expression<Func<T, object>>[] includes)
    {
        var query = _context.Set<T>().Where(predicate);
        return includes.Aggregate(query, (current, includeProperty) => current.Include(includeProperty));
    }
}

mercredi 21 juin 2023

Find Specific Pattern in String via SQL

I have a column of what we'll call remarks. Basically notes. I want to see if I can extract exact patterns of alpha or numbers from these notes see example.

 REMARKS                           
 'This is the magic key 24HMBC123456 dont lose it ex644' 
 'Code 31hbxx123456 is tested good px543' 
 'rt445 has tested 61CGRW123456 as good jx163'

for the above column I'd test and extract for a pattern of 2 numbers followed by 4 alphas followed by 6 numbers. but I dont know how to code that to get just:

    24HMBC123456
    31hbxx123456
    61CGRW123456 

Any help is appreciated.

I thought to use a case when REGEXP_INSTR mixed with some substrings but this appears either Im over complicating it or its really that complicated.

Separating PyTest Tests and Sphinx Documentation in Docker with Poetry for Development

I want to create a design for utilizing Poetry within a Docker environment. During development, I want to have separate directories for PyTest test files (tests/) and Sphinx documentation (docs/) on the host machine, rather than including them directly in the Docker image. Is there a way I could run tests for the Python files within the Docker image and create auto-updating documentation from Sphinx, which is only present on the host machine?

Context:

I am utilizing Docker for my development environment and Poetry for dependency management. My goal is to establish a workflow where the PyTest test files and Sphinx documentation directories remain on the host machine, while the actual code and dependencies are contained within the Docker image. This approach allows for easier test execution within the Docker environment and ensures that Sphinx generates up-to-date documentation without the need to rebuild the entire Docker image.

Directory Structure:

Host Machine:
├── project/
│   ├── code/
│   │   ├── file1.py
│   │   ├── file2.py
│   │   └── ...
│   ├── tests/
│   │   ├── test_file1.py
│   │   ├── test_file2.py
│   │   └── ...
│   └── docs/
│       ├── conf.py
│       ├── index.rst
│       ├── ...
│       └── ...
└── Dockerfile

Docker Machine:
├── code/
│   ├── file1.py
│   ├── file2.py
│   └── ...
└── Dockerfile

Specifically, I would like to know:

  1. How can I run PyTest tests against the Python code within the Docker image, while keeping the test files (tests/) on the host machine?
  2. Is there a way to configure Sphinx to generate the documentation from the Sphinx source files (docs/) on the host machine, without including them in the Docker image?
  3. What would be the recommended setup and workflow for achieving this combination of Docker, Poetry, PyTest, and Sphinx in terms of file organization and command configurations?

I appreciate any guidance or suggestions on how to design this development environment to meet these requirements.

design pattern used in java functional interface [closed]

I was asked a question about functional interface.

What is the design pattern used in functional interface in java?

But as far as I know, no design pattern used here in functional interface. Is it true? Or is there a design pattern used in functional interface?

Can we use SAGA name for a third party Framework?

I have been creating a free and open source framework for microservices using SAGA design pattern. I have named it as ActionSAGA. But i have a doubt whether a third party company like us can use that name or not as a suffix. Because we are using that concept as well.

I want to know there's is a possibility to have a leagal problem regarding the name in the future?

Please consult me by professionals. Thank you!

I wish to have a leagal advice.

mardi 20 juin 2023

How to provide support for custom implementation in a Java library while offering a default implementation?

I'm developing a Java-based library that includes a default implementation packaged within the JAR file. However, I also want to provide support for consumer applications to have their own custom implementation if needed.

The default implementation is known by class A, which is part of the library. The consumer application can write their own implementation using class B, as shown in the example below. In class B, there is a setHandler method that should override if the consumer application has its own implementation of E. If the consumer does not provide a custom implementation, the default implementation from class A should be used.

The packaged jar have default implementation A and used in class D

class A implements E{
    // Default implementation of E packed with jar
}

@Configuration
class D {
    
    @Autowired
    E e;
    
    public void config( HttpConfig conf ){

        conf.setHandler(e);
    }

}

The consumer class can have own implementation B which can implements E

class B implements E{
    // Implementation which source repository can have
}

How can I design the library to allow the consumer application to easily provide their own implementation for the setHandler method, overriding the default implementation from class E if necessary?

Implementing Dynamic Enumeration with X-Macros in C

I came across an issue: I needed an enumeration, where the value could never be invalid. There doesn't seem to be a design pattern for this, so I'll call this Dynamic Enumeration:

Usually, an enumerator is created in the following way:

#include <iostream>

enum MyEnum {
    Value1,
    Value2
};

int main() {
    MyEnum value = Value2;
    std::cout << value << std::endl;  // Output: 1

    return 0;
}

However, by utilizing X-macros, we can split the definition of MyEnum between multiple files:

main.ccp:

#include <iostream>
#include "EnumValues.h"

#define ENUM_VALUES_1 \
    ENUM_VALUE(Value1) \

#define ENUM_VALUES_2 \
     ENUM_VALUE(Value2)

#define ENUM_VALUES \
    ENUM_VALUES_1 \
    ENUM_VALUES_2

enum MyEnum {
    ENUM_VALUES
};

#undef ENUM_VALUE
#undef ENUM_VALUES_1
#undef ENUM_VALUES_2

int main() {
    MyEnum value = Value2;
    std::cout << value << std::endl;  // Output: 1

    return 0;
}

Enums.h:

#pragma once

#define ENUM_VALUE(x) x,

EnumValues.h:

#pragma once
#include "Enums.h"

#define ENUM_VALUES_1 \
    ENUM_VALUE(Value1) \

#define ENUM_VALUES_2 \
     ENUM_VALUE(Value2)

This can be used to create a useful design pattern: A single-argument macro that can define enumerator values, without touching the definition of the enumerator directly:

CREATE_ENUM(Foo); // Defines Foo-feature as an enumerator value for MyEnum.

This allows for dynamic enumeration: For example, You can create an enumerator of all functioning features, where only compiled features exist as enumerator values. The specific integer value of each enumerator is undefined, but each enumerator must have been compiled, preventing the use of empty, unused enumerator values.

However, it is not clear how this 'single-argument macro' can be created: The issue lies within this #define block:

#define ENUM_VALUES \
    ENUM_VALUES_1 \
    ENUM_VALUES_2

Manually listing all ENUM_VALUES macros used across other files defeats the purpose of the design pattern.

Is there a C++ standard way for dynamically creating these ENUM_VALUES? Is the X-macro approach flawed?

How do I create this "dynamic enumeration" design pattern in C++?

lundi 19 juin 2023

Factory pattern can be used to create business objects?

I have read various articles on the factory pattern. However almost in all the examples the objects used are "flat" (beans, dtos,) ie. Dogs, Cars, etc. and that's good it helped me understand. But what about service objects, those that execute specific logic.

For example, let's say I want to create an app that supports credit card and debit card payments. Assuming that the logic is different for both cases, my idea is to create an interface CardPayment with both implementations: CreditCardPayemnt and DebitCardPayemnt.

The following would be to create the factory class that will return an object of type CardPayment (instantiated with one of the implementations based on some input parameter)

In this way, the processPayment() (method from CardPayment interface)could be executed without caring about the type of payment.

enter image description here

Would this be a valid use of the factory pattern? My concern is based on the fact that factory is a creational pattern and what I propose here is yes the creation of an object (CardPayment), but it is more behavior oriented.

Most of the examples I've seen consist of objects that have different attributes so it's useful to use factory to create one or the other, but what about objects that are different because their operation itself is different.

A function as an argument in Julia (best practice / code design)

What is the best/most elegant code design in the Julia programming language for the following problem:

The modules mod1, mod2, mod3, ... implement a complicated function fun(a,b,c), which calculates and returns a matrix M.

A function foo of my program needs to calculate the matrix M repeatably via the function fun with varying input parameters a,b,c. However, the user of my program can specify which module is used for fun. Note, that the user is no programmer and only wants to type something like julia program.jl and specifies the used module with a string like "MODULE = mod2" in some input file.

The most naive and inelegant solution would probably be via if...elseif...

function foo(...
[...]
    if SpecifiedModule == "mod1"
        M = mod1.fun(a,b,c)
    elseif SpecifiedModule == "mod2"
        M = mod2.fun(a,b,c)
    SpecifiedModule == "mod3"
        M = mod3.fun(a,b,c)
    end
    # process M

An alternative way would be to use function-pointers. Or even functors as known from C++?

What is best practice in Julia for this case? Is there a way to get rid of this ugly if..elseif... code?

PS: there are similarities to the case of finding an optimized value of a function, like in the module Optim.jl (https://github.com/JuliaNLSolvers/Optim.jl/). If I am not wrong, a user specified function f is passed as an argument to the optimize(f, ...) function.

Draw pattern in python depending on direction and length of number input

I try to write a function print_histogram(n, direction='⇑', colour='blue') takes in

- a positive integer (possibly 0) as first argument;

- a character that represents one of 4 possible irections as second argument;

- the string 'blue' or 'red' as third argument.

Both second and third arguments have default values

I want to use the digits of the first argument to print out a histogram that "grows" in the direction given by the second argument, the square that marks the start of the first bar being of colour given by the third argument. What is printed out is a rectangle with a checkered pattern, the white squares "outside" the histogram "hiding" the pattern.

Below is the example of my desired input and output

for ex : print_histogram(1003290, direction='⇑', colour='blue') or print_histogram(1003290)

enter image description here

print_histogram(1003290, '⇒')

enter image description here

print_histogram(1003290, colour='red')
enter image description here

print_histogram(1003290, '⇓', 'red')
enter image description here

The code points of the Unicode characters are in base 16: 21d0, 21d1, 21d2, 21d3, 1f7e6, 1f7e5 and 2b1c. Could you help me with this ? I am confused how to make the connection between the direction and also alternating the check board

Design patten for multiple actions java

I am developing a system that allows the user to create information about objects in the database. The requirements are the user can create the information by submitting the data multiple times (multiple screens, step by step). So what is the suitable design pattern for this case? enter image description here

Currently, my implementation is using multiple controller endpoints, and multiple services to create and update the data. So I'm curious if there are some better approaches than mine.

dimanche 18 juin 2023

How can we set a pattern for a phone number with css

I'm creating a shopify app and using xo booking system for bookings but couldn't set pattern. Is there a way to add pattern with css? or what should be min and max for 10 digit phone number and out of range text.

i tried several values for min and max but doesn't work . Any help would be appreciated.

How to manage update command using CQRS pattern for multiple scenarios?

I am using the CQRS pattern and have come across a scenario where I need some help. To understand the issue let's say we have an entity User which has UserId, FirstName, LastName.... in an application AppA I only need to update the FirstName and for this, I have the below command:

public sealed record UpdateUserCommand(int UserId, string FirstName) : IRequest

Then I have another application AppB that another developer is working on and he is sharing the library using the CQRS pattern. From AppB the developer wants to update FirstName & LastName. The above command is changed to:

public sealed record UpdateUserCommand(int UserId, string FirstName, LastName) : IRequest

This change has broken my code in AppA. I need help to understand what is the best practice to handle such a situation. If I am understanding the CQRS correctly then shouldn't be the all commands be specific for each scenario and in this case I need to have two commands as follow?

public sealed record UpdateUserFirstNameCommand(int UserId, string FirstName) : IRequest

public sealed record UpdateUserFullNameCommand(int UserId, string FirstName, LastName) : IRequest

shouldn't I use them in each separate application? Please help me with how should I implement it.

Thanks.

samedi 17 juin 2023

What is traditional home decor style?

What is traditional home decor products which helps in decorating our home and room and other areas related to outdoor areas , indoor areas and others . Peoducts like wall Art, decor items,

I am Expecting that anyone suggest me the website from where I purchase good and budget friendly website , which having different categories Products .

vendredi 16 juin 2023

MS SQL Server Connector [Flutter integration]

I'm looking to implement a function to connect to SQL Server in a Flutter Desktop app and looking for some best practices on how to do this. The requirement is that this runs locally (mentioning this because I've seen the advice to build a web server and make an HTTP call from the Flutter app). Given the lack of Flutter/Dart libraries to connect to MS SQL Server, I would write that part of the code in another language and then integrate that into Flutter.

Different patterns I've considered:

Options 2 and 3 seem more hackish than the first. Is there some guidance around design patterns or for flutter apps generally, or does anyone have experience implementing something like this?

Does this flow chart appear to be correct? This is my first time creating a flowchart

FLOWCHART

Does this flowchart looks alright for a flight arrivals map which shows list of arrivals when we hover over an airport label and shows a separate list of delayed arrivals when we double click an airport label. The first list dissaperas after we double click and then only the delayed arrivals list is displayed.Thanksenter image description here

It is my first time crreating a flow chart

Which design pattern should I use for creating different types of real estate ads?

I am developing a marketplace for real estate ads and I need some advice on which design pattern to use for creating different types of ads. Each ad can be either a Property or a Residence, and each Property has subclasses such as House, Flat, Garage, etc. Each subclass has its own fields and methods. Each Property also has a type of transaction, such as Buy, BuyNew, Rent, VacationRent, Colocation, etc. Each transaction type also has its own fields and methods. For example, Rent has duration and deposit fields, while VacationRent has rent fields plus vacation rent fields.

I want to know how to create an ad object that can handle different types of properties and transactions without using too many if-else statements or switch cases. I have read about some design patterns such as Strategy, State, Factory Method, etc., but I am not sure which one is the best for my problem. Can anyone suggest a good design pattern for this scenario. I am using PHP as my programming language.

I have searched online for similar problems but I could not find any clear solutions or examples.

jeudi 15 juin 2023

How to avoid recomputing several variables without completely refactoring code

I have a category of functions 'detectors', that, given a video, a space scale parameter and a time scale parameter, detect some interest points. I wrote a 'MultiscaleDetector' function, that basically takes a list of space scale parameters and a 'detector' function as parameters and executes the given detector factor for every scale.

This is how they look:

def GaborDetector(v, sigma, tau, threshold, num_points):
    """
    Gabor Detector
    
    Keyword arguments:
    video -- input video (y_len, x_len, frames)
    sigma -- Gaussian kernel space standard deviation
    tau -- Gaussian kernel time standard deviation
    kappa -- Gabor response threshold
    """
    # setup video
    video = v.copy()
    video = video.astype(float)/video.max()
    video = video_smoothen_space(video, sigma)
    # first define a linspace of width -2tau to 2tau
    time = np.linspace(-2*tau, 2*tau, int(4*tau+1))
    omega = 4/tau
    # define the gabor filters
    h_ev = np.exp(-time**2/(2*tau**2)) * np.cos(2*np.pi*omega*time)
    h_od = np.exp(-time**2/(2*tau**2)) * np.sin(2*np.pi*omega*time)
    # normalize the L1 norm
    h_ev /= np.linalg.norm(h_ev, ord=1)
    h_od /= np.linalg.norm(h_od, ord=1)
    # compute the response
    response = (scp.convolve1d(video, h_ev, axis=2) ** 2) + (scp.convolve1d(video, h_od, axis=2) ** 2)
    points = interest_points(response, num=num_points, threshold=threshold, scale=sigma)
    return points
def MultiscaleDetector(detector, video, sigmas, tau, num_points):
    """
    Multiscale Detector

    Executes a detector at multiple scales. Detector has to be a function that
    takes a video as input, along with other parameters, and returns a list of interest points.

    
    Keyword arguments:
    detector -- function that returns interest points
    video -- input video (y_len, x_len, frames)
    sigmas -- list of scales
    """
    
    # for every scale, compute the response
    points = []
    for sigm in sigmas:
        found = detector(video, sigm, tau)
        points.append(found)

    # filter the points, currently irrelevant

As you can maybe already notice, there is some heavy computation done inside the "GaborDetector" function, that depends only on the time parameter. Therefore, the "MultiscaleDetector" function unnecessarily recomputes these variables in each call.

In an attempt to avoid refactoring the code, I came up with what I wished was a nice trick, but believed it would be vain:

def MultiscaleDetector(detector, video, sigmas, tau, num_points):
    """
    Multiscale Detector

    Executes a detector at multiple scales. Detector has to be a function that
    takes a video as input, along with other parameters, and returns a list of interest points.

    
    Keyword arguments:
    detector -- function that returns interest points
    video -- input video (y_len, x_len, frames)
    sigmas -- list of scales
    """
    
    optimization_trick = lambda s_param: detector(video, s_param, tau)
    # for every scale, compute the response
    points = []
    for sigm in sigmas:
        found = optimization_trick(sigm)
        points.append(found)

    # filter the points, currently irrelevant

I hoped that the variables dependent only on tau would remain "stored" somehow in the "optimization_trick" and avoid being recomputed. However, when I timed the different implementations, the difference was around 0.02 seconds, with the "optimized" function being faster.

Using the Usercommand class for a button

Im trying to add functionality to a button in a WPF using the MVVM pattern in C# but im not quite sure on how to do it via using the Viewmodel class.

I tried adding functionality via the MainWindow from my WPF but that'd be faithful to the pattern. Furthermore i tried making a Usercommand class that implements ICommand but im not quite sure how it works.

Turning features on/off at compile time: #if vs. wrapper vs. empty implementation

I have a C codebase for some embedded project that can be configured to run on a number of different PCBs with different hardware peripheral devices.

Configuration files dictate which of these devices are enabled or disabled, and I could use something like

#if FEATURE
do_something()
#endif

in order to enable it.

I can also use these variables in the build scripts to turn compilation of files on/off conditionally.

Now in my case calls that interact with these devices are all over the code. But, I don't want the implementation of these calls to be compiled into the binary, as it increases the size and allocates things like static variables which eat up my precious RAM (including some large buffers for storing messages that go up a network stack, for instance).

So I could use these #if statements all over the code to prevent compilation errors when I turn off compilation of the relevant .c files (but include the interface .h files). But even then, it becomes quite an "ifdef hell" which in my opinion makes the code badly readable.

So I've been trying to come up with alternatives. The options I have thought of so far:

  1. use wrapper functions that contain the #ifdef inside, so the main code does not suffer from this unreadability:
void do_something() {
#if FEATURE
    do_something_inner();
#endif
}
  1. add a different "dummy" .c file with an empty implementation for each interface I want to turn off and compile that .c file instead of the real implementation whenever my feature is turned off (or vice versa):
/// something_dummy.c
void do_something(){}

/// something_real.c
void do_something(){
    implementation goes here
}

What do you think is the best option and why? Or is there an option I haven't thought of?

(If it matters, I'm using Zephyr RTOS and generate the configuration using KConfig, which can be passed into both CMake and a C file containing the relevant #defines).

mercredi 14 juin 2023

Most efficient way to story multiple similar items in nosql database

I have multiple objects that represent the same general type of item and will be grouped into a single collection client side. However, I am trying to find and understand an efficient way to store these objects in Firebase Firestore.

My initial thought is to create a single collection and persist each object type in that collection and when I map my remote object to my cache object I will add a flag which will determine what object I need to cast it to when I map my cache object to my domain object.

C language pattern decoder

I am trying to develop a pattern decoder using a C language program. The pattern will be like for example:

5 8
1
2
4 
3 
1
1 3 2 1 0 1 2 1

It is a 5x8 board with painted and unpainted dots or squares. The pattern might be represented in a .txt file. The same representation can be seen on the attached image. The expected output is as follows, where represented by a '-' are the unpainted dots or squares and by '#' the painted ones.

Expected pattern

-#------
-##-----
####----
-----###
------#-

Program output

#-------
##------
####----
###---#-
####-###

I tried writing some code but it is not displaying or printing correctly and I have tried debugging with no success.

#include <stdio.h>

#define ROWS 5
#define COLS 8

int main() {
    int row_counts[] = {1, 2, 4, 3, 1};
    int col_counts[] = {1, 3, 2, 1, 0, 1, 2, 1};

    char board[ROWS][COLS];
    int i, j;

    // Initialize the board with unpainted dots
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            board[i][j] = '-';
        }
    }

    // Paint the dots based on row and column counts
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < row_counts[i]; j++) {
            board[i][j] = '#';
        }
    }
    
    for (j = 0; j < COLS; j++) {
        for (i = ROWS - 1; i >= ROWS - col_counts[j]; i--) {
            board[i][j] = '#';
        }
    }

    // Print the decoded pattern
    for (i = 0; i < ROWS; i++) {
        for (j = 0; j < COLS; j++) {
            printf("%c", board[i][j]);
        }
        printf("\n");
    }

    return 0;
}

Logic for events and listeners

I'm writing simple snake game on java and i should use own events and listeners for collisions and food consumption. I made a research and as for now i found that observer is the best pattern to implement this. So i have a problem with logic for separation of my project First i have a class to fire events

public class Thrower implements Subject{
    private final ArrayList<Observer> observers;
    Thrower(){
        observers = new ArrayList<Observer>();
    }

    @Override
    public void addListener(Observer observer) {
        observers.add(observer);
    }

    @Override
    public void removeListener(Observer observer) {
        observers.remove(observer);
    }

    @Override
    public void fireFoodConsumption() {
        Event event = new Event(this);
        for(Observer observer : observers){
            observer.foodConsumption(event);
        }
    }

    @Override
    public void fireOwnCollision() {
        Event event = new Event(this);
        for(Observer observer : observers){
            observer.ownCollision(event);
        }
    }

    @Override
    public void fireWallCollision() {
        Event event = new Event(this);
        for(Observer observer: observers){
            observer.wallCollision(event);
        }
    }
}

Then i have this one

public class Catcher implements Observer{
    @Override
    public void foodConsumption(Event event) {

    }

    @Override
    public void wallCollision(Event event) {

    }

    @Override
    public void ownCollision(Event event) {

    }
}

Question is following: where my game logic should be, in Catcher class, or in another one and is it okay to use one interface(Observer) with many functions to present different events. Can somebody give a hint, or example of some codes like mine?

Two different implementations only for some methods of the same in class .NET (design pattern)

I have one class with many methods. I need to have two different implementations of two methods within class, but all other methods should be the same.

public class MyDataService: IMyDataService
{
       public void Method1() { // get data from external service } 
       public void Method2() { // get data from external service } 

       public void CommonMethodA() { // some get data} 
       public void CommonMethodB() { // some get data } 
       public void CommonMethodC() { // some get data }
        ... and other methods here 
}

IMyService is injected in Startup. In another layer we use these methods.

public class MyManager {

       public void DoComplexCalculations() {
            _myservice.CommonMethodA();

            _myservice.CommonMethodB();

            _myservice.Method1();
       }
}

public class Caculator1() {
     public void Do() { _mymanager.DoComplexCalculations(); }
}

However, now we have developed another application (in .net it is separate project within the same solution), it also calls MyManager.DoComplexCalculations.

public class Caculator2() {
    // we need to call the same calculations, but need different Metohd1 and Method2
    public void Do() { _mymanager.DoComplexCalculations(); }
}

Instead of calling Method1 and Method2 we need to get data form Cache (call FromCacheMethod1 and call FromCacheMethod2 ). All other methods are common and are still needed. Data are already cached before calling MyManager.DoComplexCalculations. What is best approach to achieve this?

  1. Using Decorator pattern, but in this case we should create a lot of unneeded code, just duplicating CommonMethodX calls in decorator class. And it doesn't sound actually like Decorator.

  2. Or add get from cache code inside Mehtod1 and Method2, but this also doesn't sound as good pattern.

Bash Regex in Python [closed]

i'm trying to search for a dead simple pattern in the same fashion as i would with a grep command but i cannot get this to work with python.

In bash it is pretty straight forward to search for a pattern in a string or file.

echo -e "orange Apple oranges\npinapple Orange apples\nkiwi apple oranges" | grep -i "orange.*apple"

I've really tried to do my homework and google it but can't nail where the issue, please help?

Here's an example of the results grep(bash) vs python the python will always return no result even when debugging. enter image description here

How to implement a many-to-many adapter in Python?

I have many functions that solve the same problem in different ways (different algorithms with different properties). The functions were programmed by different people, and each function accepts its input in a different format. As a simplified example, let's say that the input to all functions is a set of items.

  • Function A accepts a dict, where each key is an item name and the value is the number of copies of that item.
  • Function B accepts a list, where each element is simply the item name, and there is only one copy of each item.

I would like to build an adapter function, that allows the user to use both A and B with both a dict and a list. A pseudocode of the adapter could be:

def adapter(func:callable, input:any):
    if (input is a dict and func expects a dict):
       return func(input)
    elif (input is a list and func expects a list):
       return func(input)
    elif (input is a list and func expects a dict):
       return func({key:1 for key in list})  # convert list to dict
    elif (input is a dict and func expects a list):
       return func(list(input.keys()))  # convert dict to list
    else:
       raise TypeError

The problem with this pseudocode is that, for n input formats, n^2 conditions are required.

Is there a more efficient way to implement such an adapter function?

mardi 13 juin 2023

Are there design patterns for data classes in c? [duplicate]

In those years I've seen and used various "data design pattern", like for example the MVC approach, where the data are stored as private member of Model classes, with getter/setter function to access them, or similar to that the State Management Design, where you have the data in a central object alongside with accessors/mutators methods to access those property.

Also recently I've discovered the Entity Component System used in game engines development, that use a different approach to store and access the data, or system that use a central Manager class to alter the data instead of have a direct setter method on the object that hold the data.

What I want to ask if there's a list of data design pattern that give a name to those designs, describing how to structure the classes and what benefit/cons. those patterns have. Something like the patterns from the gang of 4, but for data management.

I've tried looking around, but searching "data design pattern" only lead to pattern used to structure the data in databases, and not in c++ classes.

Cast Interface to Subinterface to implement a single method in Java

I would like to "cast" an instance of an interface MyInterface and to a subinterface MyInterfacePlus that only implements the methods in the subinterface.

I can't seem to find an elegant solution. In the example below, MyInterface and OtherInterface are long established and implemented/used extensively by users. I would like to make no changes to MyInterface and add only a default method to OtherInterface. For all existing implementations of OtherInterface, the oneExtraMethod in the result of getMyInterfacePlus will do nothing. That is, the method needs to be there to be called, but it should do nothing.

public interface MyInterface {
    ...//lots of methods
}
public interface MyInterfacePlus extends MyInterface {
    void oneExtraMethod();
}
public interface OtherInterface {
    MyInterface getMyInterface();

    // ANY ELEGANT WAY TO DO THIS?
    default MyInterfacePlus getMyInterfacePlus() {
        MyInterface mi = getMyInterface();
        return new MyInterfacePlus() {
            @Override
            void oneExtraMethod(){};
            // override all (many) methods `methodX` in MyInterface to return `mi.methodX`
        }
    }
}

How to persist past states and action that lead to them in the State pattern using EF Core?

I'm implementing state pattern. The issue with all the available implementation is that they are interested only in the current state, but do not persist any information about the actions performed nor past states. Below we have User class where it changes the state, but there is no way to know what where past states and especially what action caused moving to the particular state.

How to persist information about the actions and past states?

public class User
{
    private UserState _userState;

    [NotMapped]
    public UserState State
    {
        get => _userState ?? (_userState = UserState.New(StateType, this));
        set => _userState = value;
    }

    public int Id { get; set; }
    public string StateType { get; set; }
    public int NumberOfAttempts { get; set; }
    public string Captcha { get; set; }
    public DateTimeOffset? BlockedUntil { get; set; }
}

public class UserAttemptsToLogin : UserState
{
    protected override void OnStart()
    {
        User.NumberOfAttempts = 0;
        User.Captcha = null;
    }

    public override void Login(string password)
    {
        if (password == "test")
            Become(new UserIsAuthorized());
        else
        {
            User.NumberOfAttempts++;
            if (User.NumberOfAttempts > 2)
                Become(new UserInputsCaptcha());
        }
    }
}

public class UserIsAuthorized : UserState
{
    public override bool HasAccess => true;

    public override void Logout()
    {
        Become(new UserAttemptsToLogin());
    }
}

public class UserInputsCaptcha : UserState
{
    protected override void OnStart()
    {
        User.Captcha = Guid.NewGuid().ToString();
    }

    public override void InputCaptcha(string captcha)
    {
        if (captcha == User.Captcha)
            Become(new UserAttemptsToLogin());
        else
            Become(new UserIsBlocked());
    }
}

public class UserIsBlocked : UserState
{
    protected override void OnStart()
    {
        User.BlockedUntil = DateTimeOffset.UtcNow.AddHours(1);
    }
}

public abstract class UserState
{
    protected User User { get; private set; }
    public virtual void Login(string password) => throw new InvalidOperationException();
    public virtual void InputCaptcha(string captcha) => throw new InvalidOperationException();
    public virtual void Logout() => throw new InvalidOperationException();
    public virtual bool HasAccess => false;

    protected virtual void OnStart()
    {
    }

    protected void Become(UserState next)
    {
        next.User = User;
        next.OnStart();
        User.StateType = next.GetType().Name;
        User.State = next;
    }

    public static UserState New(string type, User user)
    {
        switch (type)
        {
            case nameof(UserIsAuthorized): return new UserIsAuthorized {User = user};
            case nameof(UserInputsCaptcha): return new UserInputsCaptcha {User = user};
            case nameof(UserIsBlocked): return new UserIsBlocked {User = user};
            default: return new UserAttemptsToLogin {User = user};
        }
    }
}

lundi 12 juin 2023

Why is j not printing in j==n and why j gets printed as 6 when j==2?

#include<iostream>
using namespace std;
int main(){
    int n;
    cin>>n;
    for(int i=1;i<=n-2;i++){
        for(int j=1;j<=n;j++){
            if(i==1||i==n-2){
                cout<<j;
            }
            else{
                if(j==1||j==n){
                    cout<<j;
                }
            }
        }
        cout<<endl;
    }
    return 0;
    }

input:

6

output I get:

123456
16
16
123456

Why am I getting 6 printed in j==2 when i is not 1 or n-2 instead of j==n.

I have expected a hollow rectangle.

123456
1    6
1    6
123456

Decouple parent class dependencies from child's dependencies

I have a parent class, let's call it BaseClass

And I have multiple child classes extending this BaseClass. These child classes overrides some of the methods of the BaseClass.

public class BaseClass {

}

public class ChildA extends BaseClass{

}
....

public class ChildN extends BaseClass{

}

Now, I have logic in BaseClass which keeps on changing quite often. This usually leads to adding dependencies for the BaseClass - the constructor arguments of this BaseClass keeps on increasing.

public class BaseClass {
  public BaseClass(BaseDependencyOne one, BaseDependencyTwo two...., BaseDependencyN n) {
  }
}

public class ChildA {
  public ChildA (BaseDependencyOne one, BaseDependencyTwo two,..., BaseDependencyN n){
    super(one, two,..., n);
  }
}

Since, the BaseClass constructor is modified to accommodate more dependencies, the child classes also have to accommodate these dependencies. This involves making change in all child classes, which are very large in number. This in turn results in a huge change for a single addition of dependency in BaseClass

I thought of making the parent BaseClass as a dependency for all child classes. It will decouple the dependency of parent from child. But, this will break the parent-child relation ship, therefore, I won't have the overriding behaviour of child.

Framework for multiple web service calling

I would like to ask you, if there is some framework or designer (like SSIS) or best approach for calling of multiple dependent web services during processing of data.

I have a web application, where user press button and application creates message to MSMQ. There is an application that takes this message and calls the SOAP Method 1, takes response process data and call SOAP Method 2 etc.

Current state is horrible. It is a very deep method method and it is quite difficult to change this process. I have an idea to use Chain-of-responsibility design pattern, but this is a lot of programming. I think that someone must have solved a similar problem before.

Problems:

  • sequence can fail, because remote soap server stopped working sometime and pipeline should be able to start where failed.

dimanche 11 juin 2023

How should I design a new function according to OOP?

Say I need to add some function foo that takes an instance of type A and produces an instance of type B (assuming A and B are interfaces). In object-oriented design, what are the design limitations of either of the following designs?

Design 1:

class A {
  foo(): B { /* … */ }
}

Design 2:

class B {
  static foo(a: A): B { /* … */ }
}

How to avoid conditional statements in Factory?

Imagine we have interface Button{ void Click(); } and its implementations: AndroidButton and IOSButton. Is it possible to create appropriate button based on input like string os = "ios" without violating the sOlid ? Like when a new type of 'os' appeared, we would not have to change the existing code

samedi 10 juin 2023

Color Specification class in c# is giving me error : The non-generic type-or-method 'identifier' cannot be used with type arguments

i am learning design patterns in c# language, so i wrote class which filters the products by color(enum). I used interfaces Ispecification and Ifilter which take T as generic type. here is the code i wrote


public interface ISpecification<T>
        {
            public bool IsSatisfied(T t);
        }

        public interface IFilter<T>
        {
            IEnumerable<T> Filter(IEnumerable<T> items, ISpecification<T> specification);
        }

        public class ColorSpecification : ISpecification<Product>
        {
            private Color color;
            public ColorSpecification(Color color)
            {
                this.color = color;
            }

            public bool IsSatisfied(Product product)
            {
                return product.Color == color;
            }
        }

        /// <summary>
        /// new way, implements open close design pattern
        /// </summary>
        public class BetterFilter : IFilter<Product>
        {
            public IEnumerable<Product> Filter(IEnumerable<Product> items, ISpecification<Product> specification)
            {
                foreach (var i in items)
                {
                    if (specification.IsSatisfied(i)) yield return i;
                }
            }
        }
        
    public static void Main(string[] args)
           {    
             var bf = new BetterFilter();
            var cs = new ColorSpecification<Product>(Color.Green);
            foreach (var p in bf.Filter(products, cs))
            {
                Console.WriteLine($"Green products(new) {p.Name}");
            }
         }

when i instantiate a new class for ColorSpecification which determines whether an item of type <Product> satisfies the specification, i am getting an error in line

var cs = new ColorSpecification<Product>(Color.Green);

"The non-generic type-or-method 'ColorSpecification ' cannot be used with type arguments. how can i solve this error?

What is the optimal structure for Gateways and Adapters in Clean Architecture?

I'm embarking on a project using Clean Architecture, TypeScript, and TDD. One of my primary concerns is structuring the gateways and adapters correctly, particularly database adapters.

There's some advice circulating around suggesting to avoid classes due to the overhead and resource usage. With this assumption in mind, I've explored two different methods for structuring gateways and adapters:

  • Approach 1: Define gateways as interfaces, with adapters being the implementations of these interfaces.
  • Approach 2: Define gateways as higher-order functions (functions that return functions), accepting adapters as arguments.

In this repository, I've made a simple implementation of these approaches.

The first approach appears to be safer, providing a clear contract for the adapters and is, arguably, more straightforward. On the other hand, the second approach provides more flexibility by enabling logic to be inserted into the gateways, albeit at the cost of reduced safety and increased complexity.

I'm interested in the community's thoughts and advice on these approaches. Which approach is recommended, and why? Can anyone provide some examples or feedback on the structure I've set up in my repository?

Below are some code snippets from the repository for reference:

Gateways:

interface OrderGateway1 {
  getAll: () => Promise<Order[] | undefined>
  getById: (orderId: string) => Promise<Order | undefined>
}

const orderGateway2 = (orderDbAdapter: any) => {
  return {
    getAll: (): Order[] => orderDbAdapter.getAll(),
    getById: (orderId: string): Order => orderDbAdapter.getById(orderId),
  }
}

In-memory Data Storage Adapters:

const orderInMemoryDbAdapter1: OrderGateway1 = (() => {
  const ordersDb: Order[] = [...inMemoryDb.orders]
  return {
    getAll: () => Promise.resolve(ordersDb),
    getById: (orderId: string) => Promise.resolve(ordersDb.find((order) => order.id === orderId)),
  }
})()


const orderInMemoryDbAdapter2 = () => {
  const ordersDb: Order[] = [...inMemoryDb.orders]
  return {
    getAll: () => ordersDb,
    getById: (orderId: string) => ordersDb.find((order) => order.id === orderId),
  }
}

JSON Server Data Storage Adapters:

const orderJsonServerDbAdapter1: OrderGateway1 = {
  getAll: async (): Promise<Order[] | undefined> => {
    const result = await api.get<Order[]>('/orders')
    return result
  },
  getById: async (id: string): Promise<Order | undefined> => {
    const result = await api.get<Order>(`/orders/${id}`)
    return result
  },
}

const orderJsonServerDbAdapter2 = () => {
  return {
    getAll: async (): Promise<Order[] | undefined> => {
      const result = await api.get<Order[]>('/orders')
      return result
    },
    getById: async (id: string): Promise<Order | undefined> => {
      const result = await api.get<Order>(`/orders/${id}`)
      return result
    },
  }
}

Chain of Responsibility with async awaite method and exception handling in c#

I have Some async and await method if an error occurs, instead of throw an error, it just exits the handler and continues processing the rest of the methods in that service for example this is the handler

using System.Threading.Tasks;

namespace Chain.Of.Responsibility.Example.Chain.Pattern
{
    public abstract class Handler<T>
    {
        private IHandler<T> Next { get; set; }

        public virtual async Task Handle(T request)
        {
            Next?.Handle(request);
           
        }

        public IHandler<T> SetNext(IHandler<T> next)
        {
            Next = next;
            return Next;
        }
    }
}

and this is UsernameRequiredValidationHandler

using System; using System.Threading.Tasks;

namespace Chain.Of.Responsibility.Example.Chain.Pattern
{
    public class UsernameRequiredValidationHandler : Handler<User>, IHandler<User>
    {
        public override async Task Handle(User user)
        {
            if (string.IsNullOrWhiteSpace(user.Username))
            {
                throw new Exception("Username is required.");
            }
            base.Handle(user);
        }
    }
}

and this is PasswordRequiredValidationHandler

using System;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;

namespace Chain.Of.Responsibility.Example.Chain.Pattern
{
    public class PasswordRequiredValidationHandler : Handler<User>, IHandler<User>
    {
        public override async Task Handle(User user)
        {
          
            if (string.IsNullOrWhiteSpace(user.Password))
            {
                throw new Exception("Password is required.");
            }

             base.Handle(user);
        }
    }
}

and this is OnlyAdultValidationHandler

using System;
using System.Threading.Tasks;

namespace Chain.Of.Responsibility.Example.Chain.Pattern
{
    public class OnlyAdultValidationHandler : Handler<User>, IHandler<User>
    {
        public override async Task Handle(User user)
        {
            throw new Exception();
            if (user.BirthDate.Year > DateTime.Now.Year - 18)
            {
                throw new Exception("Age under 18 is not allowed.");
            }

            base.Handle(user);
        }
    }
}

and when exception throw in OnlyAdultValidationHandler the exception not catch in try catch block in the Register class

public class ChainPatternRegistrationProcessor
    {
        public async Task Register(User user)
        {
            try
            {
                var handler = new UsernameRequiredValidationHandler();
                handler.SetNext(new PasswordRequiredValidationHandler())
                    .SetNext(new OnlyAdultValidationHandler());

                await handler.Handle(user);
                Console.WriteLine("");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
    }

can we catch this error in Register class?

Runs fine in Atom but Runtime error(sigsegv) in codestudio compiler

The pattern to print if n=5 is

1 2 3 4 5

11 12 13 14 15

21 22 23 24 25

16 17 18 19 20

6 7 8 9 10

if anyone can tell me why and where is the overflow/segmentation fault.

     #include <bits/stdc++.h> 

     vector<string> printPattern(int n)
     {
     int matrix[n][n];
     int i=0;
     int j=n-1;
     int k=1;
     while(i<=j)
     {
           int x=0;
                    while (x <n&& i<=j) 
                    {
                         matrix[i][x]=k;
                     k++;
                     x++;
                    }
           i++;
           int y=0;
                   while(y<n && i<=j)
                   {   
                        matrix[j][y]=k;
                        k++;
                        y++;
                   }
           j--;
     }
     for (int i = 0; i <= n-1; i++)
     {
           for (int j = 0; j <=n-1; j++)
           {
                 cout<< matrix[i][j];
                 if (j < n - 1)
                 {
                       cout << " ";
                 }
           }
      cout<<endl;
     }
     }

Its a 2D array approach to a pattern problem in codingninja's codestudio interview problems.