mardi 30 juin 2020

which design pattern should be used for alternating turn purpose?

For a simple board game, saying that there are two players and there is a turn() method to alternate turns, which design pattern is appropriate to be used for this condition?

Design patterns for board game

I am currently trying to implement a really simple board game (have not decided what board game to make) using some design patterns.

Am I on the right track?

Adding players: when adding players, in order to satisfy the open-closed principle, strategy pattern is appropriate to be used

Moving players forwards or backward on the board depending on the situation: command pattern is appropriate to be used for moving players by having execute() method

Rolling a dice: have no idea for it...

I am really new to design patterns, can someone please tell me if I am on the right track or not?

Thanks in advance!

How to get pagedlist size in android when using paging library with mvvm

please, I'm using android MVVM with retrofit and with paging library and the problem is I can't get size of pagedlist. pagedlist = 0 in UI always.

and the below code that the way how I get the list size.

 private void getAllAds() {
        userHomeViewModel.getHomeAllAdsPagedList().observe(this, new Observer<PagedList<AllAdsModel>>() {
            @Override
            public void onChanged(PagedList<AllAdsModel> list) {
                allAdsModelPagedList = list;
                Toast.makeText(AllAdsActivity.this, ""+list.size(), Toast.LENGTH_SHORT).show();
                //list.size = 0!!!!
                initUserAllAds();
            }
        });
    }

How to refactor class with too many dependencies

I have a class with 20 dependencies injected in the constructor. The class implements an interface with one method called handle. Unfortunately, the implementation of that handle method uses ALOT of method chaining, so any variables that need to be shared between methods need to become private properties of the class, which contributes even more to the mess detection. The dependencies injected are classes that handle data hydration from an HTTP request, calling other web services for fulfilling business logic, persisting records, and ultimately creating an HTTP response object. There are external configurations that adjust the business logic applied to the request as well.

The example is hopefully enough to give you all a jist of what I'm dealing with. The real implementation is even worse.

class ResourceHandler implements HandlerInterface
{
    private $request;
    private $response;
    private $someWebServiceClient;
    private $requestToWebServiceRequestTransformer;
    private $databaseRepo;
    private $requestToDatabaseRecordTransformer;
    .
    .
    .
    private $cacher;
    private $logger;

    public function handle()
    {
        return $this
          ->buildRequest()
          ->checkThisDatabase()
          ->callThatWebService()
          ->storeSomeRecords()
          .
          .
          .
          ->buildResponse();
    }
}

interface HandlerInterface {
    public function handle();
}

R string extract pattern

I have a question regarding to extract letters from a string For example I have in R one vector like:

America, Asia, Europe

I want to get all of the upper letters in this format like

AAE or A, A, E

How can I do this with regmatches and regexpr?

Convert code to use more OOP design patterns

I have to solve a problem of a vending machine which:

  1. Accepts coins of 0.1, 0.2, 0.5, 1, 2 euros.
  2. Allow user to select products Water(0.5euro), Coke(1euro), Pepsi(1.5euro), Soda(2.5euro)
  3. Allow user to take refund by canceling the request.
  4. Return selected product and remaining change(least amount of coins) if any
  5. Allow reset operation for vending machine supplier(initial state of machine: no coins inserted and no product selected).

I tried to implement this program by creating two classes. The first one is:

public enum Product {
    WATER("Water", 0.5), COKE("Coke", 1.0), PEPSI("Pepsi", 1.5), SODA("Soda", 2.5);
    
    private String name;
    private double price;
    
    //Constructor
    private Product(String name, double price) {
        this.name= name;
        this.price = price;
    }
    
    //Getter methods
    public String getName() {
        return name;
    }
    
    public double getPrice() {
        return price;
    }
}

and the second is the VendingMachine.java where i have implemented all the methods but i have problem with the program structure that i have made. I cant compose all the functions to create what the program wants. Here is the VendingMachine.java

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class VendingMachine {
    private double totalMachineCoins;
    private double addedCoins;
    private Product selectedProduct;
    
    
    private void printingMenu(){
        System.out.println("1-> Water(0.5€)\n" + "2-> Coke 330 ml(1€)" +
                           "3-> Coke 500 ml(1.5€)\n" + "4-> Crunch(2.5€)");
    }
    
    
    private void selectProduct() {
        printingMenu();
        Scanner scanner = new Scanner(System.in);
        System.out.println("Select Product: ");
        int choice = scanner.nextInt();
        while(choice < 1 && choice > 5) {
            System.out.println("This product code doesn't exist. Please select again!");
            choice = scanner.nextInt();
        }
        if(choice == 1) {
            selectedProduct = Product.WATER;
        }
        else if(choice == 2) {
            selectedProduct = Product.COKE330;
        }
        else if(choice == 3) {
            selectedProduct = Product.COKE500;
        }
        else {
            selectedProduct = Product.CRUNCH;
        }
    }
    
    
    private boolean validCoin(double coin) {
        if(coin == 0.1 | coin == 0.2 | coin == 0.5 | coin == 1.0 | coin == 2.0) {
            return true;
        }
        return false;
    }
    
    
    private void insertCoins() {
        addedCoins = 0;
        while(addedCoins < selectedProduct.getPrice()) {
            Scanner scanner = new Scanner(System.in);
            System.out.println("Insert coin: ");
            double coin = scanner.nextDouble();
            while(validCoin(coin) == false) {
                System.out.println("The coin is not acceptable! Please put another");
                coin = scanner.nextDouble();
            }
            addedCoins += coin;
            returnRemainingChange(selectedProduct.getPrice());
        }
        
        totalMachineCoins += addedCoins;
    }
    
    
    private void returnRemainingChange(double productPrice) {
        if(addedCoins > productPrice) {
            double change = addedCoins - productPrice;
            int coin2 = (int) (change / 2.0);
            change = change % 2.0;
            int coin1 = (int) (change / 1.0);
            change = change % 1.0;
            int coin05 = (int) (change / 0.5);
            change = change % 0.5;
            int coin02 = (int) (change / 0.2);
            change = change % 0.2;  
            int coin01 = (int) (change / 0.1);
            System.out.println("Change: " + change);
            System.out.println("You took back: \n" +
                                coin2 + " coins of 2€\n" +
                                coin1 + " coins of 1€\n" +
                                coin05 + " coins of 0.5€\n" +
                                coin02 + " coins of 0.2€\n" +
                                coin01 + " coins of 0.1€");
        }
        else {
            System.out.println("There is no remaining change");
        }
    }
    
    
    //take refund by cancelling the request
    private void takeRefund() {
        System.out.println("Cancelling the request....");
        System.out.println("Take refund: " + addedCoins + "€");
        addedCoins = 0;
    }
    
    
    private void resetMachine() {
        totalMachineCoins = 0;
        addedCoins = 0;
    }
}

Can enyone help me to finalize this exercise?(use the functions to make the program run correctly and use a java pattern to make the code better). Thank you very much for your time

Is this Scala / Functional Programming pattern to avoid OOP classes, an official design pattern? Does it have a name?

Classes in OOP couple variables to methods via a scope, thus making refactors painful as we cannot easily move methods from one place into another. The entire dependency graph, with initialisation, of the class must be moved with the method somehow. A common "solution" in OOP is dependency injection frameworks.

E.g. in OOP

class Foo(client: Client) {
  def dumbCouplingOfMethodToScope: Unit = client.send("hello world")
}

In Scala the solution to this is to use implicit parameters, usually called a "Context". E.g.

object Foo {
  def methodNotDependOnScope(client: Client): Unit = client.send("hello world")
}

But a problem occurs when we want to do dynamic dispatch, i.e. be able to pass in multiple implementations of the Context (usually for testing), and when the Context itself depends on another Context. E.g.

trait MethodsNeedContext[Context] {
  def method1(p1: Int)(implicit context: Context): Int
}

object ExampleUsage {
  def callsMethod1(implicit contextWithContext: MethodsNeedContext[???], contextsContext: ???): Unit = {
    contextWithContext.method1(10)(contextsContext)
  }
}

We only know the type ??? at runtime, not at compile time. The OOP way would be to make MethodsNeedContext an abstract class, then we can use an existential type. E.g.

abstract class OOPWay[Context <: ContextTypeBound](context: Context) {
  def method1(p1: Int): Int = context.send("hello world")
}

object ExampleUsage2 {
  def callsMethod1(implicit contextWithContext: OOPWay[_ <: ContextTypeBound]): Unit = {
    contextWithContext.method1(10)
  }
}

But if we wrap the contextWithContext and contextContext into a case class, then add an implicit class then we can solve the problem. Full example below:

trait ContextTypeBound

trait MethodsNeedContext[Context <: ContextTypeBound] {
  def method1(p1: Int)(implicit ctx: Context): Int
  def method2(p2: String)(implicit ctx: Context): String
}

case class MethodsWithContext[T <: ContextTypeBound](methods: MethodsNeedContext[T], context: T)

object Pimps {
  implicit class PimpedMethodsWithContext[T <: ContextTypeBound](methods: MethodsWithContext[T]) {
    def method1(p1: Int): Int = methods.methods.method1(p1)(methods.context)
  }
}

import Pimps.PimpedMethodsWithContext

case class FooContext(foo: Int) extends ContextTypeBound

object FooExample extends MethodsNeedContext[FooContext] {
  def method1(p1: Int)(implicit ctx: FooContext): Int = ???
  def method2(p2: String)(implicit ctx: FooContext): String = ???
}

case class BobContext(foo: Int) extends ContextTypeBound

object BobExample extends MethodsNeedContext[BobContext] {
  def method1(p1: Int)(implicit ctx: BobContext): Int = ???
  def method2(p2: String)(implicit ctx: BobContext): String = ???
}

object ExampleUsage {
  def callsMethod1(implicit contextWithContext: MethodsWithContext[_ <: ContextTypeBound]): Unit = {
    contextWithContext.method1(10)
  }

  callsMethod1(MethodsWithContext(FooExample, FooContext(20)))
  // Does not compile
  callsMethod1(MethodsWithContext(BobExample, FooContext(20)))
}

My question(s) are:

  1. Does this pattern have a name? Is it a standard Scala practice?
  2. Is this a Scala only thing, or do other FP languages have similar mechanisms to do the same thing? If other FP languages have different mechanisms, what are they?

