jeudi 30 novembre 2023

how to design a project based system to make so many resource under project?

i want to design a system it is project based system, many resource is organized in project, and the url pattern will like this

  • /projects/{project_a}/dashboard
  • /projects/{project_a}/issues
  • /projects/{project_a}/issues/{issues_id}
  • /projects/{project_a}/users
  • /projects/{project_a}/tasks
  • /projects/{project_a}/tasks/{task_id}/attachments and i do not want to let every controller like ProjectXXXController, and make every jpa query with a where project_id equals xxx clause, how to smart design it? and is multi-tenant pattern a good choose?

a solution for project based system design

How to solve multiple class inheritance without duplicating code in my case?

My concrete classes can be one of the type permutations shown below. But, since I cannot inherit from two classes (case 4 and 5) I had to convert one of them to interface which introduce code duplication shown in FIX section below. I know someone will say "use composition", but I don't see how to change the design to take this into account.

Type permutations:

  1. ControllerSimulator
  2. MovingControllerSimulator
  3. RegistersControllerSimulator
  4. ControllerSimulator + RegistersControllerSimulator
  5. MovingControllerSimulator + RegistersControllerSimulator

CODE

public abstract class ControllerSimulator
{
   protected virtual void OnTurningOn() { }
   public void TurnOn()
   { 
     ...
   }
   
   protected virtual void OnTurningOff() { }
   public void TurnOff()
   { 
     ...
   }

   // more base methods
   ...
}

public abstract class MovingControllerSimulator : ControllerSimulator
{
   public virtual void Disable() { }

   public void SetMotionDuration(TimeSpan duration)
   {
       _motionDuration = duration;
   }

    protected void OnMoveStarted()
    {
       MoveStarted?.Invoke();
    }

    // more base methods
    ...
}

public abstract class RegistersControllerSimulator : ControllerSimulator
{
   protected Dictionary<string, object> Registers;
   
   protected abstract void OnRegisterChanged(string regName, object regVal); 
   public void UpdateRegister(string regName, object regVal)
   {
      Registers[regName] = regVal;
      OnRegisterChanged(...);
   }

   // more base methods
   ...
}

FIX

Since I cannot inherit from two classes I decided to convert RegistersControllerSimulator to an interface and create RegistersMovingControllerSimulator and RegistersNonMovingControllerSimulator. But, this requires code duplication which I potentially can solve by moving it to utils.

interface IRegistersControllerSimulator
{
   void UpdateRegister(string regName, object regVal);
}

public abstract class RegistersMovingControllerSimulator : MovingControllerSimulator, IRegistersControllerSimulator
{
   protected Dictionary<string, object> Registers;
   
   protected abstract void OnRegisterChanged(string regName, object regVal); 
   public void UpdateRegister(string regName, object regVal)
   {
      Registers[regName] = regVal;
      OnRegisterChanged(...);
   }
}    

public abstract class RegistersNonMovingControllerSimulator : ControllerSimulator, IRegistersControllerSimulator
{
   protected Dictionary<string, object> Registers;
   
   protected abstract void OnRegisterChanged(string regName, object regVal); 
   public void UpdateRegister(string regName, object regVal)
   {
      Registers[regName] = regVal;
      OnRegisterChanged(...);
   }
}

public class Concrete_Registers_Moving_Controller : RegistersMovingControllerSimulator
{
    // Uses "await Task.Delay(_motionDuration)" to imitate motion
}

public class Concrete_Registers_NonMoving_Controller : RegistersNonMovingControllerSimulator
{
}

public class Concrete_NonRegisters_Moving_Controller : MovingControllerSimulator
{
    // Uses "await Task.Delay(_motionDuration)" to imitate motion
}

public class Concrete_NonRegisters_NonMoving_Controller : ControllerSimulator
{
}

Java design pattern for mod system(Minecraft mcp)

i'm coding a minecraft client at the moment but I don't know how to write efficient a modular mod system.

Until now I have one superclass called mod and subclasses with the implementation in it and one ModManager class with an ArrayList mods but when I want to get a Attribute from example Mod1 I can't get it like ModManager.getMods().get(Index).attributeName because it's not in Mod. At the Moment I coded it so that these attribute are public static but I think thats not a solution? Is there a better design Pattern or way to implement it?

//Superclass 
package Client.Mods;

import net.minecraft.client.Minecraft;

public class Mod {
    protected Minecraft minecraft;
    private static ModCategory category;
    private static String name = "NoName ERROR";
    private static boolean toggled;


    public Mod(String name, ModCategory category) {
        this.name = name;
        this.category = category;
        toggled = false;
    }

    public void toggle() {
        toggled = !toggled;
        if(toggled)
            onEnable();
        else
            onDisable();
    }

    public void onEnable() {

    }

    public void onDisable() {

    }

    public void onUpdate() {

    }

    public void onRender() {

    }

    public static String getName() {
        return name;
    }

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

    public static boolean isToggled() {
        return toggled;
    }

    public void setToggled(boolean toggled) {
        this.toggled = toggled;
    }
}

package Client.Mods;

import net.minecraft.core.particles.ParticleTypes;
import net.minecraft.core.particles.SimpleParticleType;

public class BetterBowParticles extends Mod{

    public static SimpleParticleType particleType = ParticleTypes.CRIT;

    public BetterBowParticles(String name, ModCategory category) {
        super(name, category);
        particleType = ParticleTypes.ASH;
    }

    public void onRender() {

    }
}

mercredi 29 novembre 2023

Design pattern - json.Unmarshal()

Second argument of json.Unmarshal() api allows passing value of receiver type that implements below interface:

type Unmarshaler interface {
    UnmarshalJSON([]byte) error
}

json.Unmarshal() under the hood, uses reflect package, to find and invoke UnmarshalJSON() method of the receiver type(as shown below):

u, ut, pv := indirect(v, isNull)
if u != nil {
    return u.UnmarshalJSON(item)
}

Is there a term(design pattern name) for this approach(to inspect receiver type at runtime and invoke methods of that type)?

mardi 28 novembre 2023

Why my pyramid pattern code is not working?

So I tried below code for pyramid pattern and in output pattern first star is getting misplaced.can you tell me why this is happening?

This code I used

This is output i am getting

This is output i am expecting

I tried to develope star pyramid but one star is not getting placed where it is expected in pattern as you can see in above image.

How can I use, in the same project, old and recent python librairies which respectively need old and new python version?

I'm a researcher in cartography and some specific librairies are sometimes only working with python 2.7 while others need python 3.X. I have some projects that need to use multiple of these librairies, and there often are unsolvable conflicts.

For now, I run a first script in a python 2.7 environment (with conda), save the results, activate my 3.X environment (with conda), then run another script which needs python 3.X and loads the previous results.

This is laborious, I would like to automate my workflow but I don't know how to. Any good practices ?

PS: I use miniconda and VScode, but I'm open to other tools.

Best practices for GraphQL in general

What are best practices for designing and implementing GraphQL APIs, considering aspects such as schema design, query optimization, error handling, and security?

How certain practices contribute to improved performance, maintainability, and overall efficiency in GraphQL development. For example, how you would structure your schema to handle nested queries efficiently.

Also what are security concerns by implementing best practices for input validation, authentication, authorization, and protection against common security vulnerabilities. What are robust error-handling strategies within a resolver function that takes security into account?

Design Strategies for Integrating Enroll Plan-Specific Features in a Django Project

I am working on a Django project that comprises three main components:

  1. nkb_assessment_backend: Handles assessments and exams, featuring apps like nkb_exam and nkb_exam_extensions.
  2. nkb_learning_backend: Manages learning-related functionalities including user enroll plans, with apps such as nkb_auth_v2.
  3. nkb_backend: Serves as an overarching layer that possibly integrates or orchestrates functionalities of the above two components.

Requirement: We need to introduce functionality for enroll plan-specific exam slots in the nkb_assessment_backend, where these slots are dependent on user enroll plans managed in the nkb_learning_backend. The challenge is to implement this feature without creating direct dependencies or coupling between the two backend components.

Constraints:

  • Avoid modifications to the nkb_assessment_backend, particularly its database schema or existing models.
  • Maintain a loosely coupled architecture.
  • Ensure the solution is scalable and maintainable.

Question: What are the best practices or strategies to implement this feature within the given constraints and architecture? I am looking for insights or alternative approaches that could efficiently integrate this functionality while maintaining the structural integrity of our Django project.

lundi 27 novembre 2023

Having trouble to design the data pattern in swiftui

I am creating a camera app I have a CameraService which is an ObservableObject and it runs the session. and update some UI according to session status.Then I inject it using .envrionmentObject()

in camera service I have a SettingHolder, which is also an ObservableObject, it inits using the deviceinput variable from the session. It contains the settings status of the camera, users can change it and on screen.

Basically it works like that:

class CameraService:ObservableObject{
   @Published var xxxxxxx
   var settingHolder:SettingHolder?
   func createHolder(){
       settingHolder = SettingHolder(deviceinput)//variable in service
   }
}
class SettingHolder:ObservableObject{
   @Published var focusMode = .lock//view use this to display
   ...
   var input//get from outside
   func changeFocus(){}//using input to change focus
}

But to make the @Published var in SettingHolder can update the view, I have to pass the object from upper view instead of using @EnvironmentObject, and I have use a weird way to init my view

@StateObject var service:CameraService
@StateObject var holder:SettingHolder
    init(service:CameraService){
        self._service = StateObject(wrappedValue: service)
        self._holder = StateObject(wrappedValue: service.settingHolder)
    }

I know it is a bad way using singleton and this post also suggest do not nest the ObservableObject post. But I don't know how to find a better way. So confused about this part.

Decorating class having methods internally calling each other

I have a class IMessageProcessor

public interface IMessageProcessor{
   Task ProcessMessages();
   Task ProcessMessage(Message message);
}

with simplified implementation:

public class MessageProcessor : IMessageProcessor {
   public async Task ProcessMessages(){
      ...
      foreach (Message message in messages){
         await ProcessMessage(message)
      }
      ...
   }

