mercredi 30 juin 2021

Comparing and Quantifying similarity in a set of non linear data

I have 2 lists of data which are basically a batch of SEQUENTIAL data(thus, data cannot be sorted) from a larger database which are as follows

a = [0.8, 0.9, 0.4, -0.4, 1.12, 1.16, 1.08, 1.22]

b = [0.85, 0.96, 0.4, -0.4, 1.15, 1.18, 1.1, 1.92]

The data provided may not be linear in nature and thus typical correlation wont serve the purpose.

I wish to compare a and b (as a line graph) and assign a similarity score to them.

Ive tried implementing linear co-relation from the stats library but the results are not convincing.

Any way to do this using any other statistical function, which emphasizes on the importance of non linear data?

Also, is any supporting function available in scikit learn?

Do “Clean Code”'s function argument number guidelines apply to API design?

I am a newbie reading Uncle Bob's Clean Code Book.

It is indeed great practice to limit the number of function arguments as few as possible. But I still come across so many functions offered in many libraries that require a bunch of arguments. For example, in Python's pandas, there is a function with 9 arguments:

DataFrame.groupby(by=None, axis=0, level=None, as_index=True, sort=True, group_keys=True, squeeze=<object object>, observed=False, dropna=True)

(And this function also violates the advice about flag arguments)

It seems that such cases are much rarer in Python standard libraries, but I still managed to find one with 4 arguments:

re.split(pattern, string, maxsplit=0, flags=0)

I understand that this is just a suggestion instead of silver bullet, but is it applicable when it comes to something mentioned above?

How can Kotlin extension classes replace the decorator design pattern?

Kotlin's documentation makes this statement:

Kotlin provides an ability to extend a class with new functionality without having to inherit from the class or use design patterns such as Decorator.

Kotlin Extensions

I am having trouble understanding how extension functions can completely replace the decorator design pattern.

To borrow an example from TutorialPoint how would you turn the below example into code that only used extension functions? Can you do this without sacrificing the ability to call draw() on both concrete shape objects and decorated shape objects?

interface Shape {
 fun draw();
}

class Rectangle: Shape {
 override fun draw() {
  println("Shape: Rectangle")
 }
}

class Circle: Shape {
 override fun draw() {
  System.out.println("Shape: Circle");
 }
}

abstract class ShapeDecorator(protected val decoratedShape: Shape): Shape {

 override fun draw(){
  decoratedShape.draw();
 }
}

class RedShapeDecorator(decoratedShape:Shape): ShapeDecorator(decoratedShape) {

 override fun draw() {
  decoratedShape.draw();
  setRedBorder(decoratedShape);
 }

 private fun setRedBorder(decoratedShape:Shape){
  System.out.println("Border Color: Red");
 }
}

fun main(){

 val circle: Shape = Circle();

 val redCircle: Shape  = RedShapeDecorator(Circle());

 val redRectangle: Shape = RedShapeDecorator(Rectangle());
  
 
 System.out.println("Circle with normal border");
 circle.draw();

 System.out.println("\nCircle of red border");
 redCircle.draw();

 System.out.println("\nRectangle of red border");
 redRectangle.draw();
}

TutorialPoint Example in Java

Apply a design pattern to solve this problem and not use if/else

I am trying to improve my skills with design patterns, so please be easy on me :) In my university I often have to deal with problems where the algorithm is defined, but data structures it is working on are different.

I have the following problem:

  • If the client is under 18, reduce the base price by 10%.
  • If the city is ‘London’ the price of the product is 1$.
  • If the client has a membership type of ‘gold’ the product is free (£0).

so I tried this:

    if($customer <18) {
    $price = $price-10;
} 

if($city == "London") {
    $price = 1;
}

if($client->membership == "gold") {
    $price = 0;
}

Can someone help me to make it in a nice pattern, like Factory or Strategy? Are they the right one? If not could you tell me which one and give me an example? Many thanks in advance.

Library, “Injecting factory” and best practices for extending a library

I use a library which I need to patch. I need to fork it because Factory design patter is not used.

Library has that structure: class X that hold references to other classes, that hold references to other classes and few more layers. Class hierarchy is “tree-like” structure.

I look for best way for refactoring – flexible enough to prevent people forking it. I cannot find any best practices on that problem.

Over years I use to solve it by “Injecting Factory” – Factory pattern where parent object is being injected (DI) in factory method. I cannot find any documentation on such approach and I need some feedback on it (e.g. theory or possible problems).

I describe it with an example with Car:

  • Car has CarInterior
  • CarInterior has Odometer

Problem – no custom objects could be created, especially Odometer.

class Car {
  CarInterior interior;
  public Car() {
    interior = new CarInterior();
  }
}
class CarInterior {
  Odometer odo;
  public CasInterior(){
    odo = new Odomether();
  }
}
class Odometer {
  public Odometer(){}
}

By-book solution using simple Factory methods pattern only (has a limited extendibility)

class Car {
  CarInterior interior;
  public Car(CarFactory factory) {
    interior = createInterior();
  }
  CarInterior createInterior() { return new CarInterior(); };
}
class CasInterior {
  Odometer odo;
  public CarInterior(){
    odo = createOdometer();
  }
  CarInterior createOdometer() {
    return new Odomether();
  }
}

Major problem with this approach

  • If factory method needs parameters, that change potentially makes troubles to lib users. Because extending classes should change method definitions.

Minor problems

  • if I need to different Odometer, I should extend both Car and CarInterior
  • library I need to fork has few “levels” so this means many levels of extra objects till I manage to call The factory method.

Possible Business requests

Possible extension #1 of Odometer class: with KM or Miles

Car object should have targetCountry. If it is in France, Metric units should be used. If in USA – miles. That business request could be implemented in this way:

  • (breaking change) factory method createOdometer() gets a param: createOdometer(OdoUnits)
  • (breaking change) factory method createInterior() gets a param: createInterior(OdoUnits) or createInterior(Country)
  • in case of more levels (my case), more changes are needed

Possible extension #2 of Odometer class: odometer values range

  • 0-220 km/h
  • 0-300 km/h
  • etc

Possible extension #3 of Odometer class: color of odometer should be same as color of the car

If we use same approach, we should introduce more parameters in methods. And more “proxy” functionality.

The approach to discuss - "Injecting Factory"

  • Factory methods takes an additional parameter – parent object.
  • Odometer gets its Factory, gets Car object and requests all needed data to adapt to the "Car specs"

CODE:

class CarFactory {
  CarInterior createInterior(Car car) { return new CarInterior(car); }
  Odometer createOdometer(CarInterior interior){ return new Odometer(interior); };
}
class Car {
  CarFactory factory;
  CarInterior interior;
  public Car(CarFactory factory) {
    this.factory = factory;
    interior = factory.createInterior(this);
  }
  CarFactory getFactory(){ return factory; };
}
class CarInterior {
  Car car;
  Odometer odo;
  public CarInterior(Car car){
    this.car = car;
    CarFactory factory = car.getFactory();
    odo = factory.createOdometer( this );
  }
}
class Odometer {
  public Odometer(CarInterior interior) {
    Car car = interior.getCar();
    OdoUnits odoUnits = car.getTargetCountry().getUnits();
    int maxEngineSpeed = car.getEngine().getTopSpeed;
    Color color = car.getColor();
    if (!car.isOptionColorOdometer())
      color = DEFAULT_COLOR; 
    // etc
  }
}

Questions

So what are best practices for the issue? What are disadvantages of "Injecting Factory"?

Adding logger in enum is good or bad practice?

I am having the enum like below

@Slf4j
public enum Test {
SUBJECT;

public static Test getValue() {
log.info("performing test")

return SUBJECT;
}
}

Is adding log in enum is good practice or not?

Design pattern - filtered view of a data type that's composed inside another class

I'm working with a data_type but my project requires that the data_type conform to certain specifications so I have a class wrapper that includes a data_type within it.

class wrapper {
private:
    wrapper();
    
public:
    ~wrapper();

    static wrapper * create() {...}

    void member_one(...) {
        // Does stuff to m_ to enforce particular specification
    }

    ...

    void member_ten(...) {
        // Does stuff to m_ to enforce particular specification
    }

protected:
    // Do not expose, since we don't want users to add arbitrary stuff that does not conform to spec
    data_type m_;
};

Now, I am working with a third-party library that provides a view adapter to provide a filtered view of data_type. It takes a data_type and provides a filtered_data_type object.

Keeping in the spirit of my design above, I would like to make a filtered_wrapper that inherits from wrapper. It can have a filtered_data_type as its data member, which is constructed using the base class' data_type.

Problem solved, except that the functions member_one()...member_ten() can act equally on filtered_data_type as they do on data_type, and I want users of filtered_wrapper to be able to do this (a) without having to override all of the functions in filtered_wrapper to do the same thing but on a different data member and (b) while templates are a good solution to this, they expose the data_type and its own templated construction which I am trying to hide from the user, so I want to avoid templates unless there's another template pattern that addresses this.

Is there a design pattern to achieve what I am trying to do?

What is the "Smart UI Anti-Pattern"?

Eric Evans highlighted the concept of "Smart UI Anti-Pattern" in his book "Domain-Driven Design: Tackling Complexity in the Heart of Software" (also called the "blue book").

Could you give me more details about this pattern?

GenericRepository NullReferenceException: Object reference not set to an instance of an object [duplicate]

I have Implemented a Generic Repository Pattern and UnitOfWork but I get a Null Reference Exception.

Here is my DBContext:

public class DBContext : DbContext
{
        public DBContext(DbContextOptions<DBContext> options) : base(options)
    {
       
    }
    public DbSet<User> Users { get; set; }
}

I add DBContext to Startup.cs:

   services.AddDbContext<DBContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionStrings")),
                contextLifetime: ServiceLifetime.Transient,
                optionsLifetime: ServiceLifetime.Singleton);

Here is my Repository Pattern GenericRepository.cs:

  public class GenericRepository<T> where T : class