Difference in Implementations of Thread Safe Singleton Design Patteren

What is the difference between thread-safe Singleton Design Pattern with Double Check Locking as in the below code.

public class Singleton {
    private static volatile Singleton instance;
    private Singleton() {}

    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (this) {
                if(instance==null)
                    instance = new Singleton();
             }
        }
        return instance;
    }
}

And in below implementation other than Eager initialization.

public class Singleton {
    private static volatile Singleton instance = new Singleton();
    private Singleton() {}

    public static Singleton getInstance() {
        return instance;
    }
}

lundi 29 juin 2020

Liskov vs Override

Liskov says : you can't change the super class behaviors in child class. Override says : you can change the super class behavior in child class.

I am confuse and i don't realize which one is correct?

Thank you for answers

Implement Decorator Pattern with generics in Swift

I am new to Swift, but I have plenty of experience in other languages like Java, Kotlin, Javascript, etc. It's possible that what I want to do is not supported by the language, and I've pored over the Swift Language Guide looking for the answer.

I want to implement the decorator pattern, using generics. I easily did this in Kotlin, and I'm porting the library to Swift.

class Result<T> {
  let result: T?
  let error: NSError?

  init(result: T?, error: NSError?) {
    self.result = result
    self.error = error
  }
}

protocol DoSomething {
  associatedtype T

  func doSomething() -> Result<T>
}

protocol StoreSomething {
  associatedtype T

  func storeSomething(thing: Result<T>)
}

/*
 * DOES NOT COMPILE
 */
class StoringSomething<T> {
  private let delegate: DoSomething
  private let storage: StoreSomething

  func doSomething() -> Result<T> {
    let result = delegate.doSomething()

    storage.storeSomething(thing: result)

    return result
  }
}

I get a Protocol 'DoSomething' can only be used as a generic constraint because it has Self or associated type requirements error from the compiler. I've tried using a typealias and other ideas from SO and the Swift manual.

Function to follow replica exchanges from file

I'm trying to write a python script that will follow a set of exchanges recorded in a file.

The file shows lines with "Repl ex 0 x 1 2 3 4 x 5 ......."

The "x" indicates that replica 0 exchanged with replica 1 and replica 4 exchanged with replica 5.

I want to go through the file and create a list for each starting replica that shows all the numbers that it travelled through. So a list for the replica that started at 0 and each replica that it exchanged into during the course of the simulation and the same thing for the replica that started at 1, 2, 3 and so on.

So far I've used regexes to generate a list of lists (called exchanges[i]) of the lines from the "md.log" file where exchanges occur between each pair (i.e. exchanges[0] = file lines where 0 x 1 only).

If we are following the replica that started at 2, this will look for the first exchange that occurs between 1 x 2 or 2 x 3 and add the number of the system that it moves into.

For the next round of searching, a master list (xch_lines) containing all the lines from the file where any exchange occurs is used to determine the line to start from when searching the new adjacent xch_lists.

The code returns a list that appears to follow the replica up and down but eventually it seems to decay into returning a list of 1's and 0's. The list is about twice as long as it should be and it's the second half of the list that seems to be the problem.

import analyze_exchanges

replica = 8

if replica != 0:
    xp = replica - 1
else:
    replica = 0

walker.append(replica)

On = True

while result[0] != 2:
    
    result = find_next_xch(xp, master_index)
    
    if result[0] == 2:
        On = False
        break
    elif result[0] == 0:
        if replica == 0:
            replica += 1
            master_index = result[1]
            walker.append(replica)
            continue
        else:
            replica -= 1
            walker.append(replica)
            master_index = result[1]
            if replica == 0:
                continue
            else:
                xp -= 1
                continue
            
    elif result[0] == 1:
        replica +=1
        walker.append(replica)
        master_index = result[1]
        xp += 1
        continue
    
print(len(walker))
print(walker)

Analyze exchanges module

import re

# regular expressions for each exchange pair
regexes = [r"Repl ex\s+0\s+x\s+1", r"Repl ex.*1\s+x\s+2", r"Repl ex.*2\s+x\s+3",
           r"Repl ex.*3\s+x\s+4", r"Repl ex.*4\s+x\s+5", r"Repl ex.*5\s+x\s+6",
           r"Repl ex.*6\s+x\s+7", r"Repl ex.*7\s+x\s+8", r"Repl ex.*8\s+x\s+9",
           r"Repl ex.*9\s+x\s+10", r"Repl ex.*10\s+x\s+11", r"Repl ex.*11\s+x\s+12",
           r"Repl ex.*12\s+x\s+13", r"Repl ex.*13\s+x\s+14", r"Repl ex.*14\s+x\s+15",
           r"Repl ex.*15\s+x\s+16", r"Repl ex.*16\s+x\s+17", r"Repl ex.*17\s+x\s+18",
           r"Repl ex.*18\s+x\s+19"]

# make lists for each exchange pair that will store the line numbers for each exchange that that pair makes
exchanges = [[] for i in range(19)]
# open the md.log file
f = open('/Users/danielburns/Desktop/md.log', 'r')


# go through the md.log file looking for every time a pair exchanges and add that line number to that exchange pair's list
for i, line in enumerate(f):
    for x in range(19):
        if re.compile(regexes[x]).match(line):
            exchanges[x].append(i)

# master list for all the exchange attempt lines 
xch_lines = []
# reset to beginning of log file
f.seek(0)
# append all the exchange attempt lines to the list
for j, line in enumerate(f):
    if re.compile(r"Repl ex\s+").match(line):
        xch_lines.append(j)

#number of replicas
nreps = 20

#number of exchange lists
maxpair = nreps - 2

# List the replicas that the walker goes through
walker = []

#Starting index for the master list of exchange lines
master_index = -1



def find_next_xch(xp, master_index):
    """
    returns 0 if the next exchange is down and (unless current replica = 1)
    returns 1 if the next exchange is up 

    """
    li = 1
    while True:
        
        
        if xch_lines[li + master_index] >= exchanges[xp][-1]:
            return (2,)
            break
        
        elif xch_lines[master_index + li] in exchanges[xp]:
            master_index = master_index +li
            return (0, master_index)
            break
        elif xp == maxpair:
            li += 1
            continue
        elif xch_lines[master_index + li] in exchanges[xp + 1]:
            master_index = master_index +li
            return (1, master_index)
            break
        
        else:
            li += 1
        


        

The md.log file to be analyzed can be found here https://github.com/DBurns-Lab/Analyze_Exchanges

Purpose of IAggregateRoot interface in in Microsoft Repository Pattern document

I am looking at the Respository Pattern in Microsoft website.

Respository Pattern

I section i am not understand what IAggregateRoot does?

public interface IRepository<T> where T : IAggregateRoot
    {
        //....
    }

Can each respository class interact each others e.g. Product respository may be used by OrderRespository.

Reuse various entities in different services

In my WPF application, I have a situation where I dont't know what pattern/technique shall be used in order to reuse/share various entities in different services of views.

I'll try to describe this with some C# pseudo-code:

public class ViewModelA : ViewModelBase
{
    private IParserService parserService;
    
    ViewModelA(IParserService parserService)
    {
        // Injected via DI
        this.parserService = parserService; 
    }
    
    private void ParseDataFromFile(string fileName)
    {
        string extension = Path.GetExtension(fileName);

        // Only xml and json are relevant, so no need for the strategy design pattern
        switch(extension)
        {
            case ".xml":
            var entityA = parserService.ParseXml();
                break;
            case ".json":
            var entityB = parserService.ParseJson();
                break;
        }

    }
}

public class EntityA
{
    public int IntA { get; set; }
    public string StringA { get; set; }
}

public class EntityB
{
    public string StringB1 { get; set; }
    public string StringB2 { get; set; }
}

public class ServiceB
{
    // ServiceB will use the EntityA and EntityB
    // EntityA and EntityB shall be available at the application restart
}

public class ServiceC
{
    // ServiceB will use only the EntityB
    // EntityB shall be available at the application restart
}

Now, based on the code snippet above, I try to reuse entities EntityA & EntityB in different services that are invoked from different viewmodels. Since the parsing procedures of both, the ParseXml() and ParseJson() might take quite a long processing time and in addition they shall be available after the application restart, I don't know how to reuse/share this entities between different services (or viewmodels).

My first thought was to simply serialize the parsed entities and deserialze them afterwards in each service class that requires it, like so:

public class ServiceB
{
    ServiceB()
    {
        var entityA = Deserialize(string filePathToEntityA);
        var entityB = Deserialize(string filePathToEntityB);
    }
}

public class ServiceC
{
    ServiceC()
    {
        var entityB = Deserialize(string filePathToEntityB);
    }
}

But this, imo, creates some kind of weird and unusable structure...

So, what I'm looking for, is a practical approach in C# on how to solve this kind of problem.

Strategy Pattern and context class

Reading about the strategy design pattern, was thinking if it is possible to have two context.

Looking forward for opinions if the below code-design utilises the Strategy design pattern.

Or strategy design pattern forces us to have only one context meaning that the design below is incorrect.

public interface Algorithm {}
public class FirstAlgorithm implements Algorithm {}
public class SecondAlgorithm implements Algorithm {}


public interface Cryptography {}

public class DecryptionContext implements Cryptography {
    public DecryptionContext(Algorithm algorithm) {
        this.algorithm = algorithm;
    }
}

public class EncryptionContext implements Cryptography {
public EncryptionContext(Algorithm algorithm) {
        this.algorithm = algorithm;
    }

}

Several points of objects creation

I'm developing a framework. It has a kind of Launcher class where all needed by the frameworks's core services and other classes are instantiated (first point of objects creation). There's no dependency on concrete implementations anywhere in the core outside Launcher. It's okay.

But also I have such things as plugins (let's assume there's Plugin class which represents a plugin). Of course plugins should have ability to be added without any changes in the core code. Another condition is that I do not know what services (and other things) a plugin's Plugin class needs for work so I cannot inject them (at least I guess so). Therefore a plugin developer needs to instantiate the dependencies in some function like initializePlugin() (which is in the Plugin class) and it makes this function the second+ point of objects creation.