   public Task ProcessMessage(Message message){
      // processing message
   }
}

I have also implemented decorator to be kind of error interceptor/handler:

public class ErrorHandlerDecorator : IMessageProcessor {
   IMessageProcessor decorated;

   public async Task ProcessMessages(){
      try{
         decorated.ProcessMessages();
      }
      catch{
         // exception handling logic
      }
   }

   public Task ProcessMessage(Message message){
      try{
         decorated.ProcessMessage(message);
      }
      catch{
         // other exception handling logic (retries etc.)
      }
   }
}

The problem is when I call ProcessMessages and hitting ProcessMessage method, my decorated ProcessMessage error handling logic is not executed as I call it directly on MessageProcessor instance.

Is this possible to somehow make decorator works when I call some methods internally in decorated class?

Thanks

How to write generic CRUD controller for all entities in golang?

I am creating a Go server using GoFiber to return data from MySQL database. I am using GORM library to save and fetch data from the db. I have 8 entities in total. I have defined model for these entites like this

package models

type Account struct {
    ID        uint      `json:"id" gorm:"primary_key;auto_increment;not_null"`
    Name      string    `json:"name"`
    Company   string    `json:"company"`
    GSTIN     string    `json:"gstin"`
    AccountNo string    `json:"accountNo" gorm:"unique"`
    IFSC      string    `json:"ifsc"`
    CreatedAt time.Time `json:"createdAt"`
    UpdatedAt time.Time `json:"updatedAt"`
}

Now, for each entity, I am writing 4 controller methods: Create, Update, List, Delete. It is basically the same code for each entity, just that the entity name is changing.

package controllers

// GET: List call
func GetAccounts(c *fiber.Ctx) error {
    accounts := new([]models.Account)
    result := database.DB.Find(accounts)
    if result.Error != nil {
        return result.Error
    }
    c.SendStatus(http.StatusOK)
    return c.JSON(accounts)
}

// POST
func CreateAccount(c *fiber.Ctx) error {
    account := new(models.Account)
    err := c.BodyParser(account)
    if err != nil {
        return err
    }
    result := database.DB.Create(account)
    if result.Error != nil{
        return result.Error
    }
    return c.SendStatus(http.StatusCreated)
}

Now, like this, I have written 8 x 4 =32 controller methods. All having duplicate code with just the entity name changing.

I have defined routes for each of these controllers manually as well.

    app.Post("api/account", controllers.CreateAccount)
    app.Get("api/accounts", controllers.GetAccounts)

There is definitely a better way to do this. I am not exactly sure how to do so or implement it. What interfaces should I define, what structs should I embedd, or what to do?

Looking for design pattern for flexibile generic serialization

I have a header-only library that provides three class (templates), namely

  • an abstract DAGNode,

    struct DAGNode;
    using NodePtr = std::shared_ptr<DAGNode>;
    
    class DAGNode 
    {
    public:
        virtual ~DAGNode(){}
        virtual std::string serialize() const = 0;
    
        auto const& get_parents() const {
            return m_parents;
        }
     protected:
        std::vector<NodePtr> m_parents;
    };
    
  • non-abstract class template impl::Derived<T>, which is derived from DAGNode and which is not part of the libraries API and

    // this needs to be specialized by consumer
    template <typename T>
    std::string serialize(T const&) {
        throw std::logic_error("Not implemented.");
    }
    
    namespace impl {
    
    // not part of the librarys API
    template <typename T>
    class Derived : public DAGNode 
    {
    public:
        Derived(T const& t) : m_value(t) {}
    
        std::string serialize() const override final
        {
            return ::serialize(m_value);
        }
    
        void add_parent(NodePtr const& ptr) {
            m_parents.push_back(ptr);
        }
    
    private:
        T m_value;
    };
    
    } // namespace impl
    
  • class template DerivedHolder<T>, which stores a std::shared_ptr<impl::Derived<T>>, which is part of the libraries API.

    
    template <typename T>
    class DerivedHolder
    {
    public:
        DerivedHolder(T const& t) : m_node(std::make_shared<impl::Derived<T>>(t)) {}
        NodePtr holder() const 
        {
            return m_node;
        }
    
        void add_parent(NodePtr const& p) {
            m_node->add_parent(p);
        }
    private:
        std::shared_ptr<impl::Derived<T>> m_node;
    };
    

In the current design, DAGNode has a virtual method std::string serialize() const. Derived<T> final overrides this method and delegates to the function template template <typename T> std::string ::serialize.

A consumer of this library will have to specialize the ::serialize function template for whatever types it wants to use. A typical usage scenario is that the consumer will use the visitor pattern to iterate over all DAGNodes and call the virtual serialize method.

Here is a minimal complete code example.

This approach works well, but I have now come across a use-case, where a consumer of this library needs to replace template <typename T> ::serialize with its own "magic implementation" along the lines of:

template <typename T>
std::string magic_serialize(T const& t) 
{
    if constexpr (std::is_same_v<T, MyMagicClass> ) {
        return t.as_string();
    } else {
        MagicClass m(t);
        return m.as_string();
    }
}

Since magic_serialize is in no way more special than ::serialize, specialization won't do the trick.

Therefore, we need to change the design pattern of the serialization framework of the header-only library. We are free to change any part of the library including the API, though I would prefer any minimally invasive solution over a complete rewrite. We are restricted to C++17 for now.

How can I change the library in such a way, that the consumer has complete control over how any type is to be serialized?

Is a "delayed reference" a known programming pattern?

I'm trying to understand JZZ's API.

One of the pecularities is after you obtain a port (a place to send MIDI instructions to), you can do this:

const a = port.noteOn(0, 'C5', 127); // plays note immediately, a is Promise that returns port
const b = port.wait(500); // b is a Promise that returns an object like port

port.noteOn(0, 'E5', 127); // plays note immediately
b.noteOn(0, 'G5', 127); // plays note in 500ms

The documentation says:

wait()

object.wait(delay) - returns a "delayed reference" of the object.

delay is the timeout in microseconds.

Is this "delayed reference" a known programming pattern? I haven't come across it.

dimanche 26 novembre 2023

Print the following pattern in JAVA [closed]

Question here. Print the following pattern

I tried using the nested loops but couldn't succeed. Please help me

I need to submit this assignment immediately please help someone please. I have tried using various methods but couldn't solve this.

samedi 25 novembre 2023

Creating a service layer with Django Rest Framework

I am fairly new to web-development and just studing design patterns and code architecture. Now, I am developing service layer for business logic. And here I have a dillema. One approach is to use command design pattern. Where I have a class which implements user creation and related processes (e.g. sending email, writting logs etc), also this class has one public method (entry point) and private methods, called inside the entry point. Here is the example of what I mean.

class CreateUser:
    def _create_user(self, **data) -> User:
        # here perform creation of user itself, requesting repository layer
        ...

    def _send_email(self, **data) -> None:
        # here I send email

    def _write_logs(self, **data) -> None:
        # writing logs to a file

    def execute(self, **data):
        self._create_user(**data)
        self._send_email(**data)
        self._write_logs(**data)

On the other hand, there is a approach where I create a common service as a class, that handles user authentication and registration and for each user action has one method:

class UserService:
    def create_user(self, **data) -> User:
        # call to repository
        # send email
        # write logs

    def update_user(self, **data) -> User:
        # call to repository
        # write logs

I don't really know what solution I should choose. I suppose that the command pattern is better, however I'm not sure about more complex scenarious. And throughout the project (or application), should I stuck to one design pattern (e.g. the command) or it's okay to alternate them? Maybe there are other approaches?

Sorry if my question seems silly, I am newbie and I feel lost among so much information (especially clean code patterns), so I am looking for help. Thanks in advance.

Seeking Advice on Optimizing Electrical Field Simulation App, Considering Transition to Python with Flet for Improved Efficiency

I developed a Java/JavaFX app that simulates the electrical field strenght of a cable as a 2D Heatmap (Image_Nr_1). The goal is for users to visually grasp the field distribution in their space.

Here's my current solution: I created a 2D array mirroring the canvas dimensions. Each cell holds an electrical field strength value, visualized by color. After the user draws a line (inputs: x_start, y_start, x_end, y_end, angle), I calculate local field values, add them to the global matrix, and update the canvas (Image_Nr_2). Unfortunately, the update causes significant lag.

Due to code complexity, bad design and inefficiency, I'm planning a rewrite. I'm considering switching to Python with Flet, using libraries like pandas and pycairo.

I thought of three ways of how I could improve the current algorythm design:

Option 1: Use pandas to operate similarly to my current method in the backend, however, create a local matrix for each device ( Image_Nr_3). This seems feasible, with SVG output facilitating device movement and being considerably smaller than JPEG/PNG in this case(as in theory only the min values of each color zone would need to be traced with a path fill or so). However, implementing multiple devices (Image_Nr_4) might be a challenge. This solution would work well when using Flet, as i could then add/remove a gesturedetector container for each new device added to the Canvas

Option 2: Stick with the matrix uptdating approach. Yet here would be the question of how can I selectively update only the changed part of the image in Flet, without replacing the entire image everytime a change has been made to the canvas?

Option 3: Combine both approaches — use a background image to display values for heat map in raster or (ideally) vector graphic format and provide individual gesturedetector containers, which would contain the black device line, for device manipulation. This requires addressing issues from both options.

I've been working on solving the above mentioned issues and have been experimenting with Flet and python. The first approach works, but not yet for overlapping heatmaps (as mentioned as the issue in the first approach). The second approach also partly works, but only by updating the entire image in the Flet Container.

Further, I have looked into libraries such as geopandas, as this is in theory exactly what I want -> would need to draw the polygons depending on the shape of the current heatmap.

I am seeking advice on the most efficient approach and potential solutions for handling multiple devices. Any insights are greatly appreciated!

vendredi 24 novembre 2023

handle methods in a class calling shared sub-methods with varying order and frequency in Java/Kotlin