{
    internal DBContext _context;
    internal DbSet<T> dbSet;

    public GenericRepository(DBContext context)
    {
        this._context = context;
        this.dbSet = _context.Set<T>();
    }
   public IEnumerable<T> GetList()
    {
      return  dbSet.ToList();
    }
    public async Task<IEnumerable<T>> ToListAsync()
    {
        return await dbSet.ToListAsync();
    }
    public virtual T Find(object id)
    {
        return dbSet.Find(id);
    }
  public virtual async Task AddAsync(T entity)
    {
         await dbSet.AddAsync(entity);
    }

Here is my unit of work:

public class UnitOfWork : IDisposable
{
   private readonly DBContext _context;
    public GenericRepository<User> Users
    {
        get
        {

            if (this.user == null)
            {
                this.user = new GenericRepository<User>(_context);
            }
            return user;
        }
    }
    public async Task SaveChangesAsync()
    {
        await _context.SaveChangesAsync();
    }
    public void SaveChanges()
    {
        _context.SaveChanges();
    }
    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!this.disposed)
        {
            if (disposing)
            {
                _context.Dispose();
            }
        }
        this.disposed = true;
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }
}
  

An Exception in in GenericRepository.cs occurred

NullReferenceException: Object reference not set to an instance of an object.

this.dbSet = _context.Set<T>();

Flutter gradient rainbow outline and blur

I'm revisiting the flutter and want to build my small test application. I'm opting for dark mode with nice gradient contrasts.

Would like to ask how I could achieve the rainbow outline with outside blur effect in Flutter. Apple M1 logo has a great example of what I look for. Anyone could suggest how this can be done ??

enter image description here

Interval Based Batch Processor For Fire And Forget Commands On Redis

I'm building a trade engine for cryptocurrency and since the trade engine is going to get consumed by a lot of commands in multiple markets, I was wondering instead of using a default pattern like issuing a threat for each command there can be a DataBase that saves commands for short periods of time and executes them in a batch. I was wondering if it's a good idea and is there a pattern or delivery mechanism I can use for my database?

mardi 29 juin 2021

why couldn't model communicate with view throuth interface in MVC

In classic MVC pattern, the model communicate with view throuth event notify.

But it seems that by defining some basic interfaces of view, and model communicating with view throuth interfaces is also feasible and could still decouple the model and concrete view.

However, I've never heard about any MV* pattern use interface between view and model , is there any obstacles by communicating in such way?

Can the thread of an object be copied using prototype pattern?

I use the State Pattern to design the OrdinaryUserState class and DisableState for the User class. When a user becomes disabled, I start a timer "new timer (). Schedule ({...});", the user become normal after 24 hours. When I close the program, I save the user to the ".data" file. When I restart the program, I read out the user from the ".data" file. However, I find that the user is always disabled and cannot be changed even after 24 hours. The timer works when I don't close the program.

public class User implements Serializable {
private AbstractState state;
private String name;
private String password;
private Password generator;
private Unique uniguepassword;

public boolean isVIP() {
    return isVIP;
}

public Unique getUniguepassword() {
    return uniguepassword;
}

public void setUniguepassword(Unique uniguepassword) {
    this.uniguepassword = uniguepassword;
}

public void setVIP(boolean VIP) {
    isVIP = VIP;
}

private boolean isVIP;
public User(String name,String password){
    this.name=name;
    this.password=password;
    this.state=new OrdinaryUserState(this); //init
    this.generator=new Password();
    this.uniguepassword=new UniquePassword();
}
 public void generate(int chance){
    state.generatePassword(chance);
 }
 public void registerVIP(){
    state.registerVIP();
 }
 public void restore(){
    state.restore();
 }
public AbstractState getState() {
    return state;
}

public void setState(AbstractState state) {
    this.state = state;
}

public String getName() {
    return name;
}

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

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public Password getGenerator() {
    return generator;
}

public void setGenerator(Password generator) {
    this.generator = generator;
}

}

public abstract  class AbstractState implements Serializable {
protected User user;
protected int chances;
protected  String stateName;
protected Date date;
public abstract void  checkState(int chances);
public void generatePassword(int chance) {
        this.chances -= chance;
        checkState(chances);
}
public void restore(){
    this.chances=5;  //become normal
    checkState(chances);
}
public void  registerVIP(){
    user.setVIP(true);
    this.chances=10000;
    checkState(chances);
}
public int getChances() {
    return chances;
}

public void setChances(int chances) {
    this.chances = chances;
}

public String getStateName() {
    return stateName;
}

public void setStateName(String stateName) {
    this.stateName = stateName;
}

}

public class OrdinaryUserState extends AbstractState implements Serializable {

public OrdinaryUserState(User user){
    this.chances=5;
    this.user=user;
    this.stateName="OrdinaryUser";
}
public OrdinaryUserState(AbstractState state) {
    this.user=state.user;
    this.chances=state.chances;
    this.stateName="OrdinaryUser";
}
@Override
public void checkState(int chances) {
    if(chances==0){
        user.setState(new DisableState(this));
    }
    if(chances>5){
        user.setState(new VIPUserState(this));
    }
}

}

public class DisableState extends AbstractState implements Serializable {
public DisableState(AbstractState state) {
    this.user=state.user;
    this.chances=state.chances;
    this.stateName="disabled";
    //this.date=new Date();
    //System.out.println(this.date.getTime());
    refresh();
}
public void refresh(){
    new Timer().schedule(new TimerTask() {
        @Override
        public void run() {
            restore();
        }
    },24*60*60*1000,24*60*60*1000);

}

@Override
public void checkState(int chances) {
    if(chances==5){
        user.setState(new OrdinaryUserState(this));
    }
    if(chances>5){
        user.setState(new VIPUserState(this));
    }
}

}

public class saveUser {   //save the user
public saveUser(){};
public void save(User user) throws IOException, ClassNotFoundException {
    String path = "D:/aaa/.data";
    FileOutputStream fileOutputStream;
    ObjectOutputStream objectOutputStream;
    File file = new File(path);
    if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
    }
    if (file.exists()) {
        file.delete();
    }
    file.createNewFile();

    fileOutputStream = new FileOutputStream(file.toString());
    objectOutputStream = new ObjectOutputStream(fileOutputStream);
    objectOutputStream.writeObject(user);
    objectOutputStream.close();
    fileOutputStream.close();
}

public User copy() throws IOException, ClassNotFoundException {
    String path = "D:/aaa/.data";
    User user;
    FileOutputStream fileOutputStream;
    ObjectOutputStream objectOutputStream;
    File file = new File(path);
    if (!file.getParentFile().exists()) {
        file.getParentFile().mkdirs();
    }
    if (file.exists()) {
        FileInputStream fileInputStream;
        ObjectInputStream objectInputStream;
        fileInputStream = new FileInputStream(file.toString());
        objectInputStream = new ObjectInputStream(fileInputStream);
        user = (User) objectInputStream.readObject();
        objectInputStream.close();
        fileInputStream.close();
        return user;
    } else {
        return null;
    }
}

}

How to change loop direction

I have 3x3 stars cube, but I make it can print continue as we want from our input, BUT it's loop Will go down, not go right, how to change to loop to the right

import java.util.scanner;

Public class program {
    Public static void main(String [] args) {
        Scanner getInp;
        int a;
        
        getInp = new Scanner(System.in);
        a = getInp.nextInt();

        for (int x=0; x<a; x++) {
            for (int y=0; y<3; y++) {
                for (int z=0; z<3; z++) {
                    System.out.print("* ");
                }
                System.out.println("\n");  
            }
        }
    }
}

Mediator Design Pattern: is this a correct implementation?

I'm learning and try to practice design patterns, I was trying to implement the mediator pattern based on this explanation, The code works as I wanted to do it, but as I changed a few things and implemented methods and classes inside the concrete class, I don't know if the pattern is correctly implemented, can you please comment on this.

<?php 

namespace DesignPatternsPractice\Mediator;

interface Mediator 
{
    public function notify(object $sender, string $event);
}

class ConcreteMediator implements Mediator {
    private $component;

    public function __construct($component) {
        $this->component = $component;
        $this->component->setMediator($this);
        $this->family = new Family();
        $this->family->setMediator($this);
    }

    public function notify($sender, $event) {
        if($sender instanceof Kidnapper && $event === "called_family") {
            echo "The family suspected a kidnapping, didn't responded the call and called a mediator \n";
            $this->family->callMediator();
        } else if($sender instanceof Kidnapper && $event === "called_mediator") {
            $this->callFamily();
        }

        if ($sender instanceof Family && $event === "called_mediator") {
            echo "Mediator is ready to respond the new call from the kidnapper\n";
        }

        if($sender instanceof ConcreteMediator && $event === "called_police") {
            echo "The police does not negotiates with kidnappers and the victim was rescued \n";
        }
    }

    public function callFamily() {
        echo "The family responded no to the demands and tell the mediator to call the police \n";
        $this->callPolice();
    }

    public function callPolice() {
        $this->notify($this, "called_police");
    }
}

class BaseComponent {
    protected $mediator;

    public function __construct(Mediator $mediator = null)
    {
        $this->mediator = $mediator;
    }

    public function setMediator(Mediator $mediator): void
    {
        $this->mediator = $mediator;
    }
}

class Kidnapper extends BaseComponent {
    
    public function callFamily() {
        $this->mediator->notify($this, "called_family");
    }

    public function callMediator() {
        echo "Mediator asked for demands\n";
        $this->mediator->notify($this, "called_mediator");
    }
}

class Family extends BaseComponent {    
    public function callMediator() {
        $this->mediator->notify($this, "called_mediator");
    }
}

$kn = new Kidnapper();
$mediator = new ConcreteMediator($kn);
$kn->callFamily();
$kn->callMediator();

Using repository pattern inside microservice

I have a long discussion with my colleague about using repository design pattern inside microservice, my suggestion is to create a single repository for the microservice as I deal with it as a single bounded context and all of its tables should be handled through one repository but colleague suggest to have repository per each table, so please kindly advice what is the best option to follow.