And instantiation code (in the second+ creation point) then depends on concrete implementations of interfaces. But what if I decide to change implementation of services? I would have to change every point of objects creation (what I cannot do because some plugins can be 3rd party software). So how do I organize classes without changing the second+ points of creation in future? Do I have to use DI container?

Service in front of session/cache design pattern

We have a series of model objects that are stored on a user's Session (although you could think of this as any cache). And we have a series of 'services' sitting in front of those that act as interfaces to them. So for example say Address was one of the things we stored. We would have an address based service in front that would expose getAddress(), and would check the session for if it exists. If it exists it just returns it, if it doesn't exist it would go fetch it from somewhere, store it on the session and return it. It’s kind of a lazy loading approach.

I believe this is a common pattern, but what is the name for the 'series of services'? I have considered names such as Delegate, Proxy, Facade, Loader, but none of those seem quite correct.

Java Regex Matching Classes inside Classes

Hey so I already searched the internet for various examples but I cannot get to work the following Regex. I am trying to remove every char out of a String list entry that doesn't match my pattern.

My pattern looks like this for example: e2-e4, d4-d5 and occasionally a specific last char may be given.

First of every line gets filtered with the following pattern:

List<String> lines = Files.readAllLines(Paths.get(String.valueOf(file)));
        Pattern pattern = Pattern.compile("[a-h][1-8]-[a-h][1-8][BQNRbqnr]?");
        List<String> filteredLines = lines.stream().filter(pattern.asPredicate()).collect(Collectors.toList());

But if I have input like this garbo1239%)@a2-a5, I want the garbo to be filtered out.

I came up with the following solution to this problem: I iterate over my String list and use the replaceAll method to filter out the junk:

for(int i = 0; i < filteredLines.size(); i++){
            filteredLines.set(i, filteredLines.get(i).replaceAll("[^[a-h][1-8]-[a-h][1-8]][BQNRbqnr]?",""));
        }

Unfortunately it doesn't have the desired effect. Things like a2-a4d or h7-h614 are still not being "cleaned" and I couldn't really figure out why. I hope someone can help me, thanks in advance!

How to implement Laravel send test email and sms the right way?

We have a form to receive email(smtp) and another form to receive sms settings. under these forms we allow user to send a test email and sms using entered data in related form above. what is the right way to implement sending test email and sms?(I mean a way that does not brake SOILD and other OOP principles). which routes and controllers and methods should created? currently I just added to methods in SettingController : sendTestEmail,sendTestSms but I know it's not the correct way of doing that because as the program grows it gets harder to debug and maintain and it also brakes SRP principle of SettingController. note: we receive and save settings from database using SettingController.

Builder class for generic type list

I have a class which have a generic type list, I want to set this field using builder pattern, please help me, I am not able to find any suitable content in the internet

Java Class

public class DialogCar<T> implements Parcelable {

    private String type;
    private List<T> selectedValues;
...

please let me know the Builder class for the above java class

С++ GUI wxWidgets: Code Architecture, Design Principles and Patterns

I recently started learning C++ and wxWidgets. Now I'm doing a calculator. When I start writing code, everything is ok, but when code gets bigger and bigger, it becomes a mess.

One thing that I realized, and that turns my code into a mess, is that I'm putting all my code into one file instead of splitting it into several files.

I want to know any C++ GUI code architectures, design principles and patterns that will help to write clean, flexible and scalable GUI applications.

Laravel best strategy to serve requests from API and form at the same time

Using Laravel 7.*, I'm tasked with creating a simple app to send requests for payment, the user fill a form and send the data then I validate the user inputs and create a new Payment instance.

Then the user is redirected back to the same page. (Of course there are other requests for listing all payments and updating a payment):

   //In PaymentController.php

   public function store()
    {
        $inputData = $this->validateRequest();

        $person = $this->personRepository->findOneByAttribute('id_number', request('id_number'));

        if ($person instanceof Person) {
            $this->paymentRepository->create($inputData, $person);
            return back()->with('successMessage', 'Your payment request registered successfully.');
        } else {
            return back()->with('failureMessage', 'Shoot! Cannot find a peron with the given Identification Number.')->withInput();
        }
    }

Everything is fine, but I need to implement a Restful API to do the same request and get a valid json response, Assuming there is no front-end JavaScript framework, what is the best approach to achieve this goal?

Should I create a separate controller? Or Simply check whether request is sent from a traditional form or an API client? Am I missing a design pattern?

Call Controller from kafka component

I've been searching a lot about it, and the only two things I've found is that my design is possibly bad, but I doubt it is. The problem I am having is that I have Spring Kafka classes, where I have a trigger waiting for the messages that reach a topic, and when that info arrives I want to send it to my controller, and from my controller it will be taken to another microservice.

Could I autowired my controller without creating infinite instances?

Name of classes: KafkaConsumer

When kafka is activated I would like to call a method from my controller.

Code Kafka:

@Component
public class KafkaConsumer {

    private static final String TOPIC = "topic_name";