How can I implement multiple methods in a Java/Kotlin class that invoke the same sub-methods but in a different order, or sometimes a method calls more sub-methods than another? Is there a design pattern for this scenario?

                  +------------------+
                  |   My Class       |
                  +------------------+
                           |
            +--------------+--------------+
            |                             |
 +------------------+         +------------------+
 | Method A         |         | Method B         |
 +------------------+         +------------------+
 | Call SubMethod 1 |         | Call SubMethod 2 |
 | Call SubMethod 2 |         | Call SubMethod 1 |
 | ...              |         | ...              |
 +------------------+         +------------------+
                

  +------------------+         +------------------+
  | SubMethod 1      |         | SubMethod 2      |
  +------------------+         +------------------+
  | Implementation   |         | Implementation   |
  | ...              |         | ...              |
  +------------------+         +------------------+

but i have a lot number of methods to implement on the same class.

Java : generics, inheritance and best design

I have a basic processing interface :

public interface Processing<T> {
    void appendTo(T t);
}

And this inheritance tree :

public class Animal {
}

public class Dog extends Animal {
    public void forDog() {}
}

public class Cat extends Animal {
    public forCat() {}
}

It's about processing animals. I have two solutions. Which one is the best pattern ?

SOLUTION A (with generics) :

public abstract class AbstractProcessing<T extends Animal> implements Processing<T> {
    protected void internalAppend() {}
}

public class CatProcssing extends AbstractProcessing<Cat>{

    @Override
    public void appendTo(Cat cat) {
        cat.forCat();
        internalAppend();
    }
}

public class DogProcessing extends AbstractProcessing<Dog>{
    
    @Override
    public void appendTo(Dog dog) {
        dog.forDog();
        internalAppend();
    }
}

SOLUTION B :

public class AnimalProcessing implements Processing<Animal>{
    @Override
    public void appendTo(Animal animal) {
        if (animal instanceof Cat cat) {
            cat.forCat();
        } else if (animal instanceof Dog dog) {
            dog.forDog();
        } else {
            throw new IllegalArgumentException();
        }
        internalAppend();
    }

    private void internalAppend() { }
}

jeudi 23 novembre 2023

Django Model Structure for products with Multiple Categories

I want to know if it is possible (and if so, what is the most pythonic way) to have a product that belongs to multiple product categories. e.g. an avocado belonging to [Food->Fresh Food->Fruit & Vegetables->Salad & Herbs] as well [Food->Pantry->Global Cuisine->Mexican]?

I am currently using Django-MPTT to create the category tree for single-category products. How do I set up the Product and Category models, what would the data import look like, and what would an efficient query look like? I am open to any suggestion, even if it requires me to rewrite my project. I would appreciate ANY advice on anything to do with this problem.

I am currently using Django-MPTT to create the category tree for single-category products. It makes sense conceptually, but I'm struggling with the multiple-category tree.

I've found some examples of TreeManyToManyField

class Category(MPTTModel, CreationModificationDateMixin):
    parent = TreeForeignKey('self',
                            on_delete=models.CASCADE,
                            blank=True,
                            null=True)
    title = models.CharField(max_length=200)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ['tree_id', 'lft']
        verbose_name_plural = 'categories'


class Product(CreationModificationDateMixin):
    title = models.CharField(max_length=255)
    categories = TreeManyToManyField(Category)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name_plural = 'movies'

but there are no explanations or examples of import/creating data for such a model. I have also seen the following example of how to set up the Category model, but they use a BaseProduct which threw me off:

class CategoryProductBase(BaseProduct):
    main_category = TreeForeignKey(get_category_model_string('Category'))
    additional_categories = TreeManyToManyField(
        get_category_model_string('Category'),
        related_name='extra_product_categories')

Best Practices for Retrieving Selective Data from a Database in a RESTful API

I am currently working on designing a RESTful API that interacts with an SQL database containing a 'Users' table. The example 'Users' table has fields such as AccountID, Username, Password, Firstname, Lastname, Email, Text, Setting1, Setting2, and Setting3.

In the services layer of my application, I have implemented getters and setters for Email, Text, Setting1, Setting2, and Setting3. Additionally, there are getters for Firstname and Lastname (but no setters).

The challenge I am facing is how to efficiently retrieve data from the database when the server code calling these services requires selective fields to perform various operations, while maintaining seperation of the business/services logic from the SQL statements (which exist in data gateway classes). For instance, one part of the code may need Firstname, Setting1, and Setting2, while another part may only need Lastname and Setting3.

I've considered two potential solutions:

  1. Sequential Field Queries: Query each field independently and in sequence. For example, first query for Firstname, then Setting1, and finally Setting2.

  2. Retrieve All Fields: Query all fields and retrieve the necessary data, ignoring the unused fields based on the requirements of the client code.

I am seeking guidance on the following:

  • Best Practices: How is this problem typically solved in the design of RESTful APIs?

  • Pros and Cons: What are the advantages and disadvantages of each method (sequential queries vs. retrieving all fields)?

  • Alternative Solutions: Are there alternative approaches or best practices for efficiently handling selective data retrieval in a scenario like this?

For a code example, the services/business logic functions look like this:

  getUserEmail(userId: number): string {
    // Implement logic to retrieve user email using the database gateway
  }

  setUserEmail(userId: number, email: string): void {
    // Implement logic to update user email using the database gateway
  }

  // Implement similar functions for other fields

  loginUser(username: string, password: string): boolean {
    // Implement logic to check if the provided username and password match a user, using the database gateway
  }

  getUserFirstname(userId: number): string {
    // Implement logic to retrieve user's firstname using the database gateway
  }

  getUserLastname(userId: number): string {
    // Implement logic to retrieve user's lastname using the database gateway
  }

The database gateway class looks like this:

interface UserTableGateway {
  // CRUD Operations
  createUser(user: User): void;
  readUser(userId: number): User | null;
  updateUser(user: User): void;
  deleteUser(userId: number): void;

  // Additional Query Operations
  getUserByEmail(email: string): User | null;
  getUserByUsername(username: string): User | null;
}

I appreciate any insights, experiences, or recommendations that you can provide. Thank you!

mercredi 22 novembre 2023

Java Factory pattern

java spring boot : i have module A and module B each one have some specific services and i have a module c that don't have any dependencies to A and B so what i want is in module C i want to call services from module A or B i want to acheive that using factory pattern.

in module C i have this interface

public interface ThirdPartyCallsStrategy {
    void apply(String orderId);
}

and this is example of factory class

@Component
@AllArgsConstructor
public class CoreCallsFactory {

    private static final String A_PACKAGE = "com.testA.service";
    private static final String A_CLASS = "TestClassA";


    private static final String B_PACKAGE = "com.testB.service";
    private static final String B_CLASS = "TestClassA";


    @SneakyThrows
    public ThirdPartyCallsStrategy createThirdPartyCallsStrategy(String type) {

        Class<?> clazz;
        if (type.equals("A")) {
            clazz = Class.forName(String.format("%s.%s", A_PACKAGE , A_CLASS ));
            return (ThirdPartyCallsStrategy) clazz.getDeclaredConstructor().newInstance();
        }

        if (type.equals("B")) {
            clazz = Class.forName(String.format("%s.%s", B_PACKAGE , B_CLASS ));
            return (ThirdPartyCallsStrategy) clazz.getDeclaredConstructor().newInstance();
        }
        return null;
    }
}

ThirdPartyCallsStrategy is implemented in different services in different modules

And finally in module C, i make the instanciation through java reflective but this will be at runtime and i really appreciate cleaner way

`public String checkStatusAndRedirect(String orderId, String type) { boolean status = checkStatus(orderId); StringBuilder paymentResultUrl = new StringBuilder(frontUrl + "/public/payment/status?success=");

    if (status) {
        coreCallsFactory.createThirdPartyCallsStrategy(type).apply(orderId);
        paymentResultUrl.append(Boolean.TRUE);
    } else {
        paymentResultUrl.append(Boolean.FALSE);
    }
    return paymentResultUrl.toString();
}`

So what i need is a clean way and change this implementation

How can I "augment" a JS class with methods from another class, without extending it?

I'm writing an app that manages playlists. Basically, my actual logic looks like

//define playlist props
class Playlist{
    public tracks = [];
}

class ApiPlaylist extends Playlist{
    //fill playlist withs (single page) data from API
    public async loadPage(paginationSettings){
        const pageTracks = await...
        this.tracks = [...this.tracks,...pageTracks]; //concat tracks
    }
}

class Paginated extends ApiPlaylist{
    private iterations = 0;
    private endReached = false;
    public async loadAll(){
        while (!this.endReached){
            this.loadNext();
        }
    }
    public async loadNext(){
        this.iterations++;
        await this.loadPage(); //call ApiPlaylist method
        if(...){
            this.endReached = true; //stop iterating
        }
    }

}

const playlist = new Paginated();
playlist.loadAll();

It works.

But what if I have different others paginated datas to get, that are not related to playlists ?

I would like to use the mechanism from PaginatedPlaylist with another classes, without having to duplicate it.

Acually, Paginated extends ApiPlaylist. Is there a simple way to implement the methods from Paginated to ApiPlaylist without using extends ?

Something like

class ApiPlaylist [implements] Paginated{}
class ApiPost [implements] Paginated{}
class ApiPage [implements] Paginated{}

Thanks for your help !

mardi 21 novembre 2023

Shell Script Design Patteren: Source a library file VS Call different files?

We discuss about POSIX compliant shell script here.

While we are writing more and more shell scripts, we build some helper functions to reuse the codes.

We are considering putting a few helper functions (around 10 functions of the same category) into a library file (e.g. string_lib.sh) or splitting each functions into individual script files (e.g. str_replace, str_cmp, etc.) to be called directly.

Due to the potential problem of variable name collision, we lean towards splitting each functions into individual script files. But there will be more than a hundred of script files, which is hard to manage.

We understand in some cases, we do not have a choice to choose between these two.

  • If we need to pass (several) variables from functions back to the caller, we must use a library file and sources it, as they need to share the same variable scope. (Using text file to pass variable is not preferred in most cases.)

  • If we would just like to avoid one script file being too long, split it into different sections and source them sequentially. In this case they usually need some shared variables (e.g. setting variables).

In other cases, these would be the pros and cons comparison.