Design pattern for dynamically generating a request object based on user selection

I'm working on an application for data processing where users need to be able to select operations to perform on the data when it is being retrieved. This will be done using a data flow language, and it will need to be generated by taking the parameters the user has given. This system needs to be extensible, so that more operations can be added in the future without too much added complexity.

A possible design pattern I’ve looked into was using the Decorator pattern and decorating a base query with different decorators that consist of reusable operations. However I’m not sure how to handle and validate the execution order when using the decorator pattern. Is the Decorator pattern a good fit or are there different design patterns that would be a better fit for this problem.

Need help in architecture on coding platform website like hackerrank, leetcode, etc

We trying to create a coding platform website like hackerrank, leetcode, etc but need some suggestion on architecture about compiling multiple langauges like c#, Python, java, etc

current architecuture: Client website--> Queue--> FunctionApp--> Docker (unsure this part)

Undefined reference of Composer class for Strategy pattern, C++ [duplicate]

I have the book "Design Patterns, Elements of Reusable Object-Oriented Software", and I've been using the internet. I've boiled down my code to bare minimum.

I don't know why I get the error messages:

Error    undefined reference to `InputStrategy::InputStrategy()'

I can post more of the error, but it was just the recipe for target failed, and the subsequent undefined reference being passed in to Input(new BinaryInputStrategy());

Does anyone see why this isn't working?

#include <avr/io.h>

class InputStrategy {
    protected:
        InputStrategy();
};

class Input {
    public:
        Input(InputStrategy* is) {
            inputStrategy = is;
        }
    private:
        InputStrategy *inputStrategy;
};

class BinaryInputStrategy : public InputStrategy {
    public:
        BinaryInputStrategy() {}
};

int main(void) { 
    Input ins = Input(new BinaryInputStrategy());
    while (1) {}
}

What is a smart and/or pythonic approach to writing functions with constraints on function arguments?

Suppose I wanted to write a Python function in which the arguments to this function should only ever be used with e.g. lists of equal length.

Let's imagine a python-like pseudocode implementation which might look like:

 def somefunc(arg1: list, arg2: list) -> list, where len(arg1) == len(arg2): 

What is the pythonic approach to writing a function, where passing arguments which do not satisfy such constraints would result in a (run-time) error.

Database design issues due to concurrency in multi-node architecture

I will try my best to go through the issue. Please let me know if there needs any clarity.

The problem is faced for an application in a distributed environment where multiple nodes (running on AWS) have a single persistent data store. In that datastore, we have 3 tables like,

instance_info (id, instance_details, ...)   -> legacy table
task_info (id, task_id, ...)    -> legacy table
new_table (id, instance_info_id, task_info_id, ...)

"id" in all the tables are the PKs of their respective tables. In new_table the column "task_info_id" is a foreign key to table task_info, and "instance_info_id" is to table instance_info.
On new_table, a unique constraint exists for columns instance_info_id & task_info_id, while the other tables don't consist of any unique constraint. The situation is that there could be multiple tasks running concurrently (on a single node) that try to insert data in the task_info table, leading to having multiple entries in the table (due to the absence of unique constraints).

Thought of the following bad approaches,

  1. add unique constraints to task_info table so that it fails on IntegrityConstrainViolation. However, this approach ruins an existing functionality for retrying mechanism (legacy code).
  2. Lock the whole table during write operation preventing other writes to fail. However, this could end up creating performance issues for us.

There is a distributed cache (Memcache) but seems to be in doubt as there could be a downtime, leading to data loss.
Is there any efficient design approach (with minimal/no changes in the legacy code/design) that can be looked into?

How to perform another DB query in the same transaction in case of unique constraint violation in Java Spring @Transactional method?

I am struggling with handling exceptions during transactional methods with Spring @Transactional annotations. Currently, when my Dao insert method throws a unique contraint violation, I want to perform a read instead to get the existing item. However, this fails because the UniqueIdViolation causes the transaction to fail. How can I refactor this to work as intended whilst not doing a dodgy boolean return on the insert?

I have a DAO with an insert method, e.g.:

public class ItemDao {
  
  public void insertItem(Item item) {
    // insert into db via jooq
  }

  public Item fetch(String id) {
    // fetch from db
  }
  ...
}

If it violates a unique constraint I have an aspect that handles the DataAccessException and rethrows it as a UniqueIdException.

I have a service method that takes in some information and creates an Item, before returning that item.

If the dao throws a UniqueIdException, I want the service to catch this error and then call itemDao.find() to get the existing Item and return it.

public class MyServiceImpl implements MyService {
  
  @Transactional(isolation = SERIALIZABLE)
  public Item createItem(...) {
    Item item = new Item(...);
    try {
      itemDao.insert(item);
      return item;
    } catch (UniqueIdException ex) {
      return itemDao.find(item.getId());
    }
  }
}

The issue here is when itemDao.insert(item) throws an exception this causes the transaction to fail and therefore itemDao.find() doesn't run.

Generate a table that meet conditions

I would like for an activity to generate a table that meet certain conditions as know as:

  • There are 16 groups
  • There are 8 activities
  • Every group need to do every activity
  • Each activity must accommodate 2 group and no more
  • We would like a group to never meet the same group again (so the people can see the maximum amount of other people :-) )

We tried to manually generate this in Excel but there are always some groups that see each other again.

We tried to manually "generate a list" but we always end we teams crossing each other, like team 7 and team 9 cross 3 time in this exemple : table generated so far

I though maybe a thre dimensional array could do , but it seems like an overkill to me and there is certainly some known way to handle those situations.

Simplify .net core web api design complexity

This is a design related problem.

I have a legacy application in asp.net webforms which have 3 kind of users: Admin, Customer and Provider, which access multiple services like Product, Account, Sale, Purchase etc. All these 3 users share same set of class libraries for services, logic and database until now. And the deployment is single for all 3 users.

Now we are migrating this into .net core web api + angular. And I am thinking about the options. Till now I have figured out this is the best for our application:

  1. Create separate web api for Admin, Customer and Provider. Then for any changes in Admin, the deployment will not impact Customer. But the problem with this approach is the class libraries will be duplicated. Some common methods will be duplicated.

Is there any alternative/good approach for this?

How to define RAII buffer class with custom memory manager?

The question below can be a general question about design patterns but, due to my lack of knowledge, I couldn't.

I am trying to implement a RAII-style buffer class (Buffer) using a given memory manager class (MemoryManager) with interfaces like open_manager/close_manager/allocate/deallocate etc. The Buffer would look like:

class Buffer {
public:
  explicit Buffer(std::size_t sz) { /* Allocation */ }
  ~Buffer() { /* Deallocation */ }
};

But as a condition, the MemoryManager class needs to be instantiated, which means that the Buffer needs to be able to use the specific manager instance in the destructor.

  ~Buffer() { manager.dealloc(/* ... */); }

There would be several options:

  • const MemoryManager* as a Buffer member variable like:
    class Buffer {
    public:
      Buffer(std::size_t sz, const MemoryManager* manager) : manager_(manager) { /*...*/ }
      ~Buffer() { manager_->dealloc(/*...*/); }
    private:
      const MemoryMenager* manager_{nullptr};
    };
    
  • const MemoryManager& as a Buffer member variable
  • The manager as a global variable

Which options are the best ? or are there any better ways to get this done ?

Thank you.

lundi 28 juin 2021

do you guys know how to turn on the light at the the top left of the squares? [closed]

here's the video of it https://1drv.ms/v/s!AuNT_JgXUNfdjRlICHnAqKOxQG-2. the start point is at the top left of the squares. I've been tried to code lightOn(); at the beginning of my code, but it didn't change. Then I tried to code it to turn and go up to return to the start point and light it up, but seems like something block the way to the start point.

Dependency Injection, IoC and Stateful Objects

Every time I have a stateful object with class properties, I resort to using a factory for that class to be used in the dependent class as such:

class Foo
{
    Dependency1 d1;
    Dependency2 d2;
    IdProcessorFactory idProcessorFactory;
    public Foo(Dependency1 d1, Dependency2 d2, IdProcessorFactory idProcessorFactory)
    {
        this.d1 = d1;
        this.d2 = d2;
        this.idProcessorFactory = idProcessorFactory;
    }


    private void DoSomething(List<int> ids)
    {
        foreach(var id in ids)
        {
            var idProcessor = idProcessorFactory.GetInstance();
            idProcessor.Process(id);
        }
    }
}

I wonder if this is the right approach. Because, since stateful objects are encouraged in an object oriented language, then one has to write a factory for each dependency if multiple instances are to be used in the dependent class. Is this the way to go or is there a better alternative?

(Please note that I am aware of the service locator pattern which is discouraged.)

Spring Boot Best approach for validation in facade

I use Spring Boot with Kotlin and my project is splitted on modules where I have application layer with REST controllers and facades, domain layer with services and business logic and infrastructures layer for communication with external services or DBs. I think (but I can be wrong) that the best place for basic validation like notNull, notEmpty, max and min, size etc. is facade because both REST controllers and another modules communicate with it, but the problem is that javax validation annotation like @Valid are working only on REST Controller layer (in classes with annotation @RestController) and when I try to create some tests for this facade then fields with wrong values return NullPointerException instead of MethodArgumentNotValidException. I tried to create WebMvcTest but also returns wrong exception. Is it some solution for it? I saw that I could call some validator inside the method but it looks like much more complex approach than annotation on method's argument.

How to design a Java fluent DSL API without static methods

There are several ways how to define a Java fluent API:

  • Use static classes/methods + an internal ThreadLocal to get the DSL instance
  • Use setter/getter based methods to chain the API. Personally I don't like the readability of it, e.g. see some Spring Security code examples.

Is there a way to create a Java DSL that is more readable, like fluent methods in Kotlin? For exmaple a Computer class with Attributes like cpu/gpu and nested DSL classes like drives (Note: I want to nest ssd and hdd even further, e.g. define partitions?

public class Main {

    public static void main(String[] arguments) {
        Computer computer = Computer.build("Gaming PC").cpu("AMD 5950X").gpu("Lol rly?");
        computer.drives(() {
            ssd("1TB", "m2");
            hdd("10TB", "SATA");
        });
        computer.print();
    }

    public static class Computer {

        private final Map<String, String> attributes;

        private Computer() {
            this.attributes = new LinkedHashMap<>();
        }

        public static Computer build(String name) {
            Computer computer = new Computer();
            computer.attributes.put("name", name);
            return computer;
        }

        public Computer cpu(String modelName) {
            attributes.put("cpu", modelName);
            return this;
        }

        public Computer gpu(String modelName) {
            attributes.put("gpu", modelName);
            return this;
        }

        // TODO: Add ssd and hdd. How?

        public void print() {
            for (Map.Entry<String, String> entry : attributes.entrySet()) {
                System.out.println(entry.getKey() + " = " + entry.getValue());
            }
        }
    }
}

The example above won't compile. But is there a way to achieve it with regular classes/abstract classes or even interfaces [with default methods?]. Like this:

public class Main {

    public static void main(String[] arguments) {
        Computer computer = Computer.build("Gaming PC").cpu("AMD 5950X").gpu("Lol rly?");
        computer.drives((new DriveManager() {
            ssd("1TB", "m2");
            hdd("10TB", "SATA");
        });
        computer.print();
    }

    public static class DriveManager {

        private Computer computer;

        public void setComputer(Computer computer) {
            this.computer = computer;
        }

        public void ssd(String size, String interfaceType) {
            computer.ssd(size, interfaceType);
        }

        public void hdd(String size, String interfaceType) {
            computer.ssd(size, interfaceType);
        }
    }
}

But how does one call setComputer?

one producer with long running several consumers with blocking Queue

I have to create message sending application witch send SMS to our customers. since generating and sending messages to customers takes considerable time, I have decided to implement it with producer and consumer pattern. So, this will not affect the original flow of execution.

ones I put raw data to the queue as a object, this will picked by one of consumer threads in thread pool and then generate message and send SMS. this flow should continue once application is up and running.

My application works fine. but I found that each thread that consumer and producer thread pool creates stay alive in waiting state even after it finished the send SMS task. is it a problem for long running application or can I use the the consumer and producer thread pool for all the time instead of creating new thread pool each time when initializingSendMessage(RawData trxn) method invoked?

MessageSendUtil class is used to create common queue and initialize the taks.

public class SendMessageUtil {
    public static void initializingSendMessage(RawData trxn) {

        BlockingQueue<Message> sharedQueue = new LinkedBlockingQueue<>();
        ExecutorService produceMessagePool = Executors.newFixedThreadPool(1);
        ExecutorService consumerMessagePool = Executors.newFixedThreadPool(5);
        try {
            produceMessagePool.submit(new Producer(sharedQueue));
            int i = 0;
            while (i++<MESSAGE_CONSUME_POOL_SIZE) {
                consumerMessagePool.submit(new Consumer(sharedQueue));
            }
            produceMessagePool.shutdown();
            consumerMessagePool.shutdown();
            
        } catch (Exception ex){
            System.out.println(ex.getMessage());
        }
    }

my consumer and producer class looks like this.

public class Producer implements Runnable {
    private final BlockingQueue<Message> sharedQueue;
    public Producer(BlockingQueue<Message> sharedQueue) {
        this.sharedQueue = sharedQueue;
    }
    @Override
    public void run() {
        List<Message> messageList = new ArrayList<>();
        for(int i = 0;i<100000;i++) {
            Message message = new Message();
            message.setMessage("Test message sending");
            messageList.add(message);
        }
        sharedQueue.addAll(messageList);
    }
}

/

public class Consumer implements Runnable {
    private final BlockingQueue<Message> sharedQueue;
    private MessageBroadcaster messageBroadcaster;
    public Consumer(BlockingQueue<Message> sharedQueue) {
        this.sharedQueue = sharedQueue;
    }
    @Override
    public void run() {
        initializeMessageBroadcaster();

        //Send messages to costumer
        while(true){
            try {
                Message message = sharedQueue.take();
                messageBroadcaster.sendMessage(message);
            } catch (Exception err) {
                err.printStackTrace();
            }
        }
    }

    private void initializeMessageBroadcaster() {
        if(Objects.isNull(messageBroadcaster)){
            messageBroadcaster = new MessageBroadcasterImpl();
        }
    }
}

after several time of invoking initializingSendMessage(RawData trxn), live threads show like this. live thread count

What is the formula that is used by three.js to create the pattern that is seen when two overlapping 2-D surfaces are shown in SageMath?

I'm trying to understand the pattern (looks similar to an animal print) that shows when two different colored planes are plotted on (almost) the same plane. What is the formula that SageMath uses--using three.js--to create the pattern shown in the graph? The SageMath question/support area sent me to this support section for answers.

Example: Here one plane is slightly larger-- which makes SageMath show them both, but with a pattern. Also, as you move/manipulate the graph with the mouse, the pattern changes. What formula or information does SageMath (three.js) use to show the pattern?

I used the Sage Cell Server online to plot this (below) at https://sagecell.sagemath.org/:

sage: M = implicit_plot3d(lambda x,y,z: x, (-15,15), (-15,15), (-15,15), rgbcolor= (0.0, 1.0, 0.0), frame=true) sage: N = implicit_plot3d(lambda x,y,z: x, (-15,15), (-15,15), (-15,15.5), rgbcolor= (0.0, 0.0, 1.0), frame=true) sage: M+N

Thanks for any information you can provide!

How to get coroutine scope in lower level manager class

I have a data manager class in one of my libraries. Until now it was working with executors and had its own executor. Now the class is being converted to coroutines.

The problem arises when the manager has to initialize the data asynchronously as in below example. In order to execute suspend function, the call to suspendedInit has to be wrapped in launch. The issue here is that the manager has no its own coroutine scope.

There are some that I am looking at and don't like:

  1. passing coroutine scope into DataManager constructor and using it. The issue with that the the user of DataManager does not yet support coroutines and hence has no own scope.
  2. DataManager implementing CoroutineScope and creating its own scope. This is discouraged as documented by CoroutineScope documentation.

What is the recommended solution to this problem?

    class DataManager {
        init {
            suspendedInit()
        }
        
        private suspend fun suspendedInit() = withContext(Dispatchers.IO) {
            /* some long asynchronous operations here */
        }
    }

Simplifying Control Flow

I am using flags to control the flow of my program. The program is a stateful module which is repeatedly called. Flags represent its internal state. The state has multiple dimensions like initialized actionAlreadyChosen rewardAlreadyGiven explorationFinished ... each of which is valid for one object in a set of many. I.e. those states are also to be taken per object managed by my module.

I can't change the architecture of the caller nor any other behaviour from outside. That's the justification for this bookkeeping with internal states.

Now I got annoyed about the complexity of the control-flow logic, as those flags are read inside functions which are called from other functions, completely hiding the control flow inside flags and function calls. To follow the flow-logic, it is necessary to step inside every function and check how the conditional statements evaluate the flags and where the code executes after.

Is there any good pattern adressing such cases ? Is there some good concept to avoid this complexity ?

I intentionally ask that in general as this should be a problem occuring in multiple domains.

Which design pattern I should use in this case

I have a class (let's call it BugFinderCommand) which will be responsible for finding bugs (in ex. missing schedule payment) in loan schedules.

The scenario would look like this: The cron will run BugFinderCommand and it will iterate all the schedules. If a bug is found, it would return a message, in ex. "Missing 5th schedule payment" and I would store these messages in array and then in excel file.

Currently, we know just two bugs, but we are SURE that in future we will find more of them.

I was wondering, which design pattern would fit best and it would be easy to extend with new bugs? Would be cool if each bug check logic would stay in new class.

I am using php (Symfony) if that helps.

How to design API for reports

Hi and thanks in advance for ideas.

I have an api endpoint to design which is a report of tickets. The report itself needs to accept up to 8-10 parameters like start / end date or start / end product group. The report then is fairly simple ( Van number, product, quantity ) group by van & product The API endpoint should represent a resource ( so it would be tickets ) however that would force the API consumer ( a webpage in this scenario ) to calculate the total quantity on frontend.

So I wonder what is the correct pattern here? Is creating an endpoint for such report wrong way of doing it? Should I create /tickets/vanloading?startDate=2021-06-28&endDate=.........

What is general approach for different kind of reports when implementing API when there is plenty of data to aggregate ?

Thank you.

dimanche 27 juin 2021

python to organize code to be more modular and generic

I have this loop that builds string out of some parameters, I like to make it more modular in case other parameters are added Currently cant find better idea from what i have now :

my_list = []
separator = "|"
for dd in data_:

    function_that_handle(dd)

    my_list.append(f"'\$}.myapp{separator}{self.container.app_type}'")
    my_list.append(f"'\$}.ip{separator}{self.container..server_ip}'")
    my_list.append(f"'\$}.port{separator}{self.container..server_port}'")
    my_list.append(f"'\$}.name{separator}{db_properties.get('user_name')}'")
    my_list.append(f"'\$}.pass{separator}{self.container.org_password}'")
    my_list.append(f"'\$}.version{separator}{self.container.org_version}'")
    my_list.append(f"'\$}.uuid{separator}{self.container.app_uuid}'")
              

all_config=f"[{','.join(map(str, my_list))}]

The problem is that more parameters can be added so the list can be long. Any idea to make it more organized?

Does strategy always needs to be passed from the client code in Strategy Pattern?

I have below piece of code:

public interface SearchAlgo { public Items search(); }

public class FirstSearchAlgo implements SearchAlgo { public Items search() {...} }

public class SecondSearchAlgo implements SearchAlgo { public Items search() {...} }

I also have a factory to create instances of above concrete classes based on client's input. Below SearchAlgoFactory code is just for the context.

public class SearchAlgoFactory {
   ...

   public SearchAlgo getSearchInstance(String arg) {
      if (arg == "First") return new FirstSearchAlgo();
      if (arg == "Second") return new SecondSearchAlgo();
   }

}

Now, I have a class that takes input from client, get the Algo from Factory and executes it.

public class Manager{
 
   public Items execute(String arg) {
      
        SearchAlgo algo = SearchAlgoFactory.getSearchInstance(arg);
        return algo.search();
   }

}

Question:

I feel that I am using both Factory and Strategy pattern but I am not sure 'cause whatever examples I have seen they all have a Context class to execute the strategy and client provides the strategy which they want to use. So, is this a correct implementation of Strategy?

Anyone Know What İs Event Centered Architecture Pattren

Please Provide Any İnformation related to i Search on Google İ don't Get Any thing

questions about strategy pattern

the definition of the context in the strategy pattern is: 1-is configured with a ConcreteStrategy object 2-maintains a reference to a Strategy object 3-may define an interface that lets Strategy access its data. "may define an interface that lets strategy access its data" can someone explain that to me, and in the definition of the strategy pattern "let the algorithm vary from the class using it" what does that mean too and in pros of this pattern "You can replace inheritance with composition" what does mean and thank you!

samedi 26 juin 2021

Can an object be a Participant in both the Mediator and Observer Design pattern?

Can an object behave like an Observer (subscriber) with one set of objects (Observer Design Pattern) while at the same time act as a Colleague with another set of objects in the Mediator design pattern?

ZERO DownTime Deployment of application with frequent database DDL change

Hi I am trying to deploy my application with zero downtime. My app is quite frequent with database ddl changes. What are all the possible ways to achieve it with zero transaction failure in the app. Though we can use kubernetes to achieve zero downtime of the application, I don't want any failures in service request happening at the time of deployment due to database change like dropping the columns, dropping the table and changing the datatype

TechStack

Kubernetes - Deployment Spring boot Java -app Oracle -database

Why does the class have a dashed line once and a normal line once?

I have a task which requires me to draw a UML diagram based on the description. I have received the solution (see the photo). However, I can't figure out the solution and have a few questions why the solution is the way it is. I have described these below.

Description:

The contract of a prepaid cell phone should be modelled and implemented. A basic contract has a contract number (of type int) and a balance (of type double), but no monthly charges. The contract number is not automatically generated, but is to be set as a parameter by the constructor as well as the initial balance. The balance has a getter and a setter. The following options can be added to a contract (if needed also several times):

  • 100 MB of data (monthly charge 1.00 €)
  • 50 SMS (monthly charge 0.50 €)
  • 50 minutes (monthly charge 1.50 €)
  • Double Transfer Rate (monthly charge 2.00 €) Implement this this requirement with the help of the decorator pattern. All contract elements should be able to understand the methods getCharges():double, getBalance():double and setBalance (double).

The method getCharges() should provide the monthly charge of a contract with all its options selected. The methods getBalance() and setBalance(…) should be passed through and access the basic contract.

Exercise:

  • Draw an UML-Diagram with all the classes / interfaces and their relationships, fields and methods (no constructors needed).
  • Also provide a client class which holds a contract.

Solution:

Solution

Question:

  • Why does Option once have a dashed line and a normal line to Contract?
  • Why are the Minutes not listed as a class like Data and SMS?
  • Why does Phone and DoubleTransfer have no connection to the other classes?

Use "config.xml" file to Load the Adapter

I want to use the adapter pattern for my project and my teacher said that use "config.xml" to load adapters. I don't know what does he mean. what should I do? If anyone has a good reference to read I appreciate that.

how can i use Strategy Pattern in this java code context

the main class Client in a package client and we have three anther classes in anther package NewsCollection ,image and Artikel

the important class is NewsCollection

hier ist ein klassen Diagramm

vendredi 25 juin 2021

How to notify other screen on like button click android

Let's say I'm working on a social media app like facebook. We can see post on feed page and by clicking the any post that post is visible in a post view screen. If I press like button on the post view screen and go back, I can see in the feed, like has been updated. How to achieve this, let's say my same post is present at various places I want to update respective post everywhere when like is clicked anywhere in that post. I want to implement like button, I'm thinking of observer pattern but I'm little bit confused when it comes to implementation. Can anyone share some reference? How you guys are doing it?

Write a java program to find the pattern: [closed]

Write a program to print the following pattern up to given no. of rows (R) given by user.

if R=5, output will be

1 2 3 4 5 * 5 4 3 2 1
1 2 3 4 # # # 4 3 2 1
1 2 3 * * * * * 3 2 1
1 2 # # # # # # # 2 1
1 * * * * * * * * * 1   

All core business logic is written in PLSQL

I am offered to work on a project in which almost 80% of business logic is written in PostgresQL PLSQL stored procedures. Creating objects, deleting, updating variable objects and more. Including some strange pseudo-RPC for the exchange between services around, built on PostgresQL messages pg_notify ().

In my opinion, this is more than a strange decision, given that SQL DBMS were created for other purposes. But I would like to see a competent opinion about such an architecture. Please write as is, without limiting yourself in expressions. =)

Thanks!

jeudi 24 juin 2021

Python Implementation of Multi-Dimensional Document Undo/Redo Pattern

I would consider my experience level in Python intermediate, and I am developing a logo creator/editor using Pillow. The objective of the program is to eventually create and save an Image. I would like to implement the ability to undo/redo editing actions. I am also interested in the ability to undo/redo individual layers globally.

I approached the design similar to Photoshop/Pixelmator, using multiple instances of Layer and one Logo. Through my research, I came across the Memento Design Pattern, and have attempted to adapt a similar design pattern (using a list as storage, which can hold a current state). According to my program, a Layer holds a PIL Image, and these Layers are held in a List within the Logo class. So when saving the Logo, the program starts with the background layer and progressively "stacks", or pastes the next Layer's Image on top of the last. I then My reasoning is that a Layer will allow me to keep editing history tied to the lifecycle of a Layer (i.e. when said layer is removed/deleted from the List, its "history" shall be removed from memory).

I have created a class DocumentRollback and an interface DocumentRollbackInterface. Both Layer and Logo utilize both of these classes to store history.

import abc

class DocumentRollback:

    def __init__(self, data):
        self.current = data
        self.index = 0
        self.history = [data]

    def save(self, data):
        self.current = data
        self.index += 1
        self.history.insert(self.index, data)

    def undo(self):
        if self.index > 0:
            self.current = self.history[self.index - 1]
            self.index -= 1

    def redo(self):
        if self.index + 1 < len(self.history):
            self.current = self.history[self.index + 1]
            self.index += 1

    def get_current(self):
        return self.current


class DocumentRollbackInterface:

    @abc.abstractmethod
    def undo(self):
        """
        Undo changes
        """

    @abc.abstractmethod
    def redo(self):
        """
        Redo changes
        """

    @abc.abstractmethod
    def destructure_to_dict(self):
        """
        Turn data to dict
        """

    @abc.abstractmethod
    def restructure_from_dict(self, data):
        """
        Turn dict to data
        """

When I create an instance of Layer or the Logo, I instantiate DocumentRollback (this will allow me to track the current state of said object), and inherit DocumentRollbackInterface (to make sure that methods are written to undo, redo, save, and restore data from the object's DocumentRollback).


class Logo(DocumentRollbackInterface, ABC):

    def __init__(self, background, name="Logo"):
        # background = Layer(name="background")
        """
        Create a new Logo. Must pass the background

        :param background:
        :type background Layer
        """
        background.rename_layer("background")
        self.layers = [background]
        self.image = background.canvas
        self.dimensions = background.dimensions
        self.name = name
        payload = {
            "layers": self.layers,
            "image": self.image,
            "dimensions": self.dimensions,
            "name": self.name
        }
        self.document_rollback = DocumentRollback(payload)

    def undo(self):
        self.document_rollback.undo()
        prev_state = self.document_rollback.get_current()
        self.restructure_from_dict(prev_state)

    def redo(self):
        self.document_rollback.redo()
        next_state = self.document_rollback.get_current()
        self.restructure_from_dict(next_state)

    def destructure_to_dict(self):
        return {
            "layers": self.layers,
            "image": self.image,
            "dimensions": self.dimensions,
            "name": self.name
        }

    def restructure_from_dict(self, data):
        self.layers = data['layers']
        self.image = data['image']
        self.dimensions = data['dimensions']
        self.name = data['name']

    # Continuation of Logo



class Layer(DocumentRollbackInterface, ABC):

    dimensions = (1024, 1024)
    transparent_color = Color(0, 0, 0, 0)

    def __init__(self, name, dimensions=dimensions, background_color=transparent_color):
        """
        Initializes a new Layer

        :param name: Name of Layer
        :type name str
        :param dimensions: Dimensions of new layer (width, height)
        :type dimensions tuple[int, int]
        :param background_color: Color of Background
        :type background_color Color
        """
        img = Image.new(mode="RGBA", size=dimensions, color=background_color.to_tuple())
        self.center = (int(dimensions[0] / 2), int(dimensions[1] / 2))
        self.canvas = img
        self.name = name
        self.dimensions = dimensions
        self.background_color = background_color
        payload = {
            "center": self.center,
            "canvas": self.canvas,
            "name": self.name,
            "dimensions": self.dimensions,
            "background_color": self.background_color
        }
        self.document_rollback = DocumentRollback(payload)

    def undo(self):
        self.document_rollback.undo()
        prev_state = self.document_rollback.get_current()
        self.restructure_from_dict(prev_state)

    def redo(self):
        self.document_rollback.redo()
        next_state = self.document_rollback.get_current()
        self.restructure_from_dict(next_state)
        
    def destructure_to_dict(self):
        return {
            "center": self.center,
            "canvas": self.canvas,
            "name": self.name,
            "dimensions": self.dimensions,
            "background_color": self.background_color
        }

    def restructure_from_dict(self, data):
        self.center = data['center']
        self.canvas = data['canvas']
        self.name = data['name']
        self.dimensions = data['dimensions']
        self.background_color = data['background_color']

    # Continuation of Layer

I have drawn a diagram of the main problem. enter image description here

Because I am using a list to store the history of state changes for each object, when the Logo is edited, the entire histories of all Layers stored in the DocumentRollback of the Logo are appended to the list. Presumably, the amount of memory required can grow exponentially (as indicated by the red highlighted Layers in the above diagram).

Ideally, I believe it would be wise to store a reference to the current state of each Layer inside the DocumentRollback of the Logo. I have a hunch that a LinkedList might work best because it allows for the direct forward and back pointers for undo and redo, but I am unsure if storing the current Node creates a reference to the Node, or an entirely new LinkedList gets constructed (similar to the case of the entire list that I currently have).

So the two main questions I have are:

  • What is the best way to reference the current state of the Layer and Logo that implements document history?
  • Is there a way to implement a "global index", or storage system that will allow different Layers to have actions undone/redone from the Logo? For example, in Photoshop, a user can start with a background image, then add another Layer and edit that, but is there a way to globally rollback the edits to each Layer from the "editor" (Logo in this case)?

Thank you so much! Any help is greatly appreciated!

Why use service container instead of new class

In what scenario should we use a service container instead of calling a new class directly? I read from Laravel official docs that it is mainly used for managing class dependency and performing dependency injection, however I am not sure if I understand it correctly.

For example payroll applications, we would have a Payroll class, Employee Class, Leave Class, Timesheet Class. So to process a monthly payroll, Payroll class would depends on

  • Employee Class (getBasicSalary)
  • Leave Class (getUnpaidLeaveCount)
  • Timesheet Class (getLateHoursCount)

Below is what I normally writes (without any design pattern)

Class PayrollProcessController 
{
    public function index(){
         $payrollObj = new Payroll();
         $payroll->setPayrollMonth('202106');
         $payroll->process();
    }
}

Class Payroll 
{
    private $payrollMonth;

    public function process()
    {
        // loop employee from database
        foreach ($employees as $employee_id){
             $salary = $this->calculateNetSalary($employee_id); 
             // save into db
        }
    }

    public function calculateNetSalary($employee_id)
    {
         $employee = Employee::find($employee_id);
         $basicSalary = $employee->getBasicSalary();
         $basicSalaryPerDay = $basicSalary / date('t');         
         $basicSalaryPerHour = $basicSalaryPerDay / 8;
         $leaveTakenDay = Leave::getUnpaidLeaveCount( $employee->getId(), $this->payrollMonth);
         $leaveDeductionAmount = $basicSalaryPerDay * $leaveTakenDay;
         $timesheetLateHours = Timesheet::getLateHoursCount($employee->getId(), $this->payrollMonth);
         $lateDeductionAmount = $basicSalaryPerHour * $timesheetLateHours;
         $netSalary = $basicSalary - $leaveDeductionAmount - $lateDeductionAmount;
         return $netSalary;
    }
}

If apply with service container concept,

Class PayrollProcessController 
{
    public function index(Payroll $payroll){  
          $payroll->setPayrollMonth('202106');        
          $payroll->process();
    }
}

Class Payroll 
{
    public function process()
    {
        // loop employee from database
        foreach ($employees as $employee_id){

            $employee = app(Employee::class);
            $employee = $employee->find($employee_id);
            $leave = app(Leave::class);
            $timesheet = app(Timesheet::class);

            $salary = $this->calculateNetSalary($employee, $leave, $timesheet); 
             // save into db
        }
    }

    public function calculateNetSalary(Employee $employee, Leave $leave, Timesheet $timesheet)
    {
         $basicSalary = $employee->getBasicSalary();
         $basicSalaryPerDay = $basicSalary / date('t');         
         $basicSalaryPerHour = $basicSalaryPerDay / 8;
         $leaveTakenDay = $leave->getUnpaidLeaveCount( $employee->getId(), $this->payrollMonth);
         $leaveDeductionAmount = $basicSalaryPerDay * $leaveTakenDay;
         $timesheetLateHours = $timesheet->getLateHoursCount($employee->getId(), $this->payrollMonth);
         $lateDeductionAmount = $basicSalaryPerHour * $timesheetLateHours;
         $netSalary = $basicSalary - $leaveDeductionAmount - $lateDeductionAmount;
         return $netSalary;
    }
}

Questions:

  1. Is the above concept correct?

  2. I checked again on the service container documentation https://laravel.com/docs/8.x/container#when-to-use-the-container, it is written:

    First, if you write a class that implements an interface and you wish to type-hint that interface on a route or class constructor, you must tell the container how to resolve that interface. Secondly, if you are writing a Laravel package that you plan to share with other Laravel developers, you may need to bind your package's services into the container.

    So can I say that unless we are publishing the payroll modules as a laravel package for others to use or to write unit testing, there is no point in using a service container?

  3. If we look at opencart's registry class, is that is similar to Laravel's service container? https://github.com/opencart/opencart/blob/e22ddfb060752cd8134abbfb104202172ab45c86/upload/system/framework.php#L9

  4. Take an example from opencart, so Language class is singleton design pattern, while registry is container design pattern?

    $language = new \Opencart\System\Library\Language($config->get('language_code'));
    $language->addPath(DIR_LANGUAGE);
    $language->load($config->get('language_code'));
    $registry->set('language', $language);
    

mercredi 23 juin 2021

How does one implement soft wrapping of long lines in editor?

I'm in a need of implementing soft (visual) breaking of long lines in my ad-hoc text editor. I'm having problems with deciding upon:

  • How should (and if it should) the information about (visual-only-) break points of each long line be stored?
  • How should (and if…) the information about cursor position within the logical long line be stored?
  • When scrolling, from where to get information that first line on screen is actually eg. a 2nd part of a long line already partially scrolled outside the viewport?

Basically I'm looking for something possibly close to a design pattern and/or someone's experienced advice.

The current buffer structure is as follows:

typedef struct 
{
    off_t curs1;                /* pos. of the cursor from beginning of file. */
    off_t curs2;                /* pos. from end of file */
    GPtrArray *b1;              /* all data up to curs1 */
    GPtrArray *b2;              /* all data from end of file down to curs2 */
} edit_buf_t;

The pointer arrays hold hunks of 65535 bytes, so, for example, in order to get a byte before curs1, one could:

/* Size of the buffer in bits and max value */
#define EDIT_BF_SZ_BITS 16
#define EDIT_BF_SZ (((off_t) 1) << EDIT_BF_SZ_BITS)

/* Buffer size mask of all bits set */
#define EDIT_BF_SZ_MASK (EDIT_BF_SZ - 1)

b = g_ptr_array_index (buf->b1, byte_index >> EDIT_BF_SZ_BITS);
return (char *) b + (byte_index & EDIT_BF_SZ_MASK);

How to dynamically create an object for an abstract class without casting?

I have a abstract class in JAVA and few subclasses. I have a function that returns an instance of one of these subclasses. I don't want to check with few if...else to create an object based on the return type. need to do it dynamically at run time. this solution didn't help me
The ReplaceExpression is an overloaded function that return different subclasses.

 // Expression is abstract class, A and B is subclass\
 // this return me null because i did not make a new object for e1, I know a subclass of Expression
       
   

Expression e1 = ReplaceExpression(1);
Expression e2 = ReplaceExpression("a");

    
    public Expression ReplaceExpression(int i)
    {
    Return new A();
    }
    
    public Expression ReplaceExpression(String s)
    {
    Return new B();
    }

I can do it like this but i need cleaner solution:

if (ReplaceExpression(x).getClass().getSimpleName() == "A")
Expression e1 = new A();

So my question is: is there anyway I can instantiate a new subclass for my abstract class without hardcoding or casting? something like dynamically or reflection

Event sourcing and microservices, messaging system

We are designing our new system which will be written most likely from scratch, as the old one is really really old. It's really important for our system to keep audit trail logs of everything that happened in the system.

Due to the audit trail importance we decided to follow the event sourcing architecture for all of its benefits. Another key factor is that we have multiple teams who work on different "domains". Saying that, we would like to split each domain into it's own service (microservices architecture) so every team can work independently.

The biggest question that we have is who's going to be responsible for the event sharing between the microservices. For example, an event that happened in one of the services, should trigger another event in 2 other services as well. We can see 2 options:

  • A central streaming service (AWS Kinesis most likely) with all services registering a publisher and a subscriber. Every service will publish all its events there and the consumers will decide if they "care" about the specific event and then do something or not.
  • Multiple categorised streams (AWS Kinesis most likely) with specific service publishers and subscribers that really need to do something with the events that are published.

We've spent a lot of hours already trying to figure out what is the best option for us or what questions we should ask ourselves to take the right decision. I'm leaning more to the first option although i do have some concerns regarding performance and bottleneck for the consumers, since every service will listen to all events and then they will decide if they have to act on it or not.

Do you see any no-goes in the first option or the second one? Are we looking in the right direction or should we take a step back?

An image that describes a bit what we need to achieve (except CQRS) in a short scale is this one events which is taken from here

C++ self-registering factory, multi parameters constructors

I read this article about C++ factory class with a self registering capability of the concrete classes. Really like it, expecially the demangled name solution used as a key for the registered classes.

There is one main issue I would like to solve: how can we modify the factory to be able to support concrete classes with different constructor parameters?

// Dog and Cat both derive from Animal, but have different constructor parameters
class Dog : public Animal::Registrar<Dog> {
public:
  Dog(int param1, std::string param2) : m_x(param1) {}

  void makeNoise() { std::cerr << "Dog: " << m_x << "\n"; }

private:
  int m_x;
};

class Cat : public Animal::Registrar<Cat> {
public:
  Cat(bool param1) : m_flag(param1) {}

  void makeNoise() { std::cerr << "Cat: " << m_x << "\n"; }

private:
  bool m_flag;
};

I was thinking that maybe the parameter pack of template <class Base, class... Args> class Factory should be moved to the template <class T> struct Registrar, but I can't found a proper solution.

Full original code below

#include <iostream>
#include <memory>
#include <string>
#include <unordered_map>

#include <cstdlib>
#include <cxxabi.h>

std::string demangle(const char *name) {

  int status = -4; // some arbitrary value to eliminate the compiler warning

  std::unique_ptr<char, void (*)(void *)> res{
      abi::__cxa_demangle(name, NULL, NULL, &status), std::free};

  return (status == 0) ? res.get() : name;
}

template <class Base, class... Args> class Factory {
public:

  template <class ... T>
  static std::unique_ptr<Base> make(const std::string &s, T&&... args) {
      return data().at(s)(std::forward<T>(args)...);
  }

  template <class T> struct Registrar : Base {
    friend T;

    static bool registerT() {
      const auto name = demangle(typeid(T).name());
      Factory::data()[name] = [](Args... args) -> std::unique_ptr<Base> {
        return std::make_unique<T>(std::forward<Args>(args)...);
      };
      return true;
    }
    static bool registered;

  private:
    Registrar() : Base(Key{}) { (void)registered; }
  };

  friend Base;

private:
  class Key {
    Key(){};
    template <class T> friend struct Registrar;
  };
  using FuncType = std::unique_ptr<Base> (*)(Args...);
  Factory() = default;

  static auto &data() {
    static std::unordered_map<std::string, FuncType> s;
    return s;
  }
};

template <class Base, class... Args>
template <class T>
bool Factory<Base, Args...>::Registrar<T>::registered =
    Factory<Base, Args...>::Registrar<T>::registerT();

struct Animal : Factory<Animal, int> {
  Animal(Key) {}
  virtual void makeNoise() = 0;
};

class Dog : public Animal::Registrar<Dog> {
public:
  Dog(int x) : m_x(x) {}

  void makeNoise() { std::cerr << "Dog: " << m_x << "\n"; }

private:
  int m_x;
};

class Cat : public Animal::Registrar<Cat> {
public:
  Cat(int x) : m_x(x) {}

  void makeNoise() { std::cerr << "Cat: " << m_x << "\n"; }

private:
  int m_x;
};

// Won't compile because of the private CRTP constructor
// class Spider : public Animal::Registrar<Cat> {
// public:
//     Spider(int x) : m_x(x) {}

//     void makeNoise() { std::cerr << "Spider: " << m_x << "\n"; }

// private:
//     int m_x;
// };

// Won't compile because of the pass key idiom
// class Zob : public Animal {
// public:
//     Zob(int x) : Animal({}), m_x(x) {}

//      void makeNoise() { std::cerr << "Zob: " << m_x << "\n"; }
//     std::unique_ptr<Animal> clone() const { return
//     std::make_unique<Zob>(*this); }

// private:
//      int m_x;

// };

// An example that shows that rvalues are handled correctly, and
// that this all works with move only types

struct Creature : Factory<Creature, std::unique_ptr<int>> {
    Creature(Key) {}
    virtual void makeNoise() = 0;
};

class Ghost : public Creature::Registrar<Ghost> {
public:
    Ghost(std::unique_ptr<int>&& x) : m_x(*x) {}

    void makeNoise() { std::cerr << "Ghost: " << m_x << "\n"; }

private:
    int m_x;
};

int main() {
  auto x = Animal::make("Dog", 3);
  auto y = Animal::make("Cat", 2);
  x->makeNoise();
  y->makeNoise();
  auto z = Creature::make("Ghost", std::make_unique<int>(4));
  z->makeNoise();
  return 0;
}

I want to know the algorithm for solving this pattern problem? I am using python language for it [closed]

Given a positive integer 'n' less than or equal to 26, you are required to print the below pattern

Sample Input: 5

Sample Output :

--------e-------- 
------e-d-e------ 
----e-d-c-d-e---- 
--e-d-c-b-c-d-e-- 
e-d-c-b-a-b-c-d-e 
--e-d-c-b-c-d-e-- 
----e-d-c-d-e---- 
------e-d-e------ 
--------e-------- 

Sample Input : 3

Sample Output :

----c---- 
--c-b-c-- 
c-b-a-b-c 
--c-b-c-- 
----c----

select columns with patterns in data.table

I have a data table with many columns like real_0_h, real_1_h, real_2_h and so on. Unfortunately, I have other columns named for instance real_dose.

my code looks like that (data.table package): melt(dt, id.vars = c("id", "dose"), measure.vars = patterns("^real_")).

Like that, obviously real_dose will be selected as well, but I want to refer to real_0_h:real_24_h only (dplyr syntax). How is it done?

What to do in "cyclic import" situation using DDD and Go?

I'm learning DDD and Golang.

I have a big doubt.

I'm building an app for tennis players and I have structured files like this:

pkg/reservation
  /app
    /query
      /get_reservation.go
    /command
      /create_reservation.go
    /app.go
  /domain
    /reservation
      /repository.go
      /reservation.go
  /adapters
    /postgres
      /repository.go
      /reservation.go
  /ports
    /http
      /reservation.go
      /service.go

pkg/game
  /app
    /query
      /get_game.go
    /command
      /create_game.go
    /app.go
  /domain
    /game
      /game.go
      /repository.go
  /adapters
    /postgres
      /game.go
      /repository.go
  /ports
    /http
      /game.go
      /service.go

pkg/player/... is the same

with /pkg/reservation/domain/reservation/reservation.go:

import (
  "pkg/game/domain/game"
  "pkg/game/domain/player"
)

type Reservation struct {
  id int

  start time.Time
  end time.Time

  game *game.Game
  player *player.Player
}

and /pkg/game/domain/game/game.go:

import (
  "pkg/reservation/domain/reservation"
  "pkg/game/domain/player"
)

type Game struct {
  id int

  finalScore string

  reservation *reservation.Reservation
  players []player.Player
}

At least for the moment this application is a simple CRUD and perhaps this structure is excessive. But soon the application will grow and I would like to be ready.

As you can see there is a cyclic import:

reservation.go imports pkg/game/domain/game and game.go imports pkg/reservation/domain/reservation.

The big doubt is how to fix this cyclic import.

As read here I can:

  • duplicate Game and Reservation structs: but I don't like this very much because they are perfectly the same, but maybe I'm wrong here;

  • use everywhere IDs only: but this is not a fix, because sometimes I really need *Reservation in my Game struct.

What do you recommend?

This is a very common situation I think.

Design chess LLD

Design chess and implement functionality where if a player does not make a move in one minute, the player will lose it's turn and the next player is not supposed to make a move.

Can someone please help with the implementation of the above functionality? I can design the chess game similar to what is mentioned here : https://www.geeksforgeeks.org/design-a-chess-game/

But I cannot not come up with a good way to implement the above functionality. Any help/suggestions will be helpful

How to call a method at runtime based on a string value using springboot/ any java design?

Consider below example, I want to call appropriate produce method based on vehicle, where vehicle can be "car" or "bike" or "van"

Class Company {

public void manufacture(String vehicle) {

   //How to call appropriate **produce** method based on string(vehicle) passed as param in this method **without using if or switch condition here**?

}

}


Class AutoMob {

public void produce(Car c, ....){

}

public void produce(Bike b, ....){

}

public void produce(Van l, ....){

}

}

I dont want to use reflection or condition here and looking for design based approach or any idea using springboot?

Thanks in advance!!

mardi 22 juin 2021

is there a good design pattern for this classes relation in Python?

So imagine I have a class A, and class B can take class A as its member and use class A's functionality to do the job, like this

 class B:
    def __init__(self, A):
        self.A = A

    def do_something(self):
        # some other jobs ....
        self.A.do_the_job()

This is a straightforward design. However, in my case, class A can be accessed and modified outside of B as well, then this design is a little strange because although A is a member class of B, actually A could be changing its status outside of B. Therefore I change it to this design

 class B:
    def __init__(self):
        pass

    def do_something(self, A):
        # some other jobs ....
        A.do_the_job()

It is definitely perfectly fine, the only ugly thing is, right now everytime when I call B.do_something, I need to pass class A as its argument. Actually class B has several other functions that will use class A as well.

I wonder if there is any better design pattern to deal with this kind of situation?

How to refactor two similar methods and create correct readeable methods?

I have two similar methods in my controller:

First method:

public function parseDataLayerEvent()
{
    $events = $this->pixel_log->data['dataLayer'];

    if (!is_array($events)) {
        throw new \Exception('dataLayer is not an array');
    }
    foreach ($events as $event) {
        if (!isset($event['event'])) {
            continue;
        }
        if (!isset($event['ecommerce'])) {
            continue;
        }
        if (!isset($event['ecommerce']['purchase'])) {
            continue;
        }
        $purchase = $event['ecommerce']['purchase'];

        $validator = Validator::make($purchase, [
            'products.*.id' => 'required|string',
            'products.*.name' => 'required|string',
            'products.*.price' => 'required|numeric',
            'products.*.variant' => 'nullable|string',
            'products.*.category' => 'nullable|string',
            'products.*.quantity' => 'nullable|numeric|min:1',
            'actionField.id' => 'required|string',
            'actionField.action' => 'nullable|string|in:purchase',
            'actionField.revenue' => 'required|numeric',
        ]);

        if ($validator->fails()) {
            logger()->debug('Order validation failure');
            throw new ValidationException($validator);
        }

        $order_id = $purchase['actionField']['id'];
        $order = Order::query()
            ->where('pp_id', '=', $this->pixel_log->pp_id)
            ->where('order_id', '=', $order_id)
            ->first();

        if (!$order) {
            logger()->debug('Order №' . $order_id . ' does not exist, creating...');
            $order = new Order();
            $order->pp_id = $this->pixel_log->pp_id;
            $order->order_id = $order_id;
            $order->status = 'new';
        } else {
            logger()->debug('Order №' . $order_id . ' exist, updating');
        }
        $order->pixel_id = $this->pixel_log->id;
        $order->datetime = $this->pixel_log->created_at;
        $order->partner_id = $this->link->partner_id;
        $order->link_id = $this->link->id;
        $order->click_id = $this->pixel_log->data['click_id'] ?? null;
        $order->web_id = $this->pixel_log->data['utm_term'] ?? null;
        $order->offer_id = $this->link->offer_id;
        $order->client_id = $this->client->id;
        $order->gross_amount = 0;
        foreach ($purchase['products'] as $product_data) {
            $order->gross_amount += $product_data['price'] * ($product_data['quantity'] ?? 1);
        }
        
        $total_products = count($purchase['products']);
        $order->cnt_products = $total_products;
        $order->save();

        logger()->debug('Products found: ' . $total_products);
        foreach ($purchase['products'] as $product_data) {
            $product_id = $product_data['id'];
            $product = OrdersProduct::query()
                    ->where('pp_id', '=', $this->pixel_log->pp_id)
                    ->where('order_id', '=', $order->order_id)
                    ->where('product_id', '=', $product_id)
                    ->first() ?? new OrdersProduct();

            // if ($product->wasRecentlyCreated === false) {
            //     if (!is_null($product->reestr_id)) {
            //         return;
            //     }
            //     if ($product->status !== 'new') {
            //         return;
            //     }
            // }

            $product->pp_id = $this->pixel_log->pp_id;
            $product->order_id = $order->order_id;
            $product->parent_id = Order::query()
                ->where('pp_id', '=', $this->pixel_log->pp_id)
                ->where('order_id', '=', $order_id)
                ->first()->id;
            $product->datetime = $order->datetime;
            $product->partner_id = $order->partner_id;
            $product->offer_id = $order->offer_id;
            $product->link_id = $order->link_id;
            $product->product_id = $product_id;
            $product->product_name = trim(($product_data['name'] ?? '') . ' ' . ($product_data['variant'] ?? ''));
            $product->category = $product_data['category'] ?? null;
            $product->price = $product_data['price'];
            $product->quantity = $product_data['quantity'] ?? 1;
            $product->total = $product->price * $product->quantity;
            $product->web_id = $order->web_id;
            $product->click_id = $order->click_id;
            $product->pixel_id = $order->pixel_id;
            $product->amount = 0;
            $product->amount_advert = 0;
            $product->fee_advert = 0;
            $product->save();
            logger()->debug('Saved product: ' . $product->product_name);
        }
        $this->pixel_log->is_order = true;
        return true;
    }
}

Second method:

public function parseCheckoutDataLayerEvent()
{
    $events = $this->pixel_log->data['dataLayer'];

    if (!is_array($events)) {
        throw new \Exception('dataLayer is not an array');
    }
    foreach ($events as $event) {
        if (!isset($event['event'])) {
            continue;
        }
        if (!isset($event['ecommerce'])) {
            continue;
        }
        if (!isset($event['ecommerce']['checkout'])) {
            continue;
        }

        $purchase = $event['ecommerce']['checkout'];
        $validator = Validator::make($purchase, [
            'products.*.id' => 'required|string',
            'products.*.name' => 'required|string',
            'products.*.price' => 'required|numeric',
            'products.*.variant' => 'nullable|string',
            'products.*.category' => 'nullable|string',
            'products.*.quantity' => 'nullable|numeric|min:1',
        ]);

        if ($validator->fails()) {
            logger()->debug('Ошибка валидации заказа');
            throw new ValidationException($validator);
        }

        $order_id = $this->pixel_log->data['ed']['order_id'];
        $order = Order::query()
            ->where('pp_id', '=', $this->pixel_log->pp_id)
            ->where('order_id', '=', $order_id)
            ->first();

        if (!$order) {
            logger()->debug('Order №' . $order_id . ' does not exist, creating...');
            $order = new Order();
            $order->pp_id = $this->pixel_log->pp_id;
            $order->order_id = $order_id;
            $order->status = 'new';
        } else {
            logger()->debug('Order №' . $order_id . ' exist, updating');
        }
        $order->pixel_id = $this->pixel_log->id;
        $order->datetime = $this->pixel_log->created_at;
        $order->partner_id = $this->link->partner_id;
        $order->link_id = $this->link->id;
        $order->click_id = $this->pixel_log->data['click_id'] ?? null;
        $order->web_id = $this->pixel_log->data['utm_term'] ?? null;
        $order->offer_id = $this->link->offer_id;
        $order->client_id = $this->client->id;
        $order->gross_amount = 0;
        foreach ($purchase['products'] as $product_data) {
            $order->gross_amount += $product_data['price'] * ($product_data['quantity'] ?? 1);
        }
        // $order->gross_amount = $purchase['actionField']['revenue'] - ($purchase['actionField']['shipping'] ?? 0);
        $order->cnt_products = count($purchase['products']);
        $order->save();

        logger()->debug('Products found: ' . count($purchase['products']));
        foreach ($purchase['products'] as $product_data) {
            $product_id = $product_data['id'];
            $product = OrdersProduct::query()
                    ->where('pp_id', '=', $this->pixel_log->pp_id)
                    ->where('order_id', '=', $order->order_id)
                    ->where('product_id', '=', $product_id)
                    ->first() ?? new OrdersProduct();

            // if ($product->wasRecentlyCreated === false) {
            //     if (!is_null($product->reestr_id)) {
            //         return;
            //     }
            //     if ($product->status !== 'new') {
            //         return;
            //     }
            // }

            $product->pp_id = $this->pixel_log->pp_id;
            $product->order_id = $order->order_id;
            $product->datetime = $order->datetime;
            $product->partner_id = $order->partner_id;
            $product->offer_id = $order->offer_id;
            $product->link_id = $order->link_id;
            $product->product_id = $product_id;
            $product->product_name = trim(($product_data['name'] ?? '') . ' ' . ($product_data['variant'] ?? ''));
            $product->category = $product_data['category'] ?? null;
            $product->price = $product_data['price'];
            $product->quantity = $product_data['quantity'] ?? 1;
            $product->total = $product->price * $product->quantity;
            $product->web_id = $order->web_id;
            $product->click_id = $order->click_id;
            $product->pixel_id = $order->pixel_id;
            $product->amount = 0;
            $product->amount_advert = 0;
            $product->fee_advert = 0;
            $product->save();
            logger()->debug('Saved product: ' . $product->product_name);
        }
        $this->pixel_log->is_order = true;
        return true;
    }
}

As you see, I have approximately similar methods in terms of logic and operations. How can I rewrite these methods in the correct way using design patterns KISS, DRY ?

function.constructor vs function.prototype.constructor

I've ready quite a bit of blog post and stackoverflow questions but can't get good understanding regarding this.

Why is it necessary to set the prototype constructor?

Trying to understand the difference between prototype and constructor in JavaScript

Constructors in JavaScript objects

JavaScript inheritance and the constructor property

Understanding the difference between Object.create() and new SomeFunction()

Question:

function person(fname) {
  this.fname = fname;
}

let obj1 = new person('first'); //works well
console.log(obj1);
let obj2 = new person.prototype.constructor('second'); //works well
console.log(obj2);
//now the query
console.log(person.constructor); //1. it prints  function Function() { [native code] } what does it mean
let obj3 = new person.constructor('third') // 2. why this doesn't work ?
console.log(obj3); //

now as we know that a every function in javascript has a property call prototype which is an object which has a property called constructor which points back to the function on which prototype object is a property. - correct me if I'm wrong with this

so according to above statement person.prototype.constructor === person (both are the same)

Query: 1 person.constructor prints function Function() { [native code] } what does it means, please explain in detail.

Query: 2 why this new person.constructor('randon') doesn't work ?

Query: 3 what exactly is person.constructor and how it's different from person.prototype.constructor ?

Is it a better pattern to derive a class or just add to a method to existing class?

This question is specifically related to python but I guess it could be valid for any OO language. I have defined a Query class that imports the pyodbc package and groups in a single class some of its functionality, allowing to simplify the execution of queries against a database (for example, I have a run() method that executes the query and retrieves the resulting data).
pyodbc just allows positional parameter binding (binding each '?' in the source query with the corresponding element of a list of parameters) but I'd also like to have named parameter binding (binding each '@variable' in the source query with the corresponding value for a dict element having @variable as key). So, I need to transform a named parameter query into a positional parameter query and do some rework in the input parameterse. My question is related to the most correct way to achieve this. Is it better to:

  1. Define a new method of the class Query, say run_parsed(), that expects a query with the named parameter notation (@variable), and call that method when you need to run a query that way, or
  2. Define a derived class from Query (say Query_named), and use that class just when you want to run a named parameter query, and the base Query class when you want to run a positional parameter query?

Thanks for your insights

Should i use Mediator Design Pattern instead of Dependency Injection?

I am currently learning about MediatoR Pattern, And i feel like it is an alternative - or another solution for the same problem -, And i couldn't figure out when to use it instead of dependency injection.

So any one may clarify that?

How to resolve recursive dependency C#

I have a problem with two interfaces calling each other.
In my model each Component can contain a Grid. And each Grid can contain a Component.
I am trying implement mapper for this model with Dependency Injection.

public interface IComponent
{
    //if we found a grid in the content, we should call Map method from IGrid 
    ComponentViewModel Map(IContent content);
}

public interface IGrid
{
    //if we found a component in the content, we should call Map method from IComponent 
    GridViewModel Map(IContent content);
}

But now I have an error "Recursive dependency detected"
I fixed it when I changed it to static classes, but I think it is dirty hack.

I also tried to use factory for creating an instance for these interfaces in the both methods.
        var container = Current.Factory.Concrete as ServiceContainer;
        var mapper = container.GetInstance<IComponent>();

But it doesn't work too, because each instance of the interface expects an instance of another to come to its constructor.

What pattern should I implement to keep DI in my project?