    @KafkaListener(topics = TOPIC)
    private void listen(String msg) {
        
      //Send msg to my controller
    }
}


How and why can the Observer Pattern implement the MVC Architectural Style?

Can you give me an example for this and specify each components role? For better understanding. Thank you.

dimanche 28 juin 2020

Understanding programs architecture in C++

I have studied GOF and GRASP patterns, remember each of them well, and can easily write a code example with one of the patterns without hints. But when it comes to real projects, the maximum that comes to mind is a singleton pattern(which I use very often because I do not understand how to do otherwise better). After a few thousand lines of code I begin to realize that I make a lot of mistakes in the program's architecture and could have done better, even using the same design patterns. Somewhere I do not understand whether to create an Application class that will store objects of the Gui, Network classes, or better to make Gui and Network singleton. I understand that everything should come with experience, but after a month I understand that I did not understand how to do it correctly - and did not understand. Are there any good books that will help you better understand the architecture of programs? Or examples of open source projects with a competent architecture to understand what a good application architecture should look like? Thank you in advance!

Can i use gsub function to find a pattern and replace it with 2 different patterns?

I need help with finding a pattern and replacing it by two different ways. For example, the word "Code/i" should be replaced with "Code, Codi". What code should i use in replacement to get two results separated by comma? I am new to R and assuming some metacharacters or regex needs to be used? Also, i need to use base functions and no external packages. Appreciate any feedback and help as im stuck! Thanks

a <- c("Code/i")

gsub(pattern = "/i", replacement= "", a)

Having problems generating a star pattern in python suggested from a book but getting different results

I am new on Python and I am following a book that purposes the following excercise:

Write a program to generate the following pattern in Python:

*
**
***
****

The suggested code is:

n = input('Enter the number of rows: ')
m = int(n)
*k = 1
for i in range(m):
    for j in range(i, i + 2):
        print('*', end = " ")
    print()

and enter n=5.This lead me to ask to questions. The first one is the *k=1, I am asumming the '' is a typo on the book since my program does not run with it. However i am not seeing that k is being used within the loop. My second question is that I do not understand why my outcome is different than the one I get (once removed the ''). This is what I get when n=5:

**
**
**
**
**

How to create many-many communication among go-routines, without a critical section?

Every writer (goroutine) has its corresponding reader (goroutine).

Buffered channel does not give guarantee of delivery, so I have used unbuffered channel


For communication, every writer registers its data channel, in the below hub:

// Writer hub - "Maintain the set of active Writers"
type WriterHub struct {
    Writers    map[*WriterSubscription]struct{}
    Register   chan *WriterSubscription
    Unregister chan *WriterSubscription
}

func NewHub() *WriterHub {
    return &WriterHub{
        Writers:    map[*WriterSubscription]struct{}{},
        Register:   make(chan *WriterSubscription),
        Unregister: make(chan *WriterSubscription),
    }
}

type WriterSubscription struct {
   DataChannel      chan *data.Object
   CloseDataChannel chan bool
   WriterNumber     uint
}

A separate goroutine maintains registration functionality:

func (hub *WriterHub) Run() { // on a go-routine
    for {
        select {
        case Writer := <-hub.Register:
            hub.Writers[Writer] = struct{}{}

        case Writer := <-hub.Unregister:
            if _, ok := hub.Writers[Writer]; ok {
                delete(hub.Writers, Writer)
            }
        }
    }
}

Each Writer registers to this hub:

func CreateWriter(hub *WriterHub, WriterCount uint, wg *sync.WaitGroup) { // invoked from main()

    // Subscribe to Writers hub
    Writer := &WriterSubscription{
        DataChannel:      make(chan *data.Object),
        CloseDataChannel: make(chan bool),
        WriterNumber:     WriterCount,
    }
    hub.Register <- Writer

    go func() {
        defer wg.Done()
        for {
            Writer.DataChannel <- data.CreateObject()
            stop := <-Writer.CloseDataChannel
            if stop == true {
                hub.Unregister <- Writer
                fmt.Println("Signal received")
                break
            }
        }

    }()
}

For simplicity, reader goroutines launch only after all writers have registered with Writerhub

Below is the code for launching readers.

Based on number of writers, equivalent number of readers get launched, in the below code.

for Writer := range hub.Writers { // for each Writer
        go func() { // Launch a corresponding reader

            for {
                object := <-Writer.DataChannel          // receive
                print(object)
    
                if someCondition(Writer.WriterNumber) {
                    Writer.CloseDataChannel <- false
                } else {
                    Writer.CloseDataChannel <- true
                    break
                }
             }
         }
  }

Invoking CreateWriter() twice from main(), two writers(go-routines) gets launched & register their channels successfully in channel hub(WriterHub).


But,

go install -race option gives,

Line: for Writer := range hub.Writers

&

Line: hub.Writers[Writer] = struct{}{} in Run()

as data race.

Reason is, WriterHub is in race condition, due to which, second reader is not launched.

Need to access WriterHub as a critical section.


Is there a concurrency pattern (in Go) to perform many-many communication using unbuffered channel? without having a critical section

Multiple readers and writers without a critical section

Every writer(go-routine) has its corresponding reader(go-routine).

For communication, I have a channel hub, where every writer registers its data channel, as shown below:

// Writer hub - "Maintain the set of active Writers"
type WriterHub struct {
    Writers    map[*WriterSubscription]struct{}
    Register   chan *WriterSubscription
    Unregister chan *WriterSubscription
}

func NewHub() *WriterHub {
    return &WriterHub{
        Writers:    map[*WriterSubscription]struct{}{},
        Register:   make(chan *WriterSubscription),
        Unregister: make(chan *WriterSubscription),
    }
}

type WriterSubscription struct {
   DataChannel      chan *data.Object
   CloseDataChannel chan bool
   WriterNumber     uint
}

A separate go-routine maintains registration functionality:

func (h *WriterHub) Run() { // on a go-routine
    for {
        select {
        case Writer := <-h.Register:
            h.Writers[Writer] = struct{}{}

        case Writer := <-h.Unregister:
            if _, ok := h.Writers[Writer]; ok {
                delete(h.Writers, Writer)
            }
        }
    }
}

Each Writer registers to this hub:

func CreateWriter(hub *WriterHub, WriterCount uint, wg *sync.WaitGroup) { // invoked from main()

    // Subscribe to Writers hub
    Writer := &WriterSubscription{
        DataChannel:      make(chan *data.Object),
        CloseDataChannel: make(chan bool),
        WriterNumber:     WriterCount,
    }
    hub.Register <- Writer

    go func() {
        defer wg.Done()
        for {
            Writer.DataChannel <- data.CreateObject()
            stop := <-Writer.CloseDataChannel
            if stop == true {
                fmt.Println("Signal received")
                break
            }
        }

    }()
}

For simplicity, I have enforced reader go-routines launch only after all senders have registered, as shown below.

Based on number of senders, number of receivers gets launched, accordingly.

But the problem is,

Each reader need to access its corresponding datachannel, which makes WriterHub a critical section, as shown below:

for Writer := range WriterHub.Writers { // for each Writer
        go func() { // Launch a corresponding reader

            for {
                object := <-Writer.DataChannel          // receive
    
                if someCondition(Writer.WriterNumber) {
                    Writer.CloseDataChannel <- false
                } else {
                    Writer.CloseDataChannel <- true
                    break
                }
           }

Reader functionality is to just print the data received from sender.

What can be the approach to make every writer/reader access their coresponding DataChannel without adding them to a critical section(WriterHub)?

Using a design pattern like MVC with SwiftUI

I am trying to implement a design pattern like MVC in order to achieve low coupling between different parts of the code. There are few materials online that I personally didn't find helpful in relation to IOS or swift UI development and MVC pattern.

What I am trying to understand is how should the controller class control or render the UI in Swift UI ?

Following the MVC pattern for example - the View shouldn't know about how the model looks like, so sending an object back from the Data Base to the view in order to visually present it wouldn't be a good Idea..

Say we have the following View and Controller, how should I go about the interaction between the controller and view when sending the data back from the DB in order to visually present it in the view ?

View:

import SwiftUI
import Foundation

struct SwiftUIView: View {

    
    var assignmentController = AssignmentController()
    

    @State var assignmentName : String = ""
    @State var notes : String = ""
  

  
    var body: some View {
        
        NavigationView {
            VStack {
                Form {
                   
                        
                        TextField("Assignment Name", text: $assignmentName)

    
                        TextField("Notes", text: $notes)
                
     
            }
                
                Button(action: {
                                                               
                    self.assignmentController.retrieveFirstAssignment()
                                       }) {
                                                                                                                                                Text("Get The First Assignment !")
                                                                                    }

            }
            .navigationBarTitle("First Assignment")
        }
        
    
}
}

Controller

var assignmentModel = AssignmentModel()

func retrieveFirstAssignment()
{
    var firstAssignment : Assignment

    firstAssignment=assignmentModel.retrieveFirstAssignment()
    
}

For now, it does nothing with the object it found.

Model

An object in the model composed of two String fields : "assignmentName" and "notes".

*We assume the assignment Model have a working function that retrieves one task from the DB in order to present it in the view.

Avoid casting using polymorphism (or design patterns)

I have the following classes:

interface Event

interface NotificationEvent : Event

data class InviteEvent(val userId: Long, val inviteeId: Long) : NotificationEvent

Event represents a generic event
NotificationEvent represents an event that trigger a notification
InviteEvent represents an implementation of NotificationEvent

I would write a code that reacts to notification events, writing handlers for every type of event.
Accordingly to "Open-close" principle, I'd like to avoid to edit some existing classes to handle new types of event (i.e. avoid the hell switch case). The idea that I came up with was creating the following classes:

abstract class NotificationEventHandler<T : NotificationEvent> {
    fun handle(notificationEvent: NotificationEvent) {
        @Suppress("UNCHECKED_CAST")
        if (isSupported(notificationEvent)) {
            handleInternal(notificationEvent as T)
        }
    }

    protected abstract fun isSupported(notificationEvent: NotificationEvent): Boolean
    protected abstract fun handleInternal(notificationEvent: T)
}

@Component
class InviteEventHandler : NotificationEventHandler<InviteEvent>() {

    override fun isSupported(notificationEvent: NotificationEvent) =
        notificationEvent is InviteEvent

    override fun handleInternal(notificationEvent: InviteEvent) {
        // Logic here
    }

}

The idea is that, in my service I can autowire all my NotificationHandler classes, call handle on each one, and the internal logic will call handleInternal if necessary.

@Service
@Transactional
class NotificationServiceImpl(
    val notificationEventHandlers: List<NotificationEventHandler<*>>
) : NotificationService {
    override fun onNotificationEvent(notificationEvent: NotificationEvent) {
        notificationEventHandlers.forEach {
            it.handle(notificationEvent)
        }
    }

I really do not like this implementation... when I see casting in my code, normally I'm doing something wrong (i.e. missing some design pattern or ignoring polymorphism powers). Moreover I'm invoking handle on every handler instead of calling it only on supported ones.

Do you have some idea how to implement this without casting?

Thank you so much.
Francesco

samedi 27 juin 2020

Pattern for a class with a long running method and a method for stopping it

What would be the best pattern to implement for a class with a long-running method and a method that releases resources. Currently, it looks like this:

static async Task<int> Main(string[] args)
{
    MyProcessor processor = new MyProcessor();
    processor.SomeConfigOptions = ...;
    processor.SomeEvent += ...;

    // ProcessAsync() method contains an infinite loop that runs until we signal to stop.
    // ProcessAsync() method allocates unmanaged resourses.
    using (Task engineTask = Task.Run(() => processor.ProcessAsync()))
    {
        // Keep application running some event.
        Console.ReadKey();

        // Signal to stop processing, release unmanaged resources, and exit ProcessAsync() method.
        processor.Stop();

        // Wait for the processing to finish and all unmanaged resources are released.
        processor.Wait();
    }

    return 1;
}

Does it make sense to derive MyProcessor from IDisposable? Or to return a class derived from Task from ProcessAsync() method? In both cases, the Stop() method will be called inside IDisposable.Dispose() override. Any better approach for this pattern?

How do I mutably use an instance from multiple instances on the stack in Rust?

I am relatively new to Rust, coming from mainly C++ and Python trying to learn how to do things the rust way. The following code uses unsafe code to be able to use an instance of A mutably from instances of both B and C. I don't think I should need to use unsafe code to do this, but I could be wrong. Is there a better way without using dynamically allocated memory, and without flattening B and C into the same implementation?

use core::cell::UnsafeCell;

struct A {}

impl A {
    fn do_something(&mut self) {
        // does something
    }
}

struct B<'a> {
    a: &'a UnsafeCell<A>,
}

impl<'a> B<'a> {
    fn do_something_with_a(&mut self) {
        unsafe { (*self.a.get()).do_something() }
    }
}

struct C<'a> {
    a: &'a UnsafeCell<A>,
    b1: B<'a>,
    b2: B<'a>,
}

impl<'a> C<'a> {
    fn new(a: &'a UnsafeCell<A>) -> Self {
        Self {
            a: a,
            b1: B{a: a},
            b2: B{a: a},
        }
    }

    fn use_b(&mut self) {
        self.b1.do_something_with_a();
        self.b2.do_something_with_a();
    }

    fn use_a(&mut self) {
        unsafe { (*self.a.get()).do_something() }
    }
}

fn main() {
    let a = UnsafeCell::new(A{});
    let mut c = C::new(&a);
    c.use_b();
    c.use_a();
}

Designing an globally distributed restful API that writes to databases

I am currently designing a distributed restful API service that takes request from client side and writes the payload information into multiple database located in different geographical regions. The estimated QPS is ~100k. Data won't be read immediately after it has been written. What are some design considerations in designing such service?

I also have a few specific questions:

  1. There will be collocated services consuming data from the databases in their respective data center, should my service still writes all data to all databases? Or should I only write data specific to that region to its local database?

  2. If data recency is a concern (i.e. data that's being written will be read very soon), what architectural changes should I consider?

Implementing RAII on a folder iteration

I wrote this code in order to loop recursively through a folder tree and list files with their size in bytes.

Since I am using winapi and there is a Handle that should be opened and closed, I should implement RAII on this code, the problem is the examples given in online forums (not to mention that I am not a native English speaker) and many books including Effective C++ are way over the head of a person who isn't finding any place to get experience.

Anyone kind enough to point me at least?

#include <iostream>
#include <string>
#include <windows.h>

void findFiles(std::string & spath) {

  size_t i = 1;
  WIN32_FIND_DATA FindFileData;

  std::string sourcepath = spath + std::string("\\*.*");

  HANDLE hFind = FindFirstFile(sourcepath.c_str(), & FindFileData);

  if (hFind != INVALID_HANDLE_VALUE)
    do {
      std::string fullpath = std::string(spath) + std::string("\\") + std::string(FindFileData.cFileName);

      if ( * (fullpath.rbegin()) == '.')
        continue;
      else
      if (FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
        findFiles(fullpath);
      else

        std::cout << i++ << "-" << FindFileData.cFileName << " " << (FindFileData.nFileSizeHigh *(MAXWORD + 1)) + FindFileData.nFileSizeLow << std::endl;

    } while (FindNextFile(hFind, & FindFileData));

  FindClose(hFind);

}

int main(int argc, char ** argv) {

  std::string spath(argv[1]);

  findFiles(spath);

}

Use SuperGraph as a library in already existing project, doubts and questions

I'm trying to use SuperGraph as a library.

I think I can summarize the problems that a neophyte (GraphQL and Go) like me can have in these three points:

  1. How to integrate SuperGraph (especially for CRUD) into an existing Go project that does not already use GraphQL
  2. how to integrate SuperGraph (especially for CRUD) into an existing Go project that already uses GraphQL
  3. how to perform other actions (call other code/packages) before, during or after SuperGraph operations (the so-called "actions" of Hasura and other similar projects)

#1

For point number 1 I think I have found a good way with this code:

package main

import (
    "context"
    "database/sql"
    "encoding/json"
    "net/http"

    "github.com/go-chi/render"
    "github.com/dosco/super-graph/core"
    "github.com/go-chi/chi"
    _ "github.com/jackc/pgx/v4/stdlib"
)

type reqBody struct {
    Query string `json:"query"`
}

func sgHandler(sg *core.SuperGraph) http.HandlerFunc {
    return func(w http.ResponseWriter, r *http.Request) {
        // Check to ensure query was provided in the request body
        if r.Body == nil {
            http.Error(w, "Must provide graphQL query in request body", 400)
            return
        }

        var rBody reqBody
        // Decode the request body into rBody
        err := json.NewDecoder(r.Body).Decode(&rBody)
        if err != nil {
            http.Error(w, "Error parsing JSON request body", 400)
        }

        // Execute graphQL query
        ctx := context.WithValue(r.Context(), core.UserIDKey, 3) // whatever
        res, err := sg.GraphQL(ctx, rBody.Query, nil)
        // check err

        // render.JSON comes from the chi/render package and handles
        // marshalling to json, automatically escaping HTML and setting
        // the Content-Type as application/json.
        render.JSON(w, r, res.Data)
    }
}

func main() {
    dbConn, err := sql.Open("pgx", "DB_URL")
    // check err

    sg, err := core.NewSuperGraph(nil, dbConn)
    // check err

    router := chi.NewRouter()

    router.Group(func(r chi.Router) {
        router.Post("/graphql", sgHandler(sg))
    })

    server.Start(router)
}

// Some code from https://medium.com/@bradford_hamilton/building-an-api-with-graphql-and-go-9350df5c9356

it works (although now I have to fully understand how SuperGraph works).

  • Do you have any advice to give me?

  • Anything more solid for future scaling?

#2

For point number 2 (How to integrate SuperGraph (especially for CRUD) into an existing Go project that already uses GraphQL) I don't really know how to do, I have an idea that could solve: a chain of middlewares, but I still have to understand well; I'll try to explain myself with an example:

func main() {
  // initialization... see #1
    router.Group(func(r chi.Router) {
        router.Post("/graphql", superGraphOrSecondHandler())
    })
}

func superGraphOrSecondHandler() {

  // if SuperGraphHandler is

    err != nil && err == supergraph.ErrQueryNotFound // I'm just imagining

  // I can call the second graphQL handler with

    next()
}
  • Is this a good way of doing it in your opinion?

  • Is there a type of error that I can already use for this case (when I can't find the query in the allow list)? Or should I simply check the error string?

#3

For point number 3 (how to perform other actions (call other code/packages) before, during or after SuperGraph operations (the so-called "actions" of Hasura and other similar projects)) I don't really have good ideas. And this is the point that scares me most of all.

I read https://github.com/dosco/super-graph/issues/69. I think @howesteve had a good idea, although this example clarified my doubts.

I thought of something like this:

func httpHandler(w, r) {
  ...read in json
  ...validate json
  ...call core.GraphQL(context, query, validated_json)
  // my idea here: check if this just finished query is followed by an "action"/code to call
  query_name := core.Name() // https://pkg.go.dev/github.com/dosco/super-graph/core?tab=doc#Name
  query_operation := core.Operation() // https://pkg.go.dev/github.com/dosco/super-graph/core?tab=doc#Operation
  ...checkForActionsAndDo(query_name, query_operation)
  ...return output to user
}
  • Is this a good way of doing it in your opinion? What am I doing wrong?

Abstract Factory vs multiple Factory Methods

I am writing a library to GET data from two different stock-market servers (REST) and clean the data. The API servers have different end-points and they do not return the data in in similar formats which means data-cleaning has to be performed on it.


Abstract factory method:

class StockMarketFactory(ABC):
    @abstractmethod
    def create_stock_market_requestor(self) -> AbstractMarketRequestor:
        pass

    @abstractmethod
    def create_data_cleaner(self) -> AbstractDataCleaner:
        pass

class ConcreteMarketRequestorFactory(StockMarketFactory):
    def create_stock_market_requestor(self) -> ConcreteMarketRequestorA:
        return ConcreteMarketRequestorA()

    def create_data_cleaner(self) -> ConcreteMarketCleanerA:
        return ConcreteMarketCleanerA()


class ConcreteFactory2(StockMarketFactory):
    def create_stock_market_requestor(self) -> ConcreteMarketRequestorB:
        return ConcreteMarketRequestorB()

    def create_data_cleaner(self) -> ConcreteMarketCleanerB:
        return ConcreteMarketCleanerB()


class AbstractMarketRequestor(ABC):
    @abstractmethod
    def get_historical_data(self) -> str:
        pass

class ConcreteMarketRequestorA(AbstractMarketRequestor):
    def get_historical_data(self) -> str:
        return "The result of the Market A1."


class ConcreteMarketRequestorB(AbstractMarketRequestor):
    def get_historical_data(self) -> str:
        return "The result of the Market A2."


class AbstractDataCleaner(ABC):
    @abstractmethod
    def clean_and_manipulate_data(self, *args, **kwargs) -> None:
        pass

class ConcreteMarketCleanerA(AbstractDataCleaner):
    def clean_and_manipulate_data(self, historical_data):
        print(f"Historical data is being cleaned on A")


class ConcreteMarketCleanerB(AbstractDataCleaner):
    def clean_and_manipulate_data(self, historical_data):
        print(f"Historical data is being cleaned on B")


def client_code(factory: StockMarketFactory) -> None:
    market_a = factory.create_stock_market_requestor()
    historical_data = market_a.get_historical_data()
    cleaner_a = factory.create_data_cleaner()
    cleaner_a.clean_and_manipulate_data(historical_data)


It could also be achieved using 2 different "Factory Methods":

  1. For requesting the market for data
  2. For cleaning the data

From a design perspective, the abstract factory method seems elegant. However, the factory methods would make it easier to understand. Are these my best options or are there some other design patterns that I could use?

TypeScript: Return type of combined generic type is always unknown

I want to create a settings store. The user can add a setting with a value of any type. Then he can retrieve a value and get it correctly typed.

My thinking was: this sounds like connected generic type arguments. The type of the result is dependent on the type of the argument to the getSetting() method. So I tried creating said getSetting() method such that it takes a type as input, and based on that type it should be able to infer the return type. This approach uses the type as a key to get the correct information.

Below is my current approach. It seems to be somewhat close to what I want, but the return type of getSetting is always unknown. In the example I would expect it to be number, though.

abstract class Setting<T> {
  abstract value: T;
}
class SD extends Setting<number> {
  value = 0;
}

let getSetting = <T extends Setting<K>, K>(type: new () => T): K => {
  // return value somehow
};

let setting = getSetting(SD); // type of setting is unkown instead of number

Where is my error? Or is there a completely different way to achieve something like this?

Usefullness of Python Transformer Exception Pattern?

I was reading up on the various error-handling patterns and I came across the so-called "Transformer" pattern. It's exemplified as such:

try:
    something()
except SomeError as err:
    logger.warn("...")
    raise DifferentError() from err

Why would you want to do this? Why not just use DifferentError from the start? An example of this being needed may help.

Java - Infinite Loop Factory Pattern Problem in Running Project

DataModel

EvaluationObject has a Many to Many relationship with itself that this makes Infinite Loop in run code by using Factory Pattern How to prevent Infinite Loop for this datamodel ?

sample :

public class EvaluationObjectDtoToEntityMapperFactory {
public EvaluationObjectDtoToEntityMapper get(){
     EvaluationObjectAssociationDtoToEntityMapper evaluationObjectAssociationDtoToEntityMapper = new EvaluationObjectAssociationDtoToEntityMapperFactory().get();
        EvaluationObjectTypeRepository evaluationObjectTypeRepository = new EvaluationObjectTypeRepositoryFactory().get();
        return new EvaluationObjectDtoToEntityMapperImpl(evaluationObjectAssociationDtoToEntityMapper,evaluationObjectTypeRepository);
    } 

}

sample :

public class EvaluationObjectAssociationDtoToEntityMapperFactory {
public EvaluationObjectAssociationDtoToEntityMapper get(){
        EvaluationObjectDtoToEntityMapper evaluationObjectDtoToEntityMapper = new EvaluationObjectDtoToEntityMapperFactory().get();
        return new EvaluationObjectAssociationDtoToEntityMapperImpl(evaluationObjectDtoToEntityMapper);
}

}

console: output

vendredi 26 juin 2020

UML Design Pattern and implementation into C++ classes

I am trying to learn Adapter Design Pattern UML with C++ and in one of the videos in youtube displayed this content - my issue is translating the UML picture to C++ class / code:

enter image description here

What I really get confused is:

  1. The Clinet -------> [solid line] association to interface Target. What does this means generally I have seen classes implementing interface something like Adapter class implementing Target

  2. What does the content Adapter is composed with the adaptee means here - if it is containership then does it completely or partially owns it?

Below is the code implementation that I can think of it:

class Target
{
public:
 void virtual ServiceA() = 0;
}; 

class Client : public Target
{
public:
Client(){}
void ServiceA() override {}
};

class Adaptee
{
public:
Adaptee(){}
void ServiceX(){}
};

class Adapter : public Target
{
public:
Adapter(){}
void ServiceA() override {adaptee.serviceX();}
Adaptee adaptee;
};

int main()
{
.....
}

How inside main we would code up? Please explain.

How can I avoid duplicate switch statements

I have an enum of phone conditions. At one point in my application I need to update a price based on the condition of the phone, e.g.

switch (condition)
{
    case Condition.Good:
        price = goodPrice;
        break;
    case Condition.ScreenCrack:
        price = screenCrackPrice;
        break;
    case Condition.CameraCrack:
        price = cameraCrackPrice;
        break;
    case Condition.BadBattery:
        price = badBatteryPrice;
        break;
    case Condition.ScreenCrack | Condition.CameraCrack:
        price = screenCrackCameraCrackPrice;
        break;
    case Condition.ScreenCrack | Condition.BadBattery:
        price = screenCrackBadBatteryPrice;
        break;
    case Condition.CameraCrack | Condition.BadBattery:
        price = cameraCrackBadBatteryPrice;
        break;
case Condition.ScreenCrack | Condition.CameraCrack | Condition.BadBattery:
        price = screenCrackCameraCrackBadBatteryPrice;
        break;
}

Later on, the user may want to edit the price associated with that same condition. How can I do this without making another switch statement?

Interface which just groups objects of implementations of other interfaces

I'm working on a project (a framework) and at some point I found myself surrounded by couple of interfaces which serve only one purpose: to unite several objects into a kind of group. For example:

interface-group 1 interface-group 2

Also soon I will get an important interface which represents the framework. And that interface will look like this (a kind of Locator but with explicit service-returning-methods declaration (and with grouping of these services)):

interface Framework {
    GroupOfServices1 getGroupOfServices1();

    GroupOfServices2 getGroupOfServices2();

    GroupOfServices3 getGroupOfServices3();

    ...
}

I do know that these interfaces violate ISP (but I believe it's acceptable trade-off (at least relatively to framework-class)), but I don't know whether they violate SRP or not? According to Robert Martin's "Clean Architecture" SRP is violated when several groups of people can want to change the same class. So from this viewpoint SRP isn't violated, because changes to my "group-classes" can be done only by person (or group of persons) who groups services (or something) in these classes.

And with all that I'm curious are these classes well-designed (or at least is their design worth it)?

P.S. By the way maybe there's a pattern/antipattern which I unknowingly implemented. If it is, what is it?

Pattern "allocate memory or use existing data"

I have field
std::map<std::string, std::map<unsigned int, float>> widths;

I copy data to widths[key] from another map or insert custom data to widths[key] depending on runtime criteria. However, copying is too slow. I am going to use pointer to std::map<unsigned int, float> as widths::value. Thus(depending on runtime criteria):

  1. Pointer has address of existing map.
  2. Allocate memory and write custom data.

Also I need flags to decide if delete widths::value in destructor. Do you know better pattern to resolve this task?

Design pattern / Data structure for a sub-set of data/errors

Several times, I had to return this kind of data structure from a search web service:

[
    {
        "zipCode": "unique criteria", // XOR
        "city": "unique criteria",
        "data": [
            {
                "firstName": "firstName1",
                "lastName": "lastName1"
            },
            {
                "firstName": "firstName2",
                "lastName": "lastName2"
            },
            
            // ....
        ],
        "errors": [
            {
                "code": "ERR_01"
                "message": "Unable to get user 3"
            },
            {
                "code": "ERR_01"
                "message": "Unable to get user 4"
            },
            {
                "code": "ERR_02"
                "message": "Missing required info for user 5"
            },
            
            // ...
    },
    
    // ... (different value for zipCode or city)
]

Note: There is either: zipCode or city but not both. The values are unique.

On the business code I don't know the best way to handle a set of elements/errors.

Currently I plan using a Map with zipCode or city as the key since it is easily distinguishable and the values unique. Full type: Map<String, Set<? extends IFailableData>>. Sadly, IFailableData will be a marker interface (in this case, is this "anti-pattern" relevant?).

           +---------------+
           | IFailableData |
           +---+---------+-+
               ^         ^
               |         |
+--------------+--+   +--+---------+
| SingleErrorImpl |   | SingleData |
+-----------------+   +------------+

Are there design patterns that can solve this common problem or Java helper classes (eg. Optional<?>)?

Thanks in advance.

C# async decorator best practices

I have simple asynchronous service, which I need to decorate.

What is the best practice when you decorate an asynchronous method?

  • should I use async/await in the decorator? Example1

  • should I leave it as Task<> and use await only on the original caller?

Example

public interface IService
{
    Task<bool> GetStatusAsync();
}

public class Example1 : IService
{
    private readonly IService _decorated;
    public Example1(IService decorated)
    {
        _decorated = decorated;
    }

    public async Task<bool> GetStatusAsync()
    {
        // extra code

        return await _decorated.GetStatusAsync();
    }
}

public class Example2 : IService
{
    private readonly IService _decorated;
    public Example2(IService decorated)
    {
        _decorated = decorated;
    }

    public Task<bool> GetStatusAsync()
    {
        // extra code

        return _decorated.GetStatusAsync();
    }
}

jeudi 25 juin 2020

Synchronization of Events

I have some procceses using event-driven architecture that sends a random number of events at the beginning of the processing. Althout, in a certain point of the business I need to check if all of those events ended their processing. Considering that I need to keep the idenpotency of each step of the processing, is there a design pattern that I can use to achieve this?

packing a nested packed structs in a flat buffer in c++

I have something like the following code in my code base.

struct Data {
    int metadata_;
    int data_[3];
} __attribute__((__packed__));

struct GroupData {
    int metadata_;
    Data points_[4];
} __attribute__((__packed__));

struct Container {
    int metadata_; // encodes data about number clouds, and points
    GroupData point_clouds_[];
} __attribute__((__packed__));

I am tasked to design the code such to support varible size of data and points in my Data and GroupData structs with the following requirements.

  1. the container must remian POD (no cost serialization and deserialzation since we send this data over network very frequently)
  2. it must be as fast as possible, cost of adding virtual function and using type erasure maybe too much.
  3. sender of the data knows the size of data and points at compile time
  4. receiver on the other hand, can only parse this sizes from the metadata of Container, and should be able to easily consume this.

I have a couple of ideas on how to approach this problem, however each technique comes with some major drawbacks, I was wondering if someone with more experience would have a better solution to the problem?

template the sizes

template <int N>
struct Data {
  int data_[N];
  ///...
};

template <int N, int M>
struct GroupData {
  Data<M> points_[N];
  ...
};

struct container {
  int metadata_;
  uint8_t bytes[];

  template <int N, int M>
  gsl::span<GroupData<M, N>> points() {
    return //...
  }
};

pros: great for sender cons: ugly for receiver, since it doesn;t know the sizes at compile time.

flexible member arrays

struct Data {
  int metadata_;
  int data_[];
} __attribute__((__packed__));

struct GroupData {
  int metadata_;
  Data points_[];
} __attribute__((__packed__));

struct Container {
  int metadata_;  // encodes data about number clouds, and points
  uint8_t point_clouds_bytes_[];
  // custom iterator, custom operator to access the data based on the size
  // available at run time.
} __attribute__((__packed__));

pros: it removes the size templates requirements for receiver cons: everything else, size of the structs are not known at copile time, span can not be used, iterators wouldn;t work, everything has to be handled maually.

https://godbolt.org/z/cfF_6H

React Hooks: Pitfalls with this Global State pattern?

I'm starting to dive into hooks and to get a better understanding of them I am attempting to supply global state to my application where appropriate. I followed a few tutorials but nothing was producing the desired outcome I wanted from an aesthetic and functional point of view. The issues mostly stemmed around my data being from an API endpoint, where all the tutorials were demonstrating with static data. I landed on the following, and although I've confirmed it works I'm concerned there may be pitfalls that I'm not anticipating.

Before trying to shim this into a real world application where there may be repercussions that I don't find until much later in the build process I was hoping you fine folks could look it over and let me know if there's anything that stands out as being an antipattern. Specifically, I'm looking to see if there are side effects this pattern would produce that would be undesirable, such as extensive loading, infinite loops, data dead zones, ect. once scaled.

Within my /store.ts file I'm creating the general store context:

import React from 'react';

export const catFactsStore = React.createContext<{ state: {}, dispatch: any }>({ state: {}, dispatch: {} })

Within /providers/CatFactsProvider I'm passing the state as well as a dispatcher for a useReducer hook. The useReducer will allow me to set the current value of the state based on its current lifecycle:

import React, { useReducer } from 'react'
import { catFactsStore } from '../store'

const CatFactsProvider: React.FC = ({ children }): JSX.Element => {
  const [state, dispatch] = useReducer(
    (state: any, action: any) => {
      switch (action.type) {
        case 'loading':
          return { ...state, isLoading: true, hasErrored: false, entities: {} }
        case 'success':
          return { ...state, isLoading: false, hasErrored: false, entities: action.payload }
        case 'error':
          return { ...state, isLoading: false, hasErrored: true, errorMessage: action.payload }
        default:
          throw new Error()
      }
    },
    { entities: {}, isLoading: false, hasErrored: false, errorMessage: '' },
  )

  return <catFactsStore.Provider value=>{children}</catFactsStore.Provider>
}

export { catFactsStore, CatFactsProvider }

In index.tsx I'm wrapping my App component with the Provider to make it globally available.

import React from 'react'
import ReactDOM from 'react-dom'
import App from 'src/components/App'
import { CatFactsProvider } from './providers/CatFactProvider'

ReactDOM.render(
  <CatFactsProvider>
    <App />
  </CatFactsProvider>,
  document.getElementById('root'),
)

Then I'm creating a higher order component in /components/hoc/withCatFacts to make the actual API request to retrieve the data. The HOC is responsible for dispatching to my reducer and supplying the state to its child components:

import React, { useLayoutEffect, useContext } from 'react'
import { catFactsStore } from '../../store'
import axios from 'axios'

export interface WithCatFactsProps {
  catFactsState: { entities: {}; isLoading: boolean; hasErrored: boolean; errorMessage: string }
}

export default <P extends WithCatFactsProps>(
  ChildComponent: React.ComponentType<P>,
): React.ComponentType<Omit<P, keyof WithCatFactsProps>> => {
  const CatFactsFetcherHOC: React.FC<WithCatFactsProps> = (props): JSX.Element => {
    const { state, dispatch } = useContext(catFactsStore)

    // useLayoutEffect to ensure loading is dispatched prior to the initial render
    useLayoutEffect(() => {
      dispatch({ type: 'loading' })
      axios
        .get('https://cat-fact.herokuapp.com/facts')
        .then((response) => {
          dispatch({ type: 'success', payload: response.data.all })
        })
        .catch((e) => {
          dispatch({ type: 'error', payload: e.message })
        })
    }, [dispatch])

    return <ChildComponent {...(props as P)} catFactsState={state} />
  }

  return CatFactsFetcherHOC as any
}

Finally, within the /components/App.tsx file I'm wrapping my export with withCatFacts and utilizing the data to display in my app:

import React from 'react'
import withCatFacts, { WithCatFactsProps } from './hoc/withCatFacts'

interface Props {}
type CombinedProps = Props & WithCatFactsProps

const App: React.FC<CombinedProps> = ({ catFactsState }): JSX.Element => {
  if (catFactsState.isLoading) {
    return <div>LOADING</div>
  }
  if (catFactsState.hasErrored) {
    return <div>{catFactsState.errorMessage}</div>
  }
  console.log(catFactsState) // Can successfully see Cat Facts, Huzzah!
  return <div>Cat Facts!</div>
}

export default withCatFacts(App)

Any suggestions or comments would be appreciated. With my hook knowledge being limited I don't know what I don't know and would like to catch any problems before they occur.

How to make sure that the implementation objects for an interface should only be created by implementation instances of another interface?

I have a set of data model classes, e.g. DataModel1, DataModel2 and so on. The parameters that are part of each data class are totally different. The only thing common about these data classes is the objects which are going to use their values. I have an interface 'Investigator', and only different implementation of these Investigator can use different type data of above model classes.

Initially I was having an empty interface for all data classes, like this

public interface DataModel {}

But then I realised that my scenario fits the visitor pattern. So, I made changes as below: I now have a DataModel interface

public interface DataModel {
    void accept (Investigator investigator)
}

public class DataModel1 implements DataModel {
    private String attribute1;
    private String attribute2;

    @Override
    void accept (Investigator1 investigator) {
        investigator.investigate(this);
    }

}

public class DataModel2 implements DataModel {
    private String attribute3;
    private String attribute4;

    @Override
    void accept (Investigator2 investigator) {
        investigator.investigate(this);
    }

}

and an Investigator interface:

public interface Investigator {
    void investigate(DataModel dataModel);
}

public class Investigator1 implements Investigator {

    @Override
    void investigate (DataModel dataModel) {
        // do some investigations of Type 1 here
    }

}

public class Investigator2 implements Investigator {

    @Override
    void investigate (DataModel dataModel) {
        // do some investigations of Type 2 here
    }

}

Now, for any kind of investigator and data model implementations, I just have to do:

dataModel.accept(investigator)

and the correct type of investigation will be done.

Now, my problem comes when I want to actually return a result from the investigation that was done. Similar to above requirements, an Investigator can return different types of InvestgationResult, so I have the interface and its implementations:

public interface InvestigationResult {
}

public class InvestigationResult1 implements InvestigationResult {
    public String investigationText1;
    public String detailedResults1;
}

public class InvestigationResult2 implements InvestigationResult {
    public String investigationText2;
    public String detailedResults2;
}

and the Investigator interface be changed to:

public interface Investigator { InvestigationResult investigate(DataModel dataModel); }

Requirement here is that an instance of a InvestigationResult should only be created by an Investigator class. My question here is that I don't want the 'InvestigationResult' interface to be am empty interface, but I am not very sure what common method it should contain? Any help is appreciated.

PHP Design Pattern for checking if a class should be executed

I've developed a Laravel-based app that sends out various emails such as informing users of new jobs as well as new messages.

I have created all the necessary Mail classes. We now want to create a database column that will allow individual users to set whether they want to receive those notification emails or not.

When a user performs an action that would normally send out an email, I want the system to check if the user wants to receive those emails based on their settings in the database. I don't want to wrap all calls to email, in the code, with unnecessary if() functions.

Is there a preferred design pattern that I could use to handle this?

mercredi 24 juin 2020

Calling suit method based on parameter type (when parameter is general or specific)

How to call method with specific type instead of general type if I have two methods?

I prepared two examples: simple and extended.


Simple example:

public class Testing {

    static void process(Object object) {
        System.out.println("process Object");
    }

    static void process(Integer integer) {
        System.out.println("process Integer");
    }

    public static void main(String[] args) {
        Object objectString = new String("a");
        Object objectInteger = new Integer(1);

        process(objectString); // "process Object"
        process(objectInteger); // it prints "process Object" instead of "process Integer"
    }
}

I know I can create reference with specific type:

Integer objectInteger = new Integer(1);

and suit method will be called.

But I want to use general type (it's good practice to do List<String> list = new ArrayList<>() instead of ArrayList<String> list = new ArrayList<>()).


Extended example:

public class Testing {

    interface MyInterface {
    }
    static class First implements MyInterface {
        String first = "first";
    }
    static class Second implements MyInterface {
        String second = "second";
    }
    static class SpecificSecond extends Second {
        String specificSecond = "specificSecond";
    }

    public static void process(MyInterface myInterface) {
        if (myInterface instanceof First) {
            System.out.println("General case: " + ((First) myInterface).first);
        } else if (myInterface instanceof Second) {
            System.out.println("General case: " + ((Second) myInterface).second);
        } else {
            System.out.println("Should not call");
        }
    }

    public static void process(SpecificSecond specificSecond) {
        System.out.println("Specific case for SpecificSecond: " + specificSecond.specificSecond);
    }

    public static void main(String[] args) {
        MyInterface first = new First();
        MyInterface second = new Second();
        MyInterface specificSecond = new SpecificSecond();

        Testing.process(first); // "General case: first"
        Testing.process(second); // "General case: second"
        Testing.process(specificSecond); // it prints "General case: second" instead of "Specific case for SpecificSecond: specificSecond"
    }
}

I know I can do:

SpecificSecond specificSecond = new SpecificSecond();

but without using my interface I can't use my other generic methods and classes.

How can I change methods process (but without changing contract) to call proper method?

I found workaround (create new proxy method for choosing proper method and change name of general method):

public static void process(MyInterface myInterface) {
    if (myInterface instanceof SpecificSecond) {
        process((SpecificSecond) myInterface);
    } else {
        processGeneral(myInterface);
    }
}

private static void processGeneral(MyInterface myInterface) {
    if (myInterface instanceof First) {
        System.out.println("General case: " + ((First) myInterface).first);
    } else if (myInterface instanceof Second) {
        System.out.println("General case: " + ((Second) myInterface).second);
    } else {
        System.out.println("Should not call");
    }
}

private  static void process(SpecificSecond specificSecond) {
    System.out.println("Specific case for SpecificSecond: " + specificSecond.specificSecond);
}

But with this I can't find all uses of specific process(SpecificSecond) method (because they all pass through proxy method) in my IDE.

Is there any other workaround to enforce calling process(SpecificSecond) method?

How can I design it better?

mardi 23 juin 2020

Java, Business Logic Encapsulation: Utility vs Inner vs Pojo

I have gone through similar questions on this site and stackoverflow.com, but because I am still curious and want to cover all possible spectrums of this design, I am asking this question.

I am designing a new system and have lots of questions in my mind about which design works best. I have seen approach #1 and #3 used a lot, but not #2, although it is what I prefer because it keeps my code clean and properly encapsulated.

If you look close enough, there are 3 variations of methods, which can fall in all 3 approaches. computePrice for example, is suitable for #3 (BookService.class), but isGraycale for #1.

1:

class Book {
    // getters, setters
    
    public void addTOC(TOC toc) {}
    public boolean isGrayscale() {}
    public int computePrice(Conditions c) {}
}

book.addTOC(toc);

2:

class Book { 
    // getters, setters
    
    class Service {
        public void addTOC(TOC toc) {}
        public boolean isGrayscale() {}
        public int computePrice(Conditions c) {}
    }
}

book.service().addTOC(toc);

3:

class BookService {
    static void addTOC(Book b, TOC toc) {}
    static boolean isGrayScale(Book b) {}
    static int computePrice(Book b, Conditions c) {}
}

BookService.addTOC(book, toc);

how can i unshuffle function in python by the pattern of list?

o is the standard of pattern to un_shuffle

o = [2,1,3,0]
a = 'abcd'

def un_suffle(s,o):
   s = 'bcda'
   return ''.join([s[i] for i in o])
print(un_suffle(s,o))

my output is:

dcab # i want to make it abcd in output

NodeJS Service Layer asynchronous communication

If I have to invoke ServiceB.action as a result of ServiceA.action being invoked, should I call ServiceB.action from ServiceA.action at the appropriate time, or should I emit an event from ServiceA and let ServiceB react to that event?

I can use an EventEmitter, but it works synchronously, in a sense that the callbacks are invoked sequentially without waiting the previous to resolve, which is ok for me. What isn't, though, is that the $emit will not wait until all of the listeners have resolved.

For a more real world scenario, lets assume that I have a Subscription service, and when a new subscription is created, the Email service needs to know about it so that it can notify somebody by email.

const SubscriptionService = {
  async create(user) {
    await Subscription.create(user)
   
    // Notify email service
  }
}

const EmailService = {
    async notify(user) {...}
}

One way I could do it, is call the EmailService.notify(user) from SubscriptionService.create and pass in the user.

Another way I could do it is with an event emitter

async create(user) {
    await Subscription.create(user)

    Emitter.$emit('subscription', user)
}

The second approach seems clean, because I'm not mixing things together, the notifications happen as a result of the subscription being created and the create method is not polluted with extra logic. Also, adding more side-effects like the notification one would be simpler.

The subscription service's create method, however, will not wait until all of the listeners have resolved, which is an issue. What if the Notification fails? The user will not get the email, in this scenario. What about error handling? In the first scenario I can handle the errors on spot when I invoke the EmailService.notify, but not with the emitter.

Is not meant for similar use-cases or am I looking at the problem in a wrong way?

What is the correct pattern for making sure the state is current before submitting data

I'm using state to store and pass the values of inputfields. And also to signal when to upload data.

state: { value: 123, upload: false }

componentDidUpdate() {
  if(this.state.upload) {
    this.setState({ upload: false });
    axios.post(this.state.value) //simplified  
  }

}

<input onChange={(e) => this.setState({ value: e.currentTarget.value * 2})} /> //Has to be controlled component

<button onClick={() => this.setState({ upload: true}) />

Now a user types something into the input, and clicks the submit button. Both events fire, async.

  1. How do I make sure that the upload uses the current content of the input? The inputs onChange event could fire after the onClick.

  2. How do I make sure upload doesn't get happen twice, once from the button click and then from the onChange before upload is set to false again?

Cast two interfaces that have same methods but different namespaces to one generace class/interface

I have to different logging services that implement the exact same methods, however, they have different namespaces.

package com.first.namespace
public interface loggerA
{
 void info();
 void warn();
 void debug();
 void error();
}

package com.second.namespace
public interface loggerB
{
 void info();
 void warn();
 void debug();
 void error();
}

and I have a DB class that must use a logger.

public class DB{

private MyCustomLogger logger;
public DB(MyCustomLogger log){
logger = log;

}
}

And finally I have two different services:

public class serviceA{

@inject 
private LoggerA logger;

private DB myDB;

public serviceA(){
       myDB = new myDB(??); // How can I pass/cast the logger properly here.???
}

}


public class serviceB{

@inject 
private LoggerB logger;

private DB myDB;

public serviceB(){
       myDB = new myDB(??); // How can I pass/cast the logger properly here.???
}

What is the best solution to pass/cast each of those different loggers properly to myDB class that has a unique logger parameter?

Note that I have not created yet MyCustomLogger, I am still searching the best way to do write this class or to get rid of it, if there is a better solution.

Apply solid principle without too much repetition of codes?

I have tried to practice solid principle using some simple classes. Basically I want to grab a few fields from product A and product B to fit into a general class Product. And I want to be able to calculate the price based on currency. I devide the GetInUSDollars() in separate as I want to leave the possibility for more currencies without changing the exising class. But try to use a single class for one function seems to create so much duplicates. Any direction I should go for to reduce the amount of duplicates?

public class ProductAData:IProduct
    {
        public List<Product> GetAll()
        {
            return (from n in new ProductARepository().GetAll()
                    select new Product { Id = n.Id, model = n.Model, Price = n.Price, Type = "ProductA" }).ToList();
        }
    }
public class ProductADataInUSDollars: IProductInUSDollars
    {
        public List<Product> GetInUSDollars()
        {
            return (from n in new PhoneCaseRepository().GetAll()
                select new Product { Id = n.Id, model= n.Model, Price = n.Price * 0.85, Type = "ProductA" }).ToList();
        }
    }

There is another class that should fit into Product class as well.

public class ProductBCaseData : IProduct
{

    public List<Product> GetAll()
    {
        return (from n in new ProductBRepository().GetAll()
                select new Product { Id = n.Id, model= n.Model, Price = n.Price, Type = "ProductB" }).ToList();
    }

}
public class ProductBDataInUSDollars: IProductInUSDollars
        {
            public List<Product> GetInUSDollars()
            {
                return (from n in new ProductBRepository().GetAll()
                    select new Product { Id = n.Id, model= n.Model, Price = n.Price * 0.85, Type = "ProductB" }).ToList();
            }
        }

Operating systems Synchronization problem [closed]

I am new to programming and computer systems.I found this question in an old textbook and I am really interested in it, yet finding it difficult. If anyone could help with any pointers or psudo-code to work out the problem.

Question 10:

A harbour serves two purposes for passing ships: a loading/offloading dock for cargo ships, and a maintenance dock for service and repair of cargo ships.

There is one two-lane channel leading from the ocean to the harbour: one for incoming ships, and one for outgoing ships. Two tug-boats patrol the channel : one for ships that are waiting to come into the harbour to load/offload, and one to lead ships from the maintenance dock back to sea. Each lane can, therefore only service one ingoing ship and one outgoing ship at a time.

The loading dock can host five ships at a time, and there are three fork-lifts to do the work, so three ships can be loaded/unloaded simultaneously. Fork-lifts either load/unload or they are parked.

With the reasoning that servicing will be quicker than loading, the maintenance dock can host three ships for repair, service, or bypass (nothing required). There is only one team of mechanics, so one ship can be serviced/repaired/bypassed at a time. The mechanics either service/repair/bypass, or they rest. There is a single-lane channel from the loading dock to the maintenance dock.

All ships enter to: load/offload, and then service/repair. i.e. a ship enters, goes to loading dock, goes to maintenance dock, and then exits the harbour.

Model the above synchronization problem as FIVE processes:

  1. a ship

  2. incoming tug-boat

  3. a fork-lift

  4. the mechanic-team

  5. outgoing tugboat.

*Notes:Use semaphores and shared memory to model shared resources, and synchronized access to them

Python -Rest- Neo4j Clarifications/Best Practices

Currently I am trying out the following :

  1. Have RestAPI Server in python up and running ( could be using Django/Flask/FastApi etc)
  2. Based on the client requests, connect to Neo4j, get the desired data and return accordingly response to clients.

My questions are as follows :

  1. How to interact with Neo4j from server ? i.e. should I use OGM ( Object Graph Mapper) or run a query directly on Neo4j?
    • Pros/cons of each approach ?
    • How does each work when there are lots of client requests ?
  2. What is ideal design pattern to use while connecting to Neo4J database i.e should I use "Design to Interface" approach or "Object Pool Pattern" or "Singleton" or any other better design pattern?

NOTE: I have referred to some of the following links :

These examples just give a sample of how to do what .. What I am trying to understand is from best practices or best design pattern approach . There are too many contents that tend to confuse more than helping out.

Kindly help to clarify the same.

lundi 22 juin 2020

One parameter (@RequestParam String tab) - many methods

I get "tab" from front, his value can be 'profile', 'active', 'summary', 'votes' etc. Each value has its own method. How can I call a method based on the value of 'tab' without using switch and if. Are there any patterns for this case?

selenium webdriver can't find the alert box

I am using selenium webdriver , I have alert box displaying when clicking save and disappear after 5 minutes ,

Alert alert= driver.switchTo().alert(); 
alert.accept(); 

and then run the code, I am using the Selenium design pattern framework
this is the website image and code with error enter image description here

enter image description here enter image description here

Update : I tried to get close button by class and click it and works for me but till now can

Use of a class inside another class

I have got the following code:

.description p span {
  font-style: italic;
}
<div class="description">
  <p>This recipe is from one of my <span class="cor">favorite</span> cakes out there, really <span>delicious</span>...check it out below</p>
</div>

but I want the class in the first span tag to remove all text with italic to red

Method overriding in Typescript with different return types without hack

I am trying to use a class adapter pattern in typescript

class Source {
    getSomething(): TypeA
}

class Adapter extends Source {
   getSomething(): TypeB {
     const response = super.doSomething();
     // do something with the shape of response
     return response;
   }
}

Typescript is complaining that these two types are incompatible. I am not sure if this is something doable in Typescript without typehint any or union TypeA | TypeB. Imagine a scenario where I want the client code to be able to use both the Source and Adapter class and still be able to get proper type checks.

Thanks

stippling stiches graphics pattern generation inside polygon

i am working on a problem in which i have to generate a pattern simillar to the one given in the image polygon with sipple pattern inside it

enter image description here

i have tried many different ways, but none is working. i have seen some embroidery software which can generate this type of pattern, but i don't know the algorithm used to generate this patter. please help me, if someone know anything about the algorithm. Thank you!

dimanche 21 juin 2020

When and how to initialize (View)models using constructors with the aim to set all props of a object correctly and forget none

So I have this simple Edit action method which builds a viewmodel

public async Task<IActionResult> Edit(int id)
{
    var product = await _productRepo.Get(id);
    if (product == null) return RedirectToAction(nameof(Index));
    var categories = await _categoryRepo.Get();
    var suplliers = await _supplierRepo.Get(); ;
    var editVM = new EditVM()
    {
        Product = product,
        Categories = categories,
        Suppliers = suplliers
    };
    return View(editVM);
}

And for completeness here is the EditVM

public class EditVM
{
    public Product Product { get; set; }
    public IEnumerable<Category> Categories { get; set; }
    public IEnumerable<Supplier> Suppliers { get; set; }
}

I obviously use it to edit a product. So far so good.

Now I wanted to reuse this EditVM and my Edit.cshtml view for creating products so I created the Create action method

public async Task<IActionResult> Create()
{
    var categories = await _categoryRepo.Get();
    var editVM = new EditVM()
    {
        Product = Product(),
        Categories = categories
        //Notice I forget to initialize Suppliers here!!
    };
    return View("Edit", editVM);
}

I got this null error because I forgot to initialize the Suppliers prop in my Create action method. So I improved it by changing my EditVM to only be initialized with a constructor with the required params and set the props to private setters:

public class EditVM
{
    public EditVM(Product product, IEnumerable<Category> categories, IEnumerable<Supplier> suppliers)
    {
        Product = product;
        Categories = categories;
        Suppliers = suplliers;
    }

    public Product Product { get; private set; }
    public IEnumerable<Category> Categories { get; private set; }
    public IEnumerable<Supplier> Suppliers { get; private set; }
}

And now use it like:

public async Task<IActionResult> Edit(int id)
{
    var product = await _productRepo.Get(id);
    if (product == null) return RedirectToAction(nameof(Index));
    var categories = await _categoryRepo.Get();
    var suplliers = await _supplierRepo.Get();
    var editVM = new EditVM(product, categories, suppliers);
    return View(editVM);
}//And the same way in my Create action method

So now I can never forget to set anything and enforced the EditVM is always set with the required props. Is this style recommended? The EditVM is so plain simple...Its my expirience that when viemodels(or 'ajax return models' grow bigger programmers tend to forget some props. We can enforce this by using constructors with private setters or factories. Is this the right way to go? And in this case I just want to have a simple list with all the suplliers using _supplierRepo.Get() in my Create and my Edit action method. But what if I use a very complex query. Then I might want to pass in my repos as params to my EditVM constructor like this:

public EditVM(Domain.Product product, ICategoryRepo categoryRepo, ISupplierRepo supplierRepo)
{
    Product = product;
    Categories = categoryRepo.Get().Result;//My repos are async...
    Suppliers = supplierRepo.Get().Result;//Possible very complex query to be only done at one location
}

Any thoughts about my question are most welcome.