Grouping helper functions into library files:

  • (o) The library file will be sourced (by . string_lib.sh).
  • (+) Same category of functions written in same file. Easy to manage.
  • (-) Possible of variable name collision.
  • (-) Need to avoid double inclusion, or mutual recursive inclusion which will cause infinite loop.
  • (-) Too many inclusion may slower the script. If only a few functions are used within a library file, other function definitions are redundant.

Split functions into individual script files:

  • (o) The script files will be called directly, just like Linux programs.
  • (+) No need to source (i.e. .) before use. Just put all the scripts into the $PATH directory.
  • (+) Unnecessary functions are not sourced. Possibly faster loading.
  • (+) Called script is in a different shell, the sub-shell. No worry of variable name collision. (Similar concept as Java, C, etc.)
  • (-) One helper function will have one script file. There will be many script files. This is harder to manage.

There is another SO answer about bash design patterns and best practices. Especially Stefano Borini's Modularization section is inspiring. Its import function is smartly written. Do take a look when you need to source script files. However in that SO post, it did not compare between grouping functions into a library file versus splitting functions into individual files.

https://stackoverflow.com/a/739034/1884546

Are there any guidelines or recommended design patterns of shell scripts?

Golang project structure

Project strcture

project-root-directory/
├── internal/
│ ├── session/
│ │ ├── runner/
│ │ │ ├── null.go
│ │ │ ├── runner.go
│ │ │ ├── sql.go
│ │ │ └── source/
│ │ │ ---├── mysql.go
│ │ │ ---├── sql.go
│ │ │ ---└── source.go
│ │ └── cache/
│ └── database/
│ ---├── database.go
│ ---└── mysql.go

Interfaces:

database source runner

The main functionality revolves around 'runner' and 'source', with 'mysql' as the implementation. There will also be 'mysql' used for storage, so I want to clearly distinguish between when I'm calling storage and when I'm calling the database.

I've been adjusting the structure for two days now.I plan to add many more runners and databases.

I'm considering creating subfolders inside 'runner', but the structures they implement are 'runner'. It might become confusing, especially since I'll be using 'mysql' for storage as well. and I really dont want it to be called as mysql.Mysql and prefer it will be called runner.Mysql.

But I am afraid of a large package size but I really dont want sttr mysql.Mysql for each struct

Someone suggested """ I would create a runner repository inside the internal/session/runner (same for source)

Then implement the repository somewhere inside internal/mysql/runner.go and internal/mysql/source.go

"""

TBH I think it will problay what I will do

lundi 20 novembre 2023

Flutter: How to listen/get characteristic of a Text widget?

So, I am trying to make a border/stroke effect for Text widget using Stack and Positioned.

class BorderedText extends StatelessWidget {
  BorderedText({
    super.key,
    required this.text,
    required this.textSize,
    this.borderTextSize,
    required this.textColor,
    required this.borderTextColor,
  }) {
    borderTextSize ??= getBorderTextSize(textSize);
  }
  final String text;
  final double textSize;
  double? borderTextSize;
  final Color textColor;
  final Color borderTextColor;

  double getBorderTextSize(double textSize) {
    return textSize * 1.1;
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Positioned(
          child: Text(
            text,
            style: TextStyle(
              color: borderTextColor,
              fontSize: borderTextSize,
            ),
          ),
        ),
        Positioned(
          top: (borderTextSize! - textSize) * 0.5,
          left: (borderTextSize! - textSize) * 0.2,
          child: Text(
            text,
            style: TextStyle(
              fontSize: textSize.toDouble(),
              color: textColor,
              letterSpacing: (borderTextSize! - textSize) * 0.45,
            ),
          ),
        ),
      ],
    );
  }
}

In some cases like textSize >= 70, the border text overflows. How do I listen to the overflow of that text widget and apply the same to the top text ?

Best way of handling two endpoints that depend on each other

I have two endpoints. The first endpoint generates a png image with matplotlib. The second endpoint generates a list of points (x, y coordinates in pixels). The frontend will then display the image as well as the x, y points and the user will be able to hover over the x,y points and view data.

The setup is:

  1. /endpoint1 -> returns svg/png
  2. /endpoint2 -> returns something like
{
   name1: {
     coords: [203, 3204],
     other_field: true,
   },
   name2: {
     coords: [509, 320],
     other_field: false,
   }
}

The issue is that the x, y points shift depending on the requested parameters of the image. For example, if the user requests a different image layer of the same image, the image ends up being shifted a bit and the points change. To generate the points, I would need to replicate a lot of the work to generate the image. Therefore, it makes a lot of sense to just return the points and image together. However, this is a lot of work for one endpoint and I'm wondering if there is a better way to handle this or if this design is considered good/okay?

Viable solution to handling long running query in Java

I have a Spring API which invokes rest call to an enterprise payment platform which calls into JPM Chase. All is fine on that and when taken we save response in our SQL Server DB. Our Spring API is new solution which went live last week into production. For most part has been working well apart with decent response times apart from 3 instances. On 3 different days around same timeframe I spotted through datadog an instance of processPayment endpoint taking over 1 min to respond.

After looking at DataDog logs its easy to spot SQL Query where the issue occurs. However having gone through datadog metrics around this query it typically executes in under 40 milli-seconds. The select query is hitting one table which has clustered + non clustered indexing on table. I don't believe there is an issue here however there obviously is some locking happened on DB at this time occurred maybe not at application level could been DB script being executed to fix data. So question really here is around how application should behave:

  1. Should the API be altered in such a scenario to rollback payment OR Just wait for query to return and capture the response in DB
  2. Is there another viable idea?

dimanche 19 novembre 2023

Is this UML diagram violating the Interface Segregation Principle?

I have created this UML diagram which applies the Template method design pattern: UML diagram

Both concrete classes share a lot of the logic whithin the template methods createTask and completeTask, with small variations for each concrete implementation, so I went for the Template method design pattern. However, one of the concrete classes does not need validation, so it implements the abstract method performValidations as an empty void method.

Is this violating the Interface Segregation Principle? Or would it be OK in this situation to leave the implementation of this abstract method in the concrete class empty?

samedi 18 novembre 2023

Java multiple datastores return same model

I am trying to solve a multiple data source issue where I need to return the same data model regardless of its source. The multiple data sources are all within their own module with correctly configured beans and config etc... (Redis, JPA, and a Rest-based module), they are all working and return their own respective models currently with associated annotations/validations for the given data source (here lies the issue in terms of why not just re-use the same model class from a common module, we cant as we have loads of logic tied up in their respective annotations).

I could upcast and return the interface, but ideally, I would be able to return the DataModel instead as that is what other applications currently code to alongside its ToString, equals, etc... I could also manually transform and map each field to the data model but I feel like there is some sort of pattern that would help me solve this problem.

So I started to look into the proxy pattern to solve this but the more I read about it the more I think it's not the correct one to follow as i would still end up having to cast etc... Are there any patterns that would help me solve this issue? or should I just upcast and return the interface each time from each resource?

Any advice would be appreciated as I think I am misunderstanding some basic concepts.

Project structure

//Not the exact impl, but you see the idea...

Main app

public interface IFetchData {
 Optional<List<DataModel>> fetchAll();
} 

public class FetchData implements IFetchData {
 private IRedisAccess redis; 
 private IJPAAccess jpa; 
 private IRest rest; 

 public FetchData(IRedisAccess redis, IJPAAccess jpa IRRest rest) {
  this.redis = redis;
  this.jpa = jpa;
  this.rest = rest;
 } 

 public Optional<List<DataModel>> fetchAll() {
  List<DataModel> data;
  data = redis.fetchAll();
  //if not null statement return Optional.of(data);
  data = jpa.fetchAll();
  //if not null statement return Optional.of(data);
  data = rest.fetchAll();
  return Optional.of(data);
 } 
  //more methods for interacting with data interfaces...
} 

Module common

public interface IDataGeneric {
 getId();
 getOtherField1();
} 

@Getter
public class DataModel implements IDataGeneric {
 private long id;
 private String OtherField1;
} 

Module Redis

@Getter
@RedisHash
public class DataModelRedis implements IDataGeneric {
 @Id
 private long id;
 @Index
 private String OtherField1;
}

public interface IRedisAcess{
 Optional<DataModelRedis> fetchId(long id);
 Optional<List<DataModelRedis>> fetchAll();
} 

public class RedisAccess implaments IRedisAcess {
 private RedisRepo redisRepo; 

 public RedisAccess(RedisRepo redisRepo) {
  this.redisRepo = redisRepo;
 } 
 methods for interacting with RedisRepo ...
} 

@Repoistory
public interface RedisRepo extends CrudRepository<DataModelRedis, long>{
 Optional<DataModelRedis> fetchId(long id);
 Optional<List<DataModelRedis>> fetchAll();
} 

Module JPA

@Getter
@Table
@Entity
public class DataModelJPA implements IDataGeneric {
 @Id
 @GeneratedValue
 private long id;
 private String OtherField1;
} 

public interface IJPAAccess{
 Optional<DataModelJPA> fetchId(long id);
 Optional<List<DataModelJPA>> fetchAll();
} 

public class JPAAccess implements IJPAAccess {
 private JPARepo jpaRepo; 

 public jpaAccess(JPARepo jpaRepo) {
  this.jpaRepo = jpaRepo;
 } 
 methods for interacting with jpaRepo ...
} 

@Repoistory
public interface JPARepo extends JPARepository<DataModelJPA, long>{
 Optional<DataModelJPA> fetchId(long id);
 Optional<List<DataModelJPA>> fetchAll();
} 

Filtering inside a processing method vs. filtering outside

In my application I am processing a List of IMyInterface instances. Not all, but some of them in addition also implement IAnotherInterface. Note that IAnotherInterface not derives from IMyInterface. Following the Single Responsibility Principle, I have a separate class that processes the IMyInterfaces instances via a Process method. Now I am struggling with the design choice whether

  1. the signature should be Process(IEnumerable<IMyInterface> items) and I filter for IAnotherInterface inside this method
  2. or the signature should be Process(IEnumerable<IAnotherInterface> items), meaning the filtering has to be done outside the processing method by the "client".

To make it more clear, these are the two code options I am struggling between:

// alternative 1:
List<MyInterface> items = GetItems(); // code not shown here
foreach(var item in items)
{
    // do some other processing before, not shown here

    // pass items to Process(IEnumerable<IMyInterface> items)
    myProcessor.Process(items);                
            
    // do some other processing afterwards, not shown here
}

// or alternative 2:
List<MyInterface> items = GetItems(); // code not shown here
foreach (var item in items)
{
    // do some other processing before, not shown here

    // pass items to Process(IEnumerable<IAnotherInterface> items)
    // -> need to filter first
    var filteredItems = filterForIAnotherInterface(items);
    myProcessor.Process(filteredItems);

    // do some other processing afterwards, not shown here
}

Is there any good reasoning for choosing one over the other? My own thoughts are that alternative 1 is easier to use for the client, but then the Process method has to do filtering which adds some kind of an additional responsibility besides it's main responsibility. On the other hand, alternative 2 in some way makes the processing pipeline less readable I think.

vendredi 17 novembre 2023

How do you connect 2 diferent languages or more [closed]

It may sound silly but Im a beginner and still trying to learn more. Many websites now days use many languages in their backend and frontend, such as python, C# for database and others. How do you connect 1 and another programming languages, like for an example if a user click the login button, it will trigger the javascript function and do lookup in the database with python or C# for an example, How do you guys connect that 2 different languages?

I've read and watch several things but still curious

How can I add pattern in only one color ggplot?

How can I manually choose colors to my pallete and also create a pattern in only one color? (I want transparent to be white color with some lines to differentiate from white color).

ggplot(mp8, aes(x = total, y = shape, fill = color)) +
geom_col(position = "fill") +
geom_col(colour = "black", position = "fill") +
scale_x_continuous(labels = scales::percent) +
coord_flip()

ggplot

Is there an advantage to hiding the model layer?

I was looking at a tutorial on the MVVM architecture pattern.

It says that views should never have direct access to the model. So all views are always hidden behind a view model.

For example:

Model

struct Location: Codable, Equatable {

//MARK: Properties

let id: String
let name: String
let country: String

//
let latitude: Double
let longitude: Double

init(id: String, name: String, country: String, latitude: Double, longitude: Double) {
    self.id = id
    self.name = name
    self.country = country
    self.latitude = latitude
    self.longitude = longitude
}
}

View Model that hide the model layer

final class LocationCellViewModel: Identifiable {

//MARK: Properties

private let location: Location

//
var locationViewModel: LocationViewModel {
    .init(location: location)
}

// MARK: - Initialization

init(location: Location) {
    self.location = location
}

// MARK: - Public API

var locationName: String {
    location.name
}

var locationCountry: String {
    location.country
}

....

}

View Model that will be in the view as property

final class LocationsViewModel {

//MARK: Properties

private(set) var locationCellViewModels: [LocationCellViewModel] = []

   ....

 }

Why might it be better to have a LocationCellViewModel array instead of a Location array in the LocationsViewModel class? Is there any advantage to doing so?

jeudi 16 novembre 2023

HTML5 phone number validation with pattern 1-XXX-XXX-XXXX

I want phone number to be in either two formats

xxx-xxx-xxxx

or

1-xxx-xxx-xxxx

if there is area code , it should be 1

can anyone help me with reg required pattern ?

thanks in advance

tried all possible way but no luck . please help

create include dependency graph for non-header files

In my project i have .c and .h files. But also other file extensions (e.g. .abc) that could have an include statement like

#include "common.h"

So they can be seen like normal headers. I have added ".abc" in the FILE_PATTERNS as "*.abc". But it is ignoring them and does not parse them. Any help?

Command pattern design in Spring

I have more or less implemented the command pattern in my Spring Boot application. I still have some doubts and would like to get second opinion on them.

I have a CommandFactory which - when given a command code - returns an instance of command object that implements Command functional interface and has a single method called execute.

Here's an example of use:

  • PersonService:
public Person addChildToPerson(Long personId, Long childId) {
    // acquire a person object from the database given an id
    Person person = (Person) commandFactory.create(GET_PERSON_BY_ID, personId).execute();
    // do the same with child
    Child child = (Child) commandFactory.create(GET_CHILD_BY_ID, childId).execute();
    return (Person) commandFactory.create(ADD_CHILD_TO_PERSON, person, child).execute();
}

Now here's the code of a AddChildToPersonCommand class that is responsible for attaching the child to the person and persisting it in the database.

  • AddChildToPersonCommand:
@RequiredArgsConstructor
public class AddChildToPersonCommand implements Command {

     // declare needed components for performing the command
     private final ChildRepository childRepository;
     private final Person person;
     private final Child child;

     @Override
     public Person execute() {
         // some logic
     }
}

Now, my doubts are mainly concerned with the "declared components" for the execution of a command. I'm unsure whether it's a better practice to operate on the actual objects that have been already retrieved using other commands (in the example: GetPersonByIdCommand & GetChildByIdCommand) or to just give the AddChildToPersonCommand the IDs and let it take care of the rest.

On the one hand, it seems a better approach to operate on the objects as it decreases the responsibilites of AddChildToPersonCommand.

On the other hand, though, the PersonService's methods may end up really big when the logic to-be-performed is not as trivial as in this example.

What do you think?

How to prevent coupling between our code and third party libraries?

Imagine we want to use the following library like this:

use GrahamCampbell\GitHub\GitHubManager;

class Foo
{
    private GitHubManager $github;

    public function __construct(GitHubManager $github)
    {
        $this->github = $github;
    }

    public function bar(): array
    {
        $this->github->issues()->show('GrahamCampbell', 'Laravel-GitHub', 2);
    }
}

Does it makes sense to create an interface like:

interface GitHubManagerInterface
{
    public function showIssues(): array;
}

Then implement it and bind the implementation to the interface and use it in my code like the following?

class Foo
{
    private GitHubManagerInterface $github;

    public function __construct(GitHubManagerInterface $github)
    {
        $this->github = $github;
    }

    public function bar(): array
    {
        $this->github->showIssues('GrahamCampbell', 'Laravel-GitHub', 2);
    }
}

Or there is a better way to prevent coupling? Or it's over engineering? :)

mercredi 15 novembre 2023

How do I implement a paypal checkout button, given the design patterns that I used in my application?

I followed a long tutorial, and built my application side by side using the design patterns from the turorial. I am now stuck, as I don't know how to implement paypal within the scheme I'm using. I used rxjs and observables to build the app, and admittedly I don't really understand them well. Sorry if this is vague, I don;t know what else to do. The paypal implementation is as follows...

This is the code I do not understand how to implement.

TS file

export class DeposittestComponent implements OnInit {
  

  PAYPAL_CLIENT_ID: string = '##################';

  myAmount: any

@ViewChild('paypalRef', { static: true }) private paypalRef!: ElementRef;

ngOnInit(): void {

  this.renderPaypalButton();

  }

  renderPaypalButton() {
    let orderRef: string | null = null;


    loadScript({ "clientId": this.PAYPAL_CLIENT_ID, currency: 'USD' })
      .then((loadedPaypal) => {
        if (loadedPaypal) {
          const paypal: PayPalNamespace = loadedPaypal;
          paypal.Buttons({
            style: {
              layout: 'vertical',
              color: 'blue',
              shape: 'rect',
              label: 'paypal',
            },
            createOrder: (data, actions) => {
              const postData = {
                amount: this.myAmount
              };
              return fetch(AppSettings.API_ENDPOINT + '/user/create_paypal_transaction', {
                method: "post",
                headers: {
                  'Accept': 'application/json, text/plain, */*',
                  'Content-Type': 'application/json'
                },
                body: JSON.stringify(postData)
              })
                .then((response) => response.json())
                .then((response) => {
                  orderRef = response.orderRef;
                  return response.id;
                });
            },
            onApprove: (data, actions) => {
              return fetch(AppSettings.API_ENDPOINT + `/user/orders/${data.orderID}/capture`, {
                method: "post",
                headers: {
                  'Accept': 'application/json, text/plain, */*',
                  'Content-Type': 'application/json',
                },
              })
                .then((response) => response.json())
                .then((orderData) => {
                  const errorDetail = Array.isArray(orderData.details) && orderData.details[0];

                  if (errorDetail && errorDetail.issue === 'INSTRUMENT_DECLINED') {
                    return actions.restart();
                  }
                  const transaction = orderData.purchase_units[0].payments.captures[0];

                  this.paypalRedirect(transaction.status, orderRef);
                });
            },
            onCancel: () => {
              // 
            },
            onError: (err) => {
              this.paypalRedirect('ERROR', orderRef);
            }
          }).render(this.paypalRef.nativeElement);
        } else {
          console.error("");
        }
      })
      .catch((error) => {
        console.error("", error);
      });

  }

  paypalRedirect(status: string, orderRef: string | null) {
    switch (status) {
      case 'COMPLETED':
        if (orderRef) {
          //this.router.navigate(\['/result/success/' + orderRef\]);
        } else {
          console.error("");
        }
        break;
      case 'ERROR':
        if (orderRef) {
          //this.router.navigate(\['/result/error/' + orderRef\]);
        } else {
          console.error("");
        }
        break;
      default:
        console.error("");
        break;
    }
  }

HTML

<div class="form-group">
                <label>Amount</label>

                <input type="text" ngModel name="myAmount" (ngModelChange)="myAmount=$event"
                    value="$" class="form-control">
            </div>

            <div #paypalRef></div>

This is the design pattern of everything else I have done in the application.

TS

export class NewGameAccountComponent implements OnInit {
 
  newGameAccountState$: Observable<State<CustomHttpResponse<any>>>;
  private dataSubject = new BehaviorSubject<CustomHttpResponse<any>>(null);
  private isLoadingSubject = new BehaviorSubject<boolean>(false);
  isLoading$ = this.isLoadingSubject.asObservable();
  readonly DataState = DataState;
  

  constructor(private gameAccountsService: GameAccountsService) { }

  ngOnInit(): void {
    this.newGameAccountState$ = this.gameAccountsService.activeGameAccounts$()
      .pipe(
        map(response => {
          console.log(response);
          this.dataSubject.next(response);
          return { dataState: DataState.LOADED, appData: response };
        }),
        startWith({ dataState: DataState.LOADING }),
        catchError((error: string) => {
          return of({ dataState: DataState.ERROR, error })
        })
      )
  }
  

  createNewGameAccount(newGameAccountForm: NgForm): void {
    this.isLoadingSubject.next(true);
    this.newGameAccountState$ = this.gameAccountsService.newGameAccount$(newGameAccountForm.value)
      .pipe(
        map(response => {
          console.log(response);
          newGameAccountForm.reset({});
          this.isLoadingSubject.next(false);
          return { dataState: DataState.LOADED, appData: this.dataSubject.value };
        }),
        startWith({ dataState: DataState.LOADED, appData: this.dataSubject.value }),
        catchError((error: string) => {
          this.isLoadingSubject.next(false);
          return of({ dataState: DataState.LOADED, error })
        })
      )
  }

}



HTML

<ng-container *ngIf="(newGameAccountState$ | async) as state" [ngSwitch]="state.dataState">
    <ng-container *ngSwitchCase="DataState.LOADED">
        <app-navbar [user]="state?.appData?.data?.user"></app-navbar>
        <section>
            <div class="container">
               


                <div class="row justify-content-center">
                    <div class="col-md-12">
                        <div class="card">
                            <div class="card-body">
                                <div class="text-center">
                                    <h2><i style="margin-right: 5px;" class="bi bi-person-plus-fill"></i> New Game
                                        Account
                                    </h2>
                                </div>
                    

                                <form #newGameAccountForm="ngForm"
                                    (ngSubmit)="createNewGameAccount(newGameAccountForm)">
                                    ///LOTS OF INPUTS FOR FORM
                                        <button
                                            [disabled]="state.dataState === DataState.LOADING || newGameAccountForm.invalid || newGameAccountForm.pristine|| (isLoading$ | async)"
                                            type="submit" class="btn btn-primary mt-5">
                                            <span *ngIf="isLoading$ | async" class="spinner-border spinner-border-sm"
                                                role="status" aria-hidden="true" style="margin-right: 5px;"></span>
                                            <span *ngIf="isLoading$ | async">Saving...</span>
                                            <span *ngIf="!(isLoading$ | async)">Save Game Account</span>
                                        </button>
                                        
                                    </div>
                                </form>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </section>
    </ng-container>
</ng-container>

SERVICE

export class GameAccountsService {
  


  private readonly server: string = AppSettings.API_ENDPOINT;

  constructor(private http: HttpClient) { }

activeGameAccounts$ = () => <Observable<CustomHttpResponse<User & GameAccount>>>
    this.http.get<CustomHttpResponse<User & GameAccount>>
      (`${this.server}/user/game_accounts/list_active`)
      .pipe(
        tap(console.log),
        catchError(this.handleError)
      );


 newGameAccount$ = (gameAccount: GameAccount) => <Observable<CustomHttpResponse<User & GameAccount>>>
    this.http.post<CustomHttpResponse<User & GameAccount>>
      (`${this.server}/user/game_account/create`, gameAccount)
      .pipe(
        tap(console.log),
        catchError(this.handleError)
      );

 }
  


interceptor

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
  private isTokenRefreshing: boolean = false;
  private refreshTokenSubject: BehaviorSubject<CustomHttpResponse<Profile>> = new BehaviorSubject(null);

  constructor(private userService: UserService) {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> | Observable<HttpResponse<unknown>>{
    if(request.url.includes('verify') || request.url.includes('login') || request.url.includes('register') 
            || request.url.includes('refresh') || request.url.includes('resetpassword')|| request.url.includes('reset_password')) {
          return next.handle(request);
      }
    return next.handle(this.addAuthorizationTokenHeader(request, localStorage.getItem(Key.TOKEN)))
      .pipe(
        catchError((error: HttpErrorResponse) => {
          if(error instanceof HttpErrorResponse && error.status === 401 && error.error.reason.includes('expired')) {
            return this.handleRefreshToken(request, next);
          } else {
            return throwError(() => error);
          }
        })
      );
  }

Could someone please help me. Simple stuff like even getting the paypal button to load while using the pattern i used is eluding me. Thank you for reading

Variadic template and perfect-forward question

Let's say we have 2 concrete classes.
Both of them can operate, but with different type of parameters (length & type). I want to make a generic operate:

class ServiceA
{
public:
  void operate();
}

class ServiceB
{
public:
  void operate(int, float);
}

class ServiceManager
{
public:
  enum class ServiceType {A, B};
  ServiceA sa;
  ServiceB sb;

  // pseudo-code
  template<typename... Ts>
  void operate(ServiceType t, Ts... args)
  {
    if (t == ServiceType::A)
      sa.operate();
    else if (t == ServiceType::B)
      sb.operate(std::forward<Ts>(args)...);
  }
}

ServiceManager sm;
sm.operate(ServiceType::A);          // sm.sa.operate()
sm.operate(ServiceType::B, 0, 1.0);  // sm.sb.operate(0, 1.0)

Questions:

  • Is this possible by using variadic template + perfect forwarding?
  • Is this program ill-formed? If so, how to deal with the "manager class + same operate but different params" problem?

mardi 14 novembre 2023

Using Refit and mock responses based on flag and not unitTests

I have an migration tool that gets data from different sources, map them and pushes it into a new system. The push to the new system is an api, I use the refit library as the httpClient. So because we dont want to push data to the new system always and just want to see the data we are going to push, I builded in a flag that gets passed everywhere : bool pushMode. If this is true, the data gets pushed to the new System, if not the data does not get pushed, but still gets all data from the sources and prints them out. Currently I have:

private async Task<KeyValuePair<Guid, MVInfo>?> CreateMyObject(Guid ownerId, Guid invoiceOwnerId, Guid objectTypeId,
        ExtendedObjectResponse extendedObjectResponse, int groupId, Guid accountId, bool pushMode)

    var creatObjectResult = pushMode==true? await _myApiClient.CreateObjectInNewSystem(myObject):new Domain.Responses.ItemCreationResponse {UniqueId = Guid.NewGuid()} ;

return new KeyValuePair<Guid, MVUnitInfo>(creatObjectResult.UniqueId, objectInfo.MVInfo);

I want to incorporate the flag sort of in the refit httpClient. So in the startup, specify the pushMode to false and then when the api is called that it will mock the response to something hardcoded or generated and when pushmode = true that it do the actual push. Any idea how to achieve this. Mock the response based on a flag set on startup

Best Practices for retrieving data in MVC: Concerns about Using POST for Retrieval and Token Handling

I'm currently working on a MVC app. I've implemented a route using a POST method to retrieve information and navigate to the corresponding page, and I have some concerns about the design practices I'm using. This is the route:

app.post('/metrics/service/:serviceId', async (req, res) => {
        target = req.query.target;
        errors = [];
        if (!target) {
            res.render('metrics', {error: 'Please select a target to get the metrics from'});
        }else{
            await MetricsService.getServiceDetails(req.params.serviceId, target, req.body.token).then((data) => {
                const mermaid_diagram = MetricsService.getMermaidServiceDiagram(data);
                res.render('metrics_service_details', {target: target, mermaid_diagram, data, cnt: 0, errors: errors})
            }).catch((error) => {
                res.status(500).send('Error: ' + error);
            }); 
        }
    });

I have several concerns regarding this implementation:

  • Use of POST for retrieval: Is it a good practice to use a POST method to retrieve data? Should I consider changing it to a GET method instead?

  • Handling tokens in the URL: The token required for authentication is passed as part of the request body (req.body.token). If I change the method to GET I'm concerned about security by having tokens in the URL. What would be a more secure approach? Is it better to pass tokens via headers or any other recommended method?

  • Combination of URL parameters and body data: Currently, I'm using a combination of URL parameters (serviceId), query parameters (target) and the token from the request body. Is this approach acceptable, or should I modify it to maintain a more consistent approach?

I'd greatly appreciate insights and best practices on how to architect this MVC route for efficient and secure data retrieval.

Thank you!

I tried a couple of approaches, they all work as intended but my concerns are about best practices.

How can I implement this UML Diagram using State Design Pattern

enter image description here I have this UML Diagram and want to use State Design Pattern to implement InProgressState, HelpState and EscapeState. Following is the details:

  1. InProgressState: This is the initial state of the participant, and participants remain in this while they are solving the riddles.
  • Within this state, solveRiddle checks whether the input solves the current riddle.
  1. HelpState: This state is entered when the participant requests help by calling the askForHelp method.
  • In this state, solveRiddle will solve the riddle regardless of the input provided. After that, the participant will be transitioned back to InProgressState if there are remaining riddles to solve, otherwise they will be transitioned to EscapedState.
  1. EscapedState: If a participant successfully solves all riddles, they will be transitioned to the EscapedState.
  • In this state, RiddleException should be thrown if solveRiddle is called.

Note:

  1. If a riddle has been solved but passed as an argument to solveRiddle again, a RiddleException should be thrown.
  2. A participant can choose any riddle to solve at a time. The argument whichRiddle of the solveRiddle method indicates to which riddle he/she submits an input in the riddleList.

I have a Class called ParticipantState:

public interface ParticipantState {
    ParticipantState solveRiddle(String input, Riddle[] riddleList, int whichRiddle) throws RiddleException;
}

And I think InProgressState, HelpState and EscapedState should implements ParticipantState like:

public class InProgressState implements ParticipantState{

    @Override
    public ParticipantState solveRiddle(String input, Riddle[] riddleList, int whichRiddle) throws RiddleException {
        return this;
    }
}

Business validation rules and microservices

We have a microservice architecture, with one of those services being a user service, and another being a calendar service. The problem I am being faced with is this. We have users, and users have products and features. Products are simply bags of features and all of this information is stored in the user service. When selecting a user to display as a potential candidate to place on the calendar, we need to determine if the person being selected has a specific feature turned on. For this, the UI queries the user service and asks for this information and all is well. The trouble in my head comes when we then submit a post request to the calendar service to add the individual to the calendar. How should the calendar service verify that the person who was selected has the specified feature enabled? Should it call directly to the user service and ask, which would introduce coupling but centralize the logic in the service that owns the data? Or should I leverage our service bus and use event carried state transfer to make the user, product, and feature information available to the calendar service? We have several services like this, and it seems like that would be very inefficient for every service to need a copy of the user table and all of their associated products and features, but that seems to be the path of least coupling. Any thoughts or ideas?

lundi 13 novembre 2023

headfirst design pattern, does abstract factory pattern inherently employs factory pattern?

I've read through this article. What are the differences between Abstract Factory and Factory design patterns?

but I still have some uncertainty regarding the Abstract Factory Pattern. My question is whether the Abstract Factory Pattern inherently employs the Factory Design Pattern as a part of its implementation. I'd like to understand if the Abstract Factory Pattern typically incorporates the Factory Pattern for creating its related objects, and if so, how these two patterns are interconnected in practice.

Right architecture for implementing a performance class

I'm creating a library in C++ which has a class with statistical test methods. I also want to write another class that has a set of performance tests over it (like time taken to do a test), but I wonder if I'm doing this the right way, for best performance and reusability.

I have class with the statistical methods (uniformnistanalysis.cpp), a class that is the "test environment" that encapsulates and calls those statistical tests (performance.cpp) with a number n of runs, and checks for the execution time of the function. I want to implement more performance tests but I want first to be sure that the code architecture is fine and hear about other possible arrangements.

Note: performance has an inner class called Timer that counts the execution time of the function for n runs, but as n increases, the average time decreases considerably - and shouldn't, since I'm taking the average of the time of N-runs for the function and then dividing by n. It's going from ~350ns (for n=1) to ~35ns (for n=1000000)

My code structure is:

uniformnistanalysis:

class UniformNISTAnalysis {
    public:
        bool monobit(const DynamicBitset&, double = 0.1);
}

performance.hpp:

class Performance {
public:
    void testMonobit(UniformNISTAnalysis&, const DynamicBitset&, const size_t);
    // more tests will be here...
protected: 
    class Timer {
        public:
            Timer(const std::string&, size_t);
            ~Timer();
        private:
            std::string functionName;
            size_t runs;
            std::chrono::steady_clock::time_point start;
    };
}

parts of performance.cpp:

void TestEnvironment::testMonobit(UniformNISTAnalysis& analysis, const DynamicBitset& bitset, const size_t runs = 1) {
    printTestHeader("Monobit [Mon]");

    bool status;

    // print result
    std::cout << "Number: " << bitset << std::endl;
    std::cout << "Ones: " << bitset.countOnes() << "; Zeroes: " << bitset.countZeroes() << std::endl;
    std::cout << "Ratio of 1s: " << bitset.countOnes() / static_cast<double>(bitset.numBits) << std::endl;

    {
        Timer timer("Monobit", runs);
        for(size_t i = 0; i < runs; i++)
            status = analysis.monobit(bitset);
    }

    printTestStatus("Monobit", status);
}

TestEnvironment::Timer::Timer(const std::string& name, const size_t runs = 1) : functionName(name), runs(runs) {
    start = std::chrono::steady_clock::now();
}

TestEnvironment::Timer::~Timer() {
    auto stop = std::chrono::steady_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(stop - start);
    std::cout << runs << " test(s) '" << functionName << "' took an average of " << duration.count() / static_cast<double>(runs) << "ns to execute." << std::endl;
}

Calling example:

Performance testEnv;
UniformNISTAnalysis analysis;

testEnv.testMonobit(analysis, bitset, 100000);

samedi 11 novembre 2023

Finding the best placement of two black and white images to maximize the similarity

I am looking for an algorithm that would allow me to have the optimal displacement of an image on another (only in 2D x and y, no need for rotation) to find the maximum common pixel (pixel black if on white background and vice versa).

Comparing all the pixels, then redoing the same algorithm by sliding image x+1,y+1 etc. is too time-consuming.. (but works perfectly)

I've thought of comparing 1-2 columns where there's a lot of relief with the image, which would increase speed but doesn't seem optimal.

Also thought of transforming the reliefs into points and then trying to make the best correlation by moving this cloud.

If you have any solutions, I'd love to hear them!

How to implement a Maker Checker in a foreign exchange application

I am currently working on a foreign exchange application whereby a user can make transactions to different countries. For each currency i was able to implement rate limit which means a user cannot transfer more than a daily limit,there’s an admin dashboard where an admin can configure limit for users,but the issue here is that i don’t want an admin to effect a change, admin can only propose a change, then the super admin can accept the proposal. How do i implement this concept.

I use Nextjs for the frontend and Java for the backend

jeudi 9 novembre 2023

Scalable and easy to manage background Processing Java

We have a monolith JAVA application which we are starting to re-write and possibly break down into smaller services. The application has all the REST APIs to power the UI. The application also has a number of background threads that start on application startup.

For example there are three single thread executers that are responsible for doing totally independent set of tasks.

These background jobs mostly are data pipelines. The database access layer is very poorly designed (currently) and are intertwined within the monolith, hence limiting different options.

The major issue we have seen with this setup is that it is non-scalable - Since these background jobs all operate within the main application, we have limited the number of parallel executions, to make sure the main application is not impacted.

For the new application, we will be using Java and Springboot.

[Separate note] We are using airflow for a separate pipeline, however we are trying to get away from it due to operational constraints. So trying to stay away from cloud solutions for now (but suggestions are welcomes)

What are the ways/best practices to design these use cases?

C++ Program Keeps Crashing Without Specific Error [closed]

I am trying to implement an Observer/Subject design pattern between multiple classes. My compiler keeps returning to me the following:

[Done] exited with code=3221225477 in 0.603 seconds.

I assumed this was a success, until I realized nothing worked. I found out (through commenting and uncommenting code) that the crash occurs in 2 places, either when I try to attach an Observer to a child class of Subject, or when I try to call the notify method (which in turn updates the observer). Furthermore, as you will see, the LogObserver default constructor (Child class of Observer), should create and open a file called "gamelog.txt", but fails to do even that. I am not receiving any specific error message, so I dont know why it is crashing or where it is going wrong. Any and all help debugging this?

I'll show the code for the relevant .h and cpp files here, what I expected was for a file to be created, for the observer to be attached to OrderList (child class of Subject), and finally for the text file to be written to upon adding and order to orderlist (which should trigger the Notify method).

Here is the main driver:

#include "LoggingObserver.h"
#include "Orders.h"



void testLoggingObserver(){
    //3 main issues
        //1: File is NOT created upon logObserver default constructor
        //2: The Attach method seems to crash the program
        //3: Keep receiving error for "unidentified reference" to methods 

    //create instances of classes
    LogObserver* logObserver;
    OrdersList * orderList;

    //CRASHES HERE
    //Add the observer to the subjects
    orderList->Attach(logObserver);

    //CRASHES HERE
    orderList->addOrder(new DeployOrder());
}

int main(){
    
    testLoggingObserver();
    cout<<"LogObserver Default Here!"<<endl;
    return 0;
}

Here is the Header for LoggingObserver:

#pragma once
#include <iostream>
#include <vector>
#include <fstream>
#include <set>
#include <algorithm>
#include <list>
#include <iterator>
#include <string>

using namespace std;

//An Interface ILoggable. This interface will be inherited by all classes that can be the subject
//of the logging mechanism
#ifndef I_LOGGABLE_HPP
#define I_LOGGABLE_HPP
class ILoggable{
    public:
        //virtual ~ILoggable();
        //Will create and return a string to be output to the log file
        virtual string stringToLog()=0;
};
#endif

//#ifndef SUBJECT
//#define SUBJECT
class Observer;

//Subject Class will have a list of Observers and methods to add/remove and notify observers
class Subject{
    private:
        //list of Observers
        list<Observer*> *observers;

    public:
        //default contructor and destructor
        //Subject();
        //~Subject();
        
        //Methods to add, remove, and notify Observers
        virtual void Attach(Observer* o)=0;
        virtual void Detach(Observer* o)=0;
        virtual void Notify()=0;

        //friend classes
        friend class GameEngine;
        friend class OrdersList;
        friend class Order;
        friend class Command;
        friend class CommandProcessor;
};
//#endif

//#ifndef OBSERVER
//#define OBSERVER
//Observer Class will have a method to update the state of the observer
class Observer{
    private:

    public:
        //destructor
        ~Observer();
        //method to update state of observer
        virtual void Update(Subject* subject) = 0;
    
    protected:
        //default constructor
        //Observer();
};
//#endif


//#ifndef LOG_OBSERVER
//#define LOG_OBSERVER
class GameEngine;


//This class will override the update method to write the state of the subject to the log file
class LogObserver: public Observer{
    private:
        //file to write to
        ofstream logFile;
        
        //variables attributed to phase
        string playerName;
        string phaseName;
        //GameEngine* subjectGameEngine;

        //variables attributed to game statistics
        int totalContinents;
        bool winnerStatus;
        string conqueredContinent;

    public:
        LogObserver();
        //LogObserver(GameEngine* aSubjectEngine);
        ~LogObserver();
        //update method
        void Update(Subject* subject) override;

        //To display player information and current pahse information
        void logToGameLog(const string& logEntry);

};
//#endif

Here is the .cpp for LoggingObserver:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <list>
#include <algorithm>

#include "LoggingObserver.h"

using std::vector;
using std::list;

//Below we will implement all the abstract functions we declared in the previous LogginObserver.h Header File

//========================================ILoggable Class======================================
//Default constructor



//========================================Subject Class======================================
//Default constructor
/*
Subject::Subject(){
    observers = new list<Observer*>;
}


//destructor
Subject::~Subject(){
    delete observers;
}
*/
/*
//Implementation of Add method (adds an observer to the observers list)
void Subject::Attach(Observer* o){
    observers->push_back(o);
}

//Implementation of Remove method (removes an observer from the observers list)
void Subject::Detach(Observer* o){
    observers->remove(o);
}

//Implementation of the Notify method (will call on the observers update method)
void Subject::Notify(){
    list<Observer*>::iterator i = observers->begin();
    for(;i != observers->end(); ++i){
        //using "this" to pass the subject to the update method
        (*i)->Update(this);
    }
}
*/

//========================================Observer Class======================================
//Default constructor
Observer::~Observer(){
    
}

//========================================LogObserver Class======================================
//Default constructor (will open file)
LogObserver::LogObserver(){
    logFile.open("gamelog.txt", ios::app);
    cout<<"LogObserver Default Here!"<<endl;
}

//Destructor
LogObserver::~LogObserver(){
    logFile.close();
}


//Overriding the update method from Observer (will grab relevant information and update file)
void LogObserver::Update(Subject* subject){
    ILoggable* loggable = dynamic_cast<ILoggable*>(subject);
    if(loggable){
        string logEntry = loggable -> stringToLog();
        logToGameLog(logEntry);
    }
}

//implementing loToGameLog function (will write to file)
void LogObserver::logToGameLog(const string& logEntry){
    logFile << logEntry << endl;
}

Here is the .h for Orders:

#pragma once
#include <vector>
#include <string>
#include <iostream>
#include "LoggingObserver.h"



class Order : public ILoggable
{
    public:

        // default constructor
        Order();

        // constructor with order type
        Order(std::string orderType);

        // copy constructor
        Order(Order &o);

        // Overload the << operator to describe the order
        friend std::ostream & operator << (std::ostream& os, Order& order);

        // checks if an order is valid
        bool validate();

        // executes an order
        void execute();

        bool getIsExecuted();

        void setIsExecuted(bool isExecuted);

        std::string getOrderType();

        void setOrderType(std::string orderType);

        // override the assignment operator
        Order& operator=(Order& o);

        //Overriden stringToLog() method fromILoggable
        string stringToLog() override;


    private:

        std::string orderType;

        bool isExecuted;

};

// specific order classes:
class DeployOrder : public Order 
{
    public:
        // default constructor
        DeployOrder();
};
class AdvanceOrder :public  Order 
{
    public:
        // default constructor
        AdvanceOrder();
};
class BombOrder : public Order 
{
    public:
        // default constructor
        BombOrder();
};
class BlockadeOrder : public Order 
{
    public:
        // default constructor
        BlockadeOrder();
};
class AirliftOrder : public Order 
{
    public:
        // default constructor
        AirliftOrder();
};
class NegotiateOrder : public Order 
{
    public:
        // default constructor
        NegotiateOrder();
};


class OrdersList : public Subject
{

    private:
        std::vector<Order *> orders;

    public:

        // default constructor
        OrdersList();

        // copy constructor
        OrdersList(OrdersList &ol);

        // destructor
        ~OrdersList();

        std::vector<Order *> getOrders();

        Order* createOrder(std::string orderType);

        // add an order to the list
        void addOrder(Order *order);

        // change the position of an order in the order list
        void move(int listPosition1, int targerList);

        // remove an order from the order list
        void remove(int listPosition);

        // prints all the orders in the list
        void printOrdersList();
        
        // Overload the << operator to describe the order list
        friend std::ostream& operator<<(std::ostream& os, OrdersList& ordersList);
        
        // override the assignment operator
        OrdersList& operator=(OrdersList& ol);
        void Attach(Observer* o) override;
        void Detach(Observer* o) override;
        void Notify() override;
};

inline void testOrdersLists()
{
    using namespace std;
    // create an order list and add every type of oder to it
    OrdersList * ol = new OrdersList();
    ol->createOrder("Deploy");
    ol->createOrder("Advance");
    ol->createOrder("Bomb");
    ol->createOrder("Blockade");
    ol->createOrder("Airlift");
    ol->createOrder("Negotiate");

    // print all the elements in the order list
    cout << "\nInitial Order List:\n" << endl;
    cout << *ol;

    // 'execute' an order
    cout << "\n";
    ol->getOrders().front()->execute();

    // remove an order
    cout << "\n";
    ol->remove(2);

    // print all the elements in the new order list
    cout << "\nRemoved Order 2 from list:\n" << endl;
    cout << *ol;

    // move an order
    cout << "\n";
    ol->move(1,2);

    // print all the elements in the new order list
    cout << "\nChanged the first order to be the seconds order:\n" << endl;
    cout << *ol;

}

And here is the .cpp for orders:

#include <iostream>
#include <vector>
#include <string>
#include "Orders.h"
#include "LoggingObserver.h"


// list<Order *> orders = ol->getOrders(); // Make a copy of the list to avoid iterator issues

using namespace std;

// default order constructors:

// generic order
Order::Order(){
    setOrderType("Generic");
    setIsExecuted(false);
}

// order with type
Order::Order(string orderType){
    this->setOrderType(orderType);
    setIsExecuted(false);
}

//Overriden stringToLog() method fromILoggable
string Order::stringToLog() {
    string log = "Observing Issueing Orders Phase information is: \n Orders: " + orderType;
    return log;
}

// deploy order
DeployOrder::DeployOrder()
: Order("Deploy") {}

// advance order
AdvanceOrder::AdvanceOrder()
: Order("Advance") {}

// bomb order
BombOrder::BombOrder()
: Order("Bomb") {}

// blockade order
BlockadeOrder::BlockadeOrder()
: Order("Blockade") {}

// airlift order
AirliftOrder::AirliftOrder()
: Order("Airlift") {}

// negotiate order
NegotiateOrder::NegotiateOrder()
: Order("Negotiate") {}


// copy constructor
Order::Order(Order &o)
{
    setOrderType(o.getOrderType());
}

string Order::getOrderType() { return orderType; }

void Order::setOrderType(string type) { orderType = type; }

bool Order::getIsExecuted() { return isExecuted; } 

void Order::setIsExecuted(bool isExecuted) { this->isExecuted = isExecuted; }


bool Order::validate()
{
    return true;
}

void Order::execute()
{
    if(validate())
    {
        cout << "Executing " << this->orderType << std::endl;
        setIsExecuted(true);
    }
}

// stream operator order
std::ostream & operator << (std::ostream& os, Order & order)
{
    os << "This is a " << order.getOrderType() << " order. ";

    if(order.getIsExecuted())
    {
        os << "Order was executed";
    }
    os << std::endl;

    return os;
}

// assignment operater order
Order& Order::operator=(Order& o)
{ 
    o.setOrderType(getOrderType());
    o.setIsExecuted(getIsExecuted());
    return *this;
} 

// Order list:

// default constructor
OrdersList::OrdersList(){
    cout<<"OrderList Constructer here!"<<endl;
}

// destructor
OrdersList::~OrdersList()
{
    for (Order *order : orders) {
        delete order;
    }
    orders.clear();
}

// copy constructor
OrdersList::OrdersList(OrdersList &ol)
{
    this->orders = ol.getOrders();
}


// stream operator order list
ostream& operator<<(ostream& os, OrdersList & ol)
{
    int i = 0;
    for (Order *order : ol.getOrders()) 
    {
        os << ++i << ": ";
        os << *order ;
    }
    return os;
}

vector<Order *> OrdersList::getOrders()
{
   return this->orders;
}

Order* OrdersList::createOrder(std::string orderType)
{
    Order *newOrder;
    if(orderType == "Deploy")
    {
        newOrder = new DeployOrder();
    }

    else if(orderType == "Advance")
    {
        newOrder = new AdvanceOrder();
    }
    else if(orderType == "Bomb")
    {
        newOrder = new BombOrder();
    }
    else if(orderType == "Blockade")
    {
        newOrder = new BlockadeOrder();
    }
    else if(orderType == "Airlift")
    {
        newOrder = new AirliftOrder();
    }
    else if(orderType == "Negotiate")
    {
        newOrder = new NegotiateOrder();
    }
    else
    {
        newOrder = new Order();
    }
    this->addOrder(newOrder);
    return newOrder;
}

void OrdersList::addOrder(Order *order)
{
    orders.push_back(order);
    Notify();
}

void OrdersList::move(int initialListPosition, int targetListPosition)
{
    // verifiy that the index positions are valid
    int listSize = orders.size();
    if(initialListPosition > listSize || initialListPosition < 1 || targetListPosition > listSize || targetListPosition < 1)
    {
        cout << "Invalid move" << std::endl;
    }
    else
    {
        // remove the order
        vector<Order *>::iterator itr1 = orders.begin();
        advance(itr1,initialListPosition-1);
        Order * o = *itr1; // save a pointer to the order before removing it
        orders.erase(itr1);

        // add it back in the new index
        vector<Order*>::iterator itr2 = orders.begin();
        advance(itr2,targetListPosition-1);
        orders.insert(itr2, o);

        cout << "Order moved" << std::endl;
    }
}


void OrdersList::remove(int listPosition)
{
    
    vector<Order *>::iterator itr = orders.begin();
    advance(itr,listPosition-1);
    orders.erase(itr);

    cout << "Order removed" << std::endl;
}

void OrdersList::printOrdersList()
{
    int i = 0;
    for (Order *order : orders) 
    {
        cout << ++i << ": ";
        cout << *order ;
    }
}

// assignment operater order
OrdersList& OrdersList::operator=(OrdersList& ol)
{ 
    for (Order* order : ol.getOrders()) {
        // Assuming that Order has a copy constructor
        orders.push_back(new Order(*order));
    }
    return *this;
} 

void OrdersList::Attach(Observer* o){
    observers->push_back(o);
    cout << "im attaching"<<endl;
}

//Implementation of Remove method (removes an observer from the observers list)
void OrdersList::Detach(Observer* o){
    observers->remove(o);
}

//Implementation of the Notify method (will call on the observers update method)
void OrdersList::Notify(){
    list<Observer*>::iterator i = observers->begin();
    for(;i != observers->end(); ++i){
        //using "this" to pass the subject to the update method
        cout << "im notifying"<<endl;
        (*i)->Update(this);
    }
}