mercredi 30 novembre 2022

How to call a function that will create an object of a class if required?

Context:

I've found a bug in a selenium framework I'm working on, in which the Web Browser (at least Chrome) crashes unexpectedly with no notification.
As a patch, I'm reinitializing the WebDriver so it keeps working, but right now I'm creating a new EdgeDriver and I want to create a new WebDriver of the same type it was before (the one that crashed).

I came up with this approach:

driver = Map.of(
            ChromeDriver.class, getFunction(ChromeDriver.class),
            EdgeDriver.class, getFunction(EdgeDriver.class),
            FirefoxDriver.class, getFunction(FirefoxDriver.class),
            OperaDriver.class, getFunction(OperaDriver.class)
      ).entrySet().stream().filter((e) -> e.getKey().isInstance(driver))
      .map((e)->e.getValue().identity()).findFirst().orElseThrow(() -> new RuntimeException("WebDriver not detected"));

...

@SneakyThrows
static Function<Class<? extends RemoteWebDriver>, RemoteWebDriver> getFunction(Class<? extends RemoteWebDriver> driverClass){
   return c -> {
            try {
               return c.getConstructor().newInstance();
            } catch (IllegalAccessException | InstantiationException e) {
               throw new RuntimeException(e);
            }
         };
}

The problem is that I can't use this type of call

e.getValue().identity()

Do you know how can I achieve this?

I'm using the Map approach so I don't have to specify a bunch of if's with all the code inside.
And I'm using a separate method returning a Function so I don't have to spend resources in creating the instances before (and if they) are required.

I have faced this problem before and I'm pretty sure I'm going to keep facing it, I have almost no idea what I'm writing in the functional programming section because I'm very new to it. I hope I'm on the right track but honestly, I doubt it.

As an extra tip if you can provide a way to become an expert in functional programming in Java will be great because I've been looking for a course or any resources deep enough and I have not been able to find anything so far. Not only will solve this problem but it will help me to solve any future problems like this.

need a better way to validate fields in request body django depending on a specific field value

The requirement is to verify body fields in an api request depending on another field.

Like: the request data has a field:

action

If actions is deactivate then no other field should be present in the body data however if the action is anything else we want to allow updating other fields as well such as name.

currently we have a validation where we are going through the dictionary keys and comparing like below:

expected_keys = ['client_updated', 'updated_by', 'actions']
if key not in expected_keys:
    raise ValidationError("Deactivation action does not allow {} to be updated".format(key))

Just wanted to know if there is a better way to handle via django or django rest framework, with somewhat less harcoding.

Facade class implementation of 2 classes with almost same methods

I've you classes defined in different path with the same name defining almost same methods. I'm basically looking for a clean way to implement a Facade class for this scenario so that I don't have to apply switch statement to define the class. For instance I've these 2 interface defined

This is defined in xyz/V1/* public interface A {

    public abstract getService();

    public abstract void getVersion();
}

This is defined in xyz/V2/* public interface A {

    public abstract getService();

    public abstract void getVersion();

    public abstract void newMethodforV2();
}

Code I've implemented right now.

Constructor() {
    try {
        xyz.V2.A service = xyz.V2.A.getService();
        VERSION = 2;
    } catch (NoSuchElementException e) {
        try {
            xyz.V1.A service = xyz.V1.A.getService();
            VERSION = 1;
        } catch (NoSuchElementException f) {
                
        }
}
// For all function I've to do something similar
void doSomething() {
    switch (VERSION) {
        case 1:
            return V1.A.getService().doSomething()
        case 2:
            return V2.A.getService().doSomething()
        }
}

This is what something I'm looking to make it clean.

private A service;
Constructor() {
    try {
        service = xyz.V2.A.getService();
    } catch (NoSuchElementException e) {
        try {
            service = xyz.V1.A.getService();
        } catch (NoSuchElementException f) {
                
        }
}
// I want to implement something like this.
void doSomething() {
    service.doSomething();
}

I cannot modify classes/interface "A" here. Also is there a way I can define a class to do something like this

try {
    service = xyz.V2.A.getService();
} catch (NoSuchElementException e) {
     service = new V1toV2Facade(xyz.V1.A.getService());

SwiftUI how to make UI Responsiv

UI on iPhone Pro Max here the UI is not in the right place

UI on iPhone Pro thats perfectly

Hello I am new to SwiftUI and have a question. I had to implement the UI with the Star and the Number Count. I did everything, but when I switch the phones my UI is miss placed depends on the iPhone I choose. How can I fix that ? I search in the Internet for Responsiveness in SwiftUI but it didn't really helped me. I thought also that SwiftUI does most of the Responsiveness because I know in UIKIT you have to declare the constraints by yourself. Thanks for helping me, the Code is below. I also have after the CustomerCardPoints an List which works perfectly but since I added the CustomerCardPoints there is a small space between the Views, if anybody has experience how can I fix that also? (Not Necessary)

var body: some View {
        VStack(spacing: 0) {
             
                shopModel.logo
                    .resizable()
                    .aspectRatio(contentMode: .fit)
                    .frame(maxWidth: 200, maxHeight: 100)
                    .padding([.top, .leading, .trailing])
                
                Text(shopModel.name)
                    .fontWeight(.bold)
                    .padding()
                
            CustomerCardPoints()
            
            }


struct CustomerCardPoints: View {
    var body: some View {
            VStack(){
                ZStack() {
                    Image("Slice")
                        .resizable()
                        .aspectRatio(contentMode: .fit)
                        .frame(maxWidth: 180, maxHeight: 60)
                        .offset(x: 160, y: -127)
                    HStack(alignment: .firstTextBaseline) {
                        Text("22")
                            .font(.system(size: 19))
                            .fontWeight(.bold)
                            .foregroundColor(.white)
                            .offset(x: 237, y: -126)
                        Image("favoriten")
                            .resizable()
                            .aspectRatio(contentMode: .fit)
                            .frame(width: 110, height: 25)
                            .offset(x: 132, y: -120)
                        
                    }
                }
                
            }
        }
    }

Laravel - What data should be sent from the controller to the service?

I wonder whether it is good to pass on the requestobject to a separate service after successful data validation or whether I should only pass on the data. Is there a clear statement regarding SOLID or does it not matter? My feeling is that you should only give the service what it needs.

public function store(Request $request)
{
    $someService = new SomeService;
    return $someService->create($request);
}

// or 

public function store(Request $request)
{
    $someService = new SomeService;
    return $someService->create($request->post());
}

mardi 29 novembre 2022

design thoughts on a physical simulation

I'm basically new to OOP and besides a few programming basics in C++ have no experience whatsoever. For a college project I'm working on a physical simulation of the magnetic interactions of multiple protons.

My goal is to learn as many concepts and aspects to programming and apply those to my system. So what Ive been doing so far is reading into different design patterns and generally on how to approach such a project. Which only expanded my list of questions :D

I'm currently working of my class diagram. Basically my idea was to create a physObject class that implements different behaviour-interfaces. So in my case, all the Protons will implement MagneticBehaviour. I wanna try to create my design as loosely coupled as possible because I wanna provide reusability and flexibility. Later on it should be possible adding i. e. GravitationalBehaviour to simulate the gravitational behaviour of physical objects.

Model class diagram

This is my scetch of a class diagram. As I said I've tried to encapsulate the different variables needed into objects and applied the strategy pattern to make the calculations flexible based on the context of the simulation.

What I dont get is how to connect the classes. I.e. for the caclulation of the ActingBField, however that will be implemented, you'll need information of the distances to other physObjects. Also each time i.e. the location of a physObject changes, the ActingBField has to be calculated on every phsyObject that exists.

So it seems like I'll need to have a system, that automatically passes information within objects, if the value of an object changes. Which will kind of be a recursive pattern. So my first approach was to make physObject an Observable and every Behaviour-interface will be an Observer observing the variables needed. Then I've read into event-/ case-/ state-driven programming (not sure about the difference), which seems like a nice approach. I have no idea though how I would even visualize that kind of system in an uml diagram tbh.

Last but not least, all I've been doing so far is focus on the physical model of the simulation. However I figured I'll need to find a way to connect this model with some kind of user, that i.e. sets the time period of the simulation or selects which data to look at. How would that connection look like?

I'm really happy for any help, even a concept to look at would help tremendously since I'm really struggling to find any information.

Thanks for reading :)

Can I understand that there is exact word (whatever text) in the line, without the string.h library? [duplicate]

I have a text file myfile.txt, and I want to know if there is a line with "ksdjfhksjdfh"-pattern. Can I do that without <string.h> library? How?

Thank you.

I can get any line of the myfile.txt but do not know what to do next.

lundi 28 novembre 2022

Modify functionality of Parent class without rewrite in java

Let's say I have an abstract class, called Logger:

public abstract class AbstractLogger {
public enum Levels {
    DEBUG, INFO, WARNING, ERROR
}

public void debug(String message) {
    Levels level = Levels.DEBUG;
    log(level, message);
}

public void info(String message) {
    Levels level = Levels.INFO;
    log(level, message);
}

public void warning(String message) {
    Levels level = Levels.WARNING;
    log(level, message);    }

public void error(String message) {
    Levels level = Levels.ERROR;
    log(level, message);    }

public void log(Levels level, String message) {}

}

And I also have classes that inherit this class, such as FileAppenderLogger:

public class FileAppenderLogger extends AbstractLogger {
private final Path logPath;

public FileAppender(Path logPath) {
    this.logPath = logPath;
    createLogFile();
}

private void createLogFile() {
    try {
        File logFile = new File(logPath.toString());
        if (logFile.createNewFile()) {
            System.out.println("File created: " + logFile.getName());
        } else {
            System.out.println("File already exists.");
        }
    } catch (IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
}

@Override
public void log(Levels level, String message) {
    try {
        FileWriter myWriter = new FileWriter(this.logPath.toString());
        myWriter.write(message+"\n");
        myWriter.close();
        System.out.println("Successfully wrote to the file.");
    } catch (IOException e) {
        System.out.println("An error occurred.");
        e.printStackTrace();
    }
}

@Override
public void debug(String message) {
    super.info(message);
}

@Override
public void info(String message) {
    super.info(message);
}

@Override
public void warning(String message) {
    super.warning(message);
}

@Override
public void error(String message) {
    super.error(message);
}

}

Now, let's say I need to extend Logger to support new Log level, such as "FATAL", and also extend its children, such as FileAppenderLogger to support it, without modify any of those classes, only extend them. what could be the best practice for that (if I still want to preserve non generic methods such as ".info(String s)" or ".debug(String s))? What design pattern may I use here? I'm open for changes regard this problem. Thank you!

Search from combined data of multiple providers

I am faced with the following problem:

The goal is to be able search company and employees data and to be able to search them on certain criterias that the client can choose.

Example of criterias/fields are:

  • On a company: The number of employees, the industry and the orientation (B2B, B2C)
  • On an employee: Seniority, department

I get this type of data from multiple providers API.

Some of the fields I only get from only 1 provider, for example ProviderA gives me the orientation.

Other fields I get in different format. ProviderB gives me the number of employees as a number, ProviderC give me a range.

For each provider I store the raw data in a relation database such as: Provider_A_company, Provider_A_employee

I've tried to combine Company rows of multiple providers by domain (example.com) and combine Employee rows by employee email in order to create a Company view and an Employee View. However I'm concerned that this will not scale as the number of providers increases.

So I'm a bit stuck on how to approach this problem, on how to normalize and combine this data to be able to search it.

Is there a particular design or pattern that you would suggest to handle this?

Thank you

dimanche 27 novembre 2022

c++ log parser design pattern

I need to parse log files and update some of the parameters that in mfc GUI based on time. If that parameter appears 5 times, I need to hold all values based on time when application initiates and these should be played in a loop based on time. Which design pattern should be good for this mfc based c++ application.

NestJS websocket gateway pattern for multiple features

I am in the process of building a NestJS application that will be using WebSockets to communicate with the client. However, I am having trouble trying to determine what the pattern is for utilizing the @WebSocketGateway decorator between multiple features or what the suggested best practices are.

It appears that my options are to either encapsulate the functionality for all of my features (bookmarks, chats, posts) into a singular @WebSocketGateway class (i.e. app.gateway.ts) or to create a gateway for each of my features (i.e. bookmark.gateway.ts, chat.gateway.ts, etc...).

My current bookmark gateway appears like this

import {
  MessageBody,
  OnGatewayConnection,
  OnGatewayDisconnect,
  OnGatewayInit,
  SubscribeMessage,
  WebSocketGateway,
  WebSocketServer,
} from '@nestjs/websockets';
import { Server, Socket, Namespace } from 'socket.io';
import { Logger, OnModuleInit } from '@nestjs/common';

@WebSocketGateway({ namespace: 'bookmarks' })
export class BookmarkGateway
  implements OnGatewayInit, OnGatewayConnection, OnGatewayDisconnect
{
  private readonly logger = new Logger(BookmarkGateway.name);

  @WebSocketServer() io: Namespace;

  afterInit(server: Server): any {
    this.logger.log('Websocket Gateway initialized');
  }

  handleConnection(client: Socket): any {
    const sockets = this.io.sockets;

    this.logger.log(`WS Client with id: ${client.id}  connected!`);
    this.logger.debug(`Number of connected sockets ${sockets.size}`);
  }

  handleDisconnect(client: Socket): any {
    const sockets = this.io.sockets;

    this.logger.log(`WS Client with id: ${client.id}  disconnected!`);
    this.logger.debug(`Number of connected sockets ${sockets.size}`);
  }

  @SubscribeMessage('newMessage')
  onNewMessage(@MessageBody() body: any) {
    console.log(body);
  }
}

The first approach seems like it would go against the prescribed structure for a Nest application however the second approach requires a lot of code duplication for implementation of the connect and disconnect interfaces as well as creating multiple connections.

I did find another post pointing at the creation of a global gateway however it appears that it only provides the ability to emit messages by exporting the WebSocketServer and not the ability to SubscribeMessage.

Every other example I have found creates the gateway as part of the feature but this seems quite duplicitous in nature.

I was wondering if someone could point me in the right direction as to the accepted practice for implementing WebSockets across multiple features in NestJS?

Even if I give the right Input it still showing the error alert message

This is the code

<div class="form-group"><input id="name" type="text" placeholder="Name" name="name" ></div> <button type="submit" class="btn btn-primary signupbtn" onclick="check()">Sign Up</button>

`

let first = document.getElementById('name');



function check() {
  var pattern = /^[a-zA-Z]+$/;
  var res = pattern.test(first.value);
  
  if(first.value != res){
    alert('Invalid First Name');
  } 
  
}

`

I have tried keeping (first.value = res) and then executing. This time it is giving alert message only when there is correct input but not when wrong input. But as keep (first.value != res) then it is showing error message every time I press the signup button.

C# compile-time concrete class support for interface-based code

I've been scratching my head around this for weeks now. Sorry if the question is too long, I've tried to make it as short and understandable as possible by simplifying my specific case, stripping away generic parameters, access modifiers etc that don't directly relate to the problem.

Problem

Suppose I have an API cient of type ApiClient that can send commands to API. The commands take arguments and return data. I need methods in ApiClient to do this. But, and this is where things get tricky, I want the user to have a concrete return type, without needing a cast, for compile-time and Intellisense support.

Here's a sample code outline. Suppose I have 20 commands like these:

class AddCommand {
    class Args {}
    class Data {}
}

class ListCommand {
    class Args {}
    class Data {}
}
// and so on...
// Sample declarations:
ApiClient apiClient;
AddCommand.Args addCmdArgs;
ListCommand.Args listCmdArgs;
// and so on for each command's args...

I want the user code to be able to do this:

AddCommand.Data data = apiClient.SendCommand(addCmdArgs);
// Intellisense and compile-time checking available for 'data'

which means SendCommand() needs to be something like this:

Technique 1: Overloading on concrete type

public AddCommand.Data SendCommand(AddCommand.Args args) { ... }
public ListCommand.Data Sendcommand(ListCommand.Args args) { ... }
// and so on for all 20 commands

But this has a problem. Implementing it like this means there needs to be an overload of SendCommand() for each command, in ApiClient, making it more complex and error-prone to add new commands in the future. Overloading it using extension methods instead is similar, it just moves the methods outside ApiClient. The problem remains the same, and the solution still seems "unclean" to me.

Technique 2: One interface-based method

So an idea that comes to mind is to program for interfaces, changing the command types to the following, where commands, args and data each implement their corresponding interfaces:

class AddCommand : ICommand {
    class Args : ICommandArgs {}
    class Data : ICommandData {}
}

class ListCommand : ICommand {
    class Args : ICommandArgs {}
    class Data : ICommandData {}
}
// and so on...

Now there can be a single SendCommand():

ICommandData SendCommand(ICommandArgs args) {}

making it easy to add more commands in the future without changing anything. As a bonus, this solution also looks clean. But now, the user code needs to add a cast, from the interface to a concrete type: (I won't be using var to make it clear which types are being used where. In real code, yes, var can be used to shorten the code)

ICommandData data = apiClient.SendCommand(addCmdArgs);
if (data is AddCommand.Data addCmdData) {
   // ...
}

// or

AddCommand.Data data = (AddCommand.Data) apiClient.SendCommand(addCmdArgs);

This is now a problem because casting is error prone. No one is stopping the user from doing something like:

AddCommand.Data data = (AddCommand.Data) apiClient.SendCommand(listCmdArgs/*!! different args type*/);

which only fails at runtime.

Technique 3: Two unrelated generic arguments

You've probably thought about using generics by now, which, perhaps surprisingly, doesn't solve the problem either. Here's the most appropriate solution:

The command types may or may not implement their interfaces, but SendCommand() changes to:

TData SendCommand<TArgs, TData>(TArgs args) { ... }

// or

TData SendCommand<TArgs, TData>(TArgs args)
    where TArgs : ICommandArgs
    where TData : ICommandData { ... }

depending on whether the command types implement interfaces. There's basically no different between either implementation. But now the user code has to provide type arguments, because they can't be inferred:

AddCommandData data = apiClient.SendCommand<AddCommand.Args, AddCommand.Data>(addCmdArgs);

Yes, the user code now has complete compile-time benefits, but just seeing this code makes me wince. User has to provide both type arguments, and they aren't even bound together in any way, making this valid code:

ListCommand.Data data = apiClient.SendCommand<AddCommand.Args, ListCommand.Data>(addCmdArgs);

that fails only at runtime.

Technique 4: Three related type arguments

Technique 3 is probably the most verbose yet the most error prone technique yet. But it can be refactored by effectively binding the three type arguments to the same command, bringing us to the 4th and last technique that I could think of:

The types change to this:

interface ICommand<TArgs, TData>
    where TArgs : ICommandArgs
    where TData : ICommandData {}
interface ICommandArgs {}
interface ICommandData {}
class AddCommand : ICommand<AddCommand.Args, AddCommand.Data> {
    class Args : ICommandArgs {}
    class Data : ICommandData {}
}
class ListCommand : ICommand<ListCommand.Args, ListCommand.Data> {
    class Args : ICommandArgs {}
    class Data : ICommandData {}
}
// and so on...

and SendCommand() changes to:

TData SendCommand<TCommand, TArgs, TData>(TArgs args)
    where TCommand : ICommand<TArgs, TData>
    where TArgs : ICommandArgs
    where TData : ICommandData { ... }

The user now has to call it like this (brace yourselves):

AddCommand.Data data = apiClient.SendCommand<AddCommand, AddCommand.Args, AddCommand.Data>(addCmdArgs);

The user code now has compile-time support and can't accidently specify unrelated/incorrect type arguments. All three type arguments have to be for the same command. This is the most robust technique yet, and the closest solution to my problem that I could think of. Literally the only issue is that the user code has to specify all three type arguments, add namespace directives for those types, write very long lines etc.

Question

After all of this background information, I have a simple question. Is it possible to achieve what I'm trying to do, with a "clean" solution? At one end of the spectrum is Technique 1, very clean for the user, but inconvenient for the API client library. Gradually moving along the spectrum, we reach Technique 4, very clean for the library but inconvenient for the user code. I'm currently using Technique 1, overloading on the basis of concrete types, and I see Technique 4 as the closest solution to my problem, minus the disadvantages of course. Is there another technique, hopefully better that all of these? Or do I have to continue using overloads for different command types? Is there some design pattern that I'm missing, is this just another dumb question, or is something that has genuinely bugged software architecture and doesn't really have a satisfactory solution?

samedi 26 novembre 2022

Is it a good practice intatiating or registering multiple objects at the same time

I am creating a NodeJS boilerplate, as it was a framework, and I want to "register" the routes or endpoints when the application starts. I want to have an array of route classes and then instantiate them. Similar to what NestJs does with their Controllers. Then I want to loop through the collection and create instances of each Route passed in the array. Something as the following:

class RegisterRoutes() {
  routes: [FirstRoute, SecondRoute];

  instatiateRoutes() {
    for (route in routes) {
      new route()
    }
  }
}

Is this a good practice?

How do objects with arbitrary attributes gets implemented? [closed]

Irrespective of the value of x, the code

from bs4 import BeautifulSoup
import requests

source = requests.get("https://google.com").text
soup = BeautifulSoup(source, 'lxml')
obj = soup.x

never throws an AttributeError, which is what happens when we try to invoke an undefined attribute of an object.

I just can't visualize the kind of construct responsible for this functionality, nor can I decipher the source code of beautifulsoup. Can anyone enlighten me?

Builder Pattern Null Pointer Exception

I get Null Pointer Exception when running the code below:

public class Engine{

private String name = null;
private Mercedes m = null;

private Engine() {

}

public String getName() {
    return name;
}

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

public Mercedes getM() {
    return m;
}

public void setM(Mercedes m) {
    this.m = m;
}

public static EngineBuilder builder() {
    return new EngineBuilder();
}

public static class EngineBuilder {
    private Engine e = null;

    public EngineBuilder builder() {
        e = new Engine();
        return this;
    }

    public Engine build() {
        return this.e;
    }

    public EngineBuilder setName(String name) {
        this.e.setName(name);
        return this;
    }

    public EngineBuilder setM(Mercedes m) {
        this.e.setM(m);
        return this;
    }

}
public static void main(String[] args) {
    EngineBuilder builder = Engine.builder();
    builder.setName("test");
            
    Engine e = builder.build();

}

} }

I expected the Builder pattern would work, but I got "Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Engine.setName(String)" because "this.e" is null"

jeudi 24 novembre 2022

OCP and Facade with examples

I am trying to better understand Open-Closed Principle and Facade.

Question 1: OCP

If some software has a config file governing the operation of a software, is it an Open-Closed Principle case?

Question 2: Facade

Let's assume that the config file (level-1) is huge, too much detailed and somewhat redundant. Some software engineer made a smaller and more intuitive config file level-2 where level-2 can produce level-1. Is level-2 a Facade case?

Thank you,

I am trying to confirm if my understanding is correct.

Printing Triangle star(*) pattern in javascript using Recursion [duplicate]

I have been trying to solve printing down left side star(*) pattern in Javascript using recursion, i think my logic is correct but my syntax and concept might be wrong

// * * * * *
// * * * *
// * * *
// * *
// *

This is my code solution so far

var triangle = function (row, col) {
    if(row == 0){
        return
    }
    if(col < row){
        console.log("*")
        triangle(row, col + 1)
    }else{
        console.log("\n")
        triangle(row - 1, 0)
    }
}
triangle(4, 0)

output

*
*
*
*


*
*
*


*
*


*

But i want the output to be

* * * * *
* * * *
* * *
* *
*

how do I find a continuos number in dataframe and apply to new column

I have a huge dataframe around 5000 rows, I need to find out how many times a pattern occur in a column and add a new column for it, I am able to use np.where to get the pattern to 1 but I don't know how to count the pattern and add to new column, I did a search online try to use loop but I can't figure out how to use loop with dataframe

df['P'] = np.where((df['val2'] > df['val1']) & (df['val2']> df['val1'].shift(1)),1,0 )

         Date  val1  val2  P     [new column] ( 
0  2015-02-24   294    68  0         0
1  2015-02-25   155    31  0         0
2  2015-02-26   168   290  1         1            pattern occur 1 time
3  2015-02-27   273   108  0         0
4  2015-02-28    55     9  0         0
5  2015-03-01   273   123  0         0
6  2015-03-02   200    46  0         0
7  2015-03-03    80    83  0         0
8  2015-03-04   181   208  1         1            pattern occur 1 time
9  2015-03-05   195    41  0         0
10 2015-03-06    50   261  1         1            pattern occur 1 time
11 2015-03-07    50   177  0         0
12 2015-03-08   215    60  1         0
13 2015-03-09    13   290  1         2            pattern occur 2 times
14 2015-03-10   208    41  0         0
15 2015-03-11    49   263  1         0
16 2015-03-12   171   244  1         0
17 2015-03-13   218   266  1         0
18 2015-03-14   188   219  1         3            pattern occur 3 times
19 2015-03-15   232   171  0         0
20 2015-03-16   116   196  0         0
21 2015-03-17   262   102  0         0
22 2015-03-18   263   159  0         0
23 2015-03-19   227   160  0         0
24 2015-03-20   103   236  1         0
25 2015-03-21    55   104  1         0
26 2015-03-22    97   109  1         0
27 2015-03-23    38   118  1         4            pattern occur 4 times
28 2015-03-24   163   116  0         0
29 2015-03-25   256    16  0         0

physical simulation (OOP): Design and interfaces

For a college project im working on a physical simulation of how different protons react magnetically with each other. I'm looking on how the magnetizations change over time. The goal isn't the physical implementation itself, but creating a design that can be reused in some other context and be improved and expanded later on.

This being my first introduction to OOP, I was quite overwhelmed with all the concepts and principles and different implementations and patterns, you get the idea. What I've done so far is designing my class patterns and associations with each other. So in my example, I've created an physicalObject that consists of other objects. So in my case, I've tried to decouple the magnetic behaviour of a physicalObject into an interface MagneticProperties. The idea being that any object that has magnetic functionality can implement that interface.

I'm sure there is a lot to improve since I'm getting different ideas with any new concepts I read into. Apart from how my physicalObject is designed, what I'm wondering right now is how i would connect all of my created physicalObjects.

In my simulation, I need to calculate the magneticfield acting on a physObject. For this calculation however, I need the information on all the physObjects created. Also each timestep I need to calculate how the magnetization of one physObject changes using the BlochEquations.

My idea right now is to kind of create an object that stores all phyObjects and registers any change of their properties. Depending on which property changes, this objects would trigger different calculations. I have no idea though, how i should design this structure or if i should even do it this way. I'm sure there is a better way to design this. I have read into the observer pattern and thought this would be a good design, but im not sure anymore. I feel like this would make things more complex and i guess having many objects, it would make things difficult and not really reusable.

I'm not sure why I cant find a solution to my problem. I figured this kind of pattern or structure has to exist somewhere in like autonomous driving or in other scenarious where there is an object registering other objects and their change. But im struggling looking for answers. So here I am, directing this question to the community. Maybe anyone here can give an insight to what im missing :)

class diagram

Should I preallocate a vector

From an efficiency standpoint, would it be better to

  1. allocate enough memory for a vector<unique<Base*>> and downcast one by one or
  2. use polymorphism and insert(new Derived()) in combination with virtual functions (easy and straightforward). Should I even consider the first approach? Wouldn't I have to reset every unique_ptr? Also, would factory pattern be a better solution in my case?
class Chunk
{

public:
    uint32_t ChunkType;
;
class OldPaletteChunk : public Chunk;
class ColorProfileChunk: public Chunk;

So far I was preallocating the vector<unique<Chunk>> knowing the number of elements I needed to store. During runtime I would parse the file and read chunks of data based on their type:

switch (chunk->m_ChunkType) // Chunk::ChunkType
{
    case 0x0004:    // 0-255
    case 0x0011:    // 0-63
        readOldPaletteChunk(chunk); // dynamic_cast here?
    case 0x2007:    
        readColorProfileChunk(dynamic_cast<ColorProfileChunk*>(chunk)); // doesn't work
...
}

What would be the best way to simplify/refactor this because it is getting bloated :(

There is some decision logic in the software that I'm currently working on which is getting very unmaintainable and bloated. What would be the best way to refactor this? Is there some specific design pattern that could be used here?

    public Task Handle(
    OrderState orderState,
    OrderType orderType,
    bool isInternal,
    int clientId
    )
{
    return (orderState, orderType, isInternal) switch
    {
        (OrderState.New, OrderType.Personal, true) => GenericHandler(clientId, orderType, isInternal),
        (OrderState.Confirmed, OrderType.Personal, false) => OrderCreated(clientId, orderType, isInternal),
        (OrderState.New, OrderType.Corporate, true) => GenericHandlerCorporate(clientId, isInternal),
        (OrderState.BeingPrepared, OrderType.Personal, true) => GenericHandler(clientId, orderType, isInternal),
        (var type, OrderType.Corporate, false) when IsInternalWhitelisted(clientId) =>  OrderWhitelistedCreated(clientId, orderType, isInternal),
        (OrderState.Delivered, OrderType.Corporate, true) => GenericHandlerCorporate(clientId, isInternal),
        (OrderState.BeingPrepared, OrderType.Corporate, true) => GenericHandler(clientId, orderType, isInternal),
        (OrderState.Delivered, OrderType.Personal, false) => OrderCreated(clientId, orderType, isInternal),
        (OrderState.Confirmed, OrderType.Corporate, true) => GenericHandlerCorporate(clientId, isInternal),
        _ => ((Func<Task>)(() =>
        {
            DoSomethingElse();
            return Task.CompletedTask;
        }))()
    };
}

There are a lot more combinations in the switch but have been removed for keeping code snippet small.

I was thinking of maybe creating some sort of a map with all the possible combinations in it and somehow going from there.

mercredi 23 novembre 2022

Golang UnitOfWork and Repository Pattern

How can I apply UnitOfWork and Repository patterns in golang like in .Net Core?

I searched on the internet but I couldn't find an application where these two patters are used together or I couldn't search well.

What design patterns are these?

I’m stuck in a homework. I need to argue with design goals, principles and heuristics to say which pattern among these two is better. I’m curious to know which design pattern are these.

Here are the diagrams

My guess is that first one is a builder(?) and second is some structural pattern…? SOS

I had typed a code and i dont know why no output is coming not its showing any error. its just completly blank [duplicate]

import java.util.*;
public class lec6live {
    public static void main(String args[]) {

        for (int line = 1; line <=4; line--) {
            for (int star =4; star <=line; star--) {
                System.out.print("*");
            }
            System.out.println();
        }
    }
}

I was expecting

****

***

**

*

but not getting any result its completely blank. let me know the reason why?

Why do you have to define functions under a constructor's prototype but not when using other design patterns?

I am having trouble understanding prototypal inheritance when using constructors. I reached this lesson in The Odin Project where it says:

If you’re using constructors to make your objects it is best to define functions on the prototype of that object. Doing so means that a single instance of each function will be shared between all of the Student objects. If we declare the function directly in the constructor, like we did when they were first introduced, that function would be duplicated every time a new Student is created.

function Student() {
}

Student.prototype.sayName = function() {
  console.log(this.name)
}

I understand why you wouldn't want to duplicate the functions for every instance of the object, but I don't understand two things:

  1. Does this also apply to Classes which have constructors and Object() constructors?

  2. Why isn't this needed on other design patterns like Factory functions or the Module pattern? Wouldn't those functions also be duplicated for every instance of the object?

Parameter object slows down program significantly in C

I have a bunch of related arrays arr1, arr2, arr3. I pass these to a few functions, like foo.

int foo(int* arr1, int* arr2, int* arr3, ...) { ... }

The argument list starts to get pretty long, so I wanted to make a struct Bar to collect these related arrays in a single struct, like so:

struct Bar {
    int* arr1;
    int* arr2;
    int* arr3;
};

This allows me to simplify foo into foo(struct Bar bar, ...) { ... }, which is great. But when I do this the execution time goes from 1m35 to 2m18, which is a slowdown 45%. Using pointers instead, like foo(struct Bar* bar, ...) is faster at 2m03, but still slower overall. All of these measurements were taken with gcc 12.2.0. I compiled an optimized build (-O3).

I understand that adding a layer of indirection is bound to slow the program down, but given that this is such a common pattern and the change is so slight, I expected that the compiler would optimize this indirection away.

I also wonder if there is anything I can do to tell the compiler what I'm doing. Kind of like how inline can be used to change how functions are compiled. If nothing else, I'm curious as to why this is apparently a hard thing for the compiler to recognize and optimize.

Thank you in advance!

P.S. Here's the full code, it's short enough to put here. It's before I added the struct and it finds a solution to the N queens problem on the torus. The three arrays I'm trying to put into a struct are cols, updiags, downdiags.

#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#define N 31

int upDiag(int row, int col) {
    int updiag = row + col;
    if (updiag >= N)
        updiag -= N;
    return updiag;
}

int downDiag(int row, int col) {
    int downdiag = row - col;
    if (downdiag < 0)
        downdiag += N;
    return downdiag;
}

bool isSafeTorus(int* cols, int* updiags, int* downdiags, int row, int col, int updiag, int downdiag){

    for(int i = 0; i < row; i++) {
        if (cols[i] == col || updiags[i] == updiag || downdiags[i] == downdiag) {
            return false;
        }
    }
    return true;
}

bool solveNQUtil(int* cols, int* updiags, int* downdiags, int row){
    /* If all queens are placed then return true */
    if (row >= N)
        return true;
    /* try placing this queen in all coloms one by one */
    for (int i = 0; i < N; i++) {
        /* Check if the queen can be placed on board[row][i] */
        int updiag = upDiag(row, i);
        int downdiag = downDiag(row, i);

        if (isSafeTorus(cols, updiags, downdiags, row, i, updiag, downdiag)) {
            cols[row] = i;
            updiags[row] = updiag;
            downdiags[row] = downdiag;
            /* place rest of queens */
            if (solveNQUtil(cols, updiags, downdiags, row + 1))
                return true;
            /* If placing queen in board[i][col] no solution, remove queen*/
        }
    }
    /* Queen can not be placed this row */
    return false;
}


void main(){
    int* cols = (int*)malloc(N * sizeof(int));
    int* updiags = (int*)malloc(N * sizeof(int));
    int* downdiags = (int*)malloc(N * sizeof(int));

    if (solveNQUtil(cols, updiags, downdiags, 0) == false) {
        printf("Solution does not exist");
    }

    for(int i = 0; i < N; i++) {
        printf("%d\n", cols[i]);
    }
}

mardi 22 novembre 2022

System.Action/Func vs. a Switch Statement for Function Mapping

I am trying to create a function that can linearly interpolate between two objects without knowing the implementation details of the containing class. Specifically, I want to apply this to Unity's ScriptableObject class to be able to interpolate between game data presets, but the question and concepts should apply to any C# object.

Here's what I have so far: I fetch the fields and properties of the class like this (Settable is just a wrapper around FieldInfo and PropertyInfo):

public static void LerpBetweenObjects<T>(T destinationObj, T startObj, T endObj, float t)
{
    var type = typeof(T);
    var props = type.GetProperties(bindingFlags);
    var fields = type.GetFields(bindingFlags);
    foreach (var item in props)
    {
        PropertyInfo itemLocal = item;
        LerpBetweenMembersRefResult(new Settable(itemLocal), destinationObj, item.GetValue(startObj), item.GetValue(endObj), t);
    }
        
    foreach (var item in fields)
    {
        FieldInfo itemLocal = item;
        LerpBetweenMembersRefResult(new Settable(itemLocal), destinationObj, item.GetValue(startObj), item.GetValue(endObj), t);
    }

For the lerp function, my first thought was to just create a big switch statement, like this

public static void LerpBetweenMembersRefResult(ISettable result, object resultObj, object start, object end, float t)
{
    switch (start)
    {
        case float floatStart:
            result.SetValue(resultObj, Mathf.Lerp(floatStart, (float)end, t));
            break;
        case Color colorStart:
            result.SetValue(resultObj, Color.Lerp(colorStart, (Color)end, t));
            break;
                default:
            result = start;
            break;
    }
}

But then from reading some other answers on StackOverflow, people suggested using a function dictionary. So my version 2 looks like this:

private static Dictionary<Type, Action<ISettable, object, object, object, float>> lerpFuncsv2 = new Dictionary<Type, Action<ISettable, object, object, object, float>>()
{
    { typeof(float), (resultField, resObj, start, end, t) => resultField.SetValue(resObj, Mathf.Lerp((float)start, (float)end, t)) },
    { typeof(Color), (resultField, resObj, start, end, t) => resultField.SetValue(resObj, Color.Lerp((Color)start, (Color)end, t)) }
};

public static void LerpBetweenMembersRefResult(ISettable result, object resultObj, object start, object end, float t)
{
    if (lerpFuncsv2.TryGetValue(start.GetType(), out Action<ISettable, object, object, object, float> action))
    {
        action?.Invoke(result, resultObj, start, end, t);
    }
}

Version 2 looks more elegant, but it's about the same amount of typing, and comes with the downside of the invoke performance penalty. I'm wondering:

  1. Is there a method that's better than both of these?
  2. If not, then what is the benefit of using a function dictionary over a switch statement?

MVC pattern with multiple classes

When I want to use the MVC pattern to a project which contains multiple classes what should I do ?

I should create a separate view, model, and controller for each of the relevant classes or use unique controller, view and model ?

How to notify another class when the state of a class is changed

Assume you have a class Item with the attribute description and mutator methods for this attribute, and a class Registry keeping track of items. When Item#setDescription is called, I would like to be notified in the registry class because the registry might save the item update to other sources, such as a file.

Currently my Item#setDescription is accessing the registry through the static method Registry#updateDescription. I do not know if using a static method in this way is a good solution. I think an observer pattern would be overkill.

How should I approach this?

Offset management Java patten

Let's suppose I have some abstract entity in the system which created each time.

Each of those entities should have two ID - Serial and Sequence.

UC

  1. Initial state - A(Serial=1, Sequence=1).
  2. Scale out - A(Serial=1, Sequence=1), A(Serial=2, Sequence=2)
  3. Scale in - A(Serial=1, Sequence=1)
  4. Scale out again - A(Serial=1, Sequence=1), A(Serial=4, Sequence=3)

Meaning that sequence id it is kind of offset that stored and previous versions is not used.

My question is - is there any patterns in Java that you would recommend to look, main aim of which is store those values in some generic data structure.

lundi 21 novembre 2022

Trying to implement design pattern in typescript (NestJS), but having trouble when setting variable dynamically

I am trying to implement a base service builder for injecting dependencies. Here the code I've written so far.

`

import { DirectVotesService } from 'src/direct-votes/direct-votes.service';
import { EligibleVotingCandidatesService } from 'src/eligible-voting-candidates/eligible-voting-candidates.service';
import { FederalVotesService } from 'src/federal-votes/federal-votes.service';
import { VotesService } from 'src/votes/votes.service';
import { ServiceBuilder } from '../interfaces/base-service.builder';

type VotesServiceDependencies = {
  federalVotesService: FederalVotesService;
  directVotesService: DirectVotesService;
  eligibleVotingCandidatesService: EligibleVotingCandidatesService;
};

export class VotesServiceBuilder
  implements ServiceBuilder<VotesService, VotesServiceDependencies>
{
  constructor(
    readonly service: VotesService,
    private readonly dependencies: VotesServiceDependencies
  ) {}

  getService<S extends keyof VotesServiceDependencies>(
    serviceKey: S
  ): VotesServiceDependencies[S] {
    return this.dependencies[serviceKey];
  }

  setService<S extends keyof VotesServiceDependencies>(serviceKey: S): this {
    this.service[serviceKey] = this.dependencies[serviceKey];
    return this;
  }

  build(): VotesService {
    return this.service;
  }
}

` But I am getting an TS error when setting the service. The error:

`

Type 'VotesServiceDependencies[S]' is not assignable to type 'VotesService[S]'.
  Type 'VotesServiceDependencies' is missing the following properties from type 'VotesService': repository, provinceClusterService, statesService, campaignsService, and 8 more.ts(2322)

` error I would like the setService method to set the service to the respective properties and chain them as follows. For example:

this.votesBuilderService.setService("federalVotesService").setService("directVotesService")

Also, the VotesService itself:

`

export class VotesService {
  /* Set these services from the votes service builder */
  federalVotesService: FederalVotesService;
  directVotesService: DirectVotesService;
  eligibleVotingCandidatesService: EligibleVotingCandidatesService;
  constructor(
    @InjectRepository(VotesRepository)
    private readonly repository: VotesRepository,
    private readonly campaignsService: CampaignsService,
    @Inject(CACHE_MANAGER) private readonly cacheManager: Cache
  ) {}
}

`

concatanate images with same size using vstack

i'm using vstack to concat 2 images but after concatanation i have a line between the 2 images. I want to know if there is a proper way to remove that line or another way to create a seamless repeat pattern image by concatenation.

design pattern and best practice card game yugioh

I started to develop a card game based on yugioh! I want to know how to optimize it before going further. So after searching for design patterns, I am thinking of two choices, but I do not know what is the best one. Before that, to explain the game :

 We have different type of cards : 
      ->  1.SPELL
      -> 1.Trap 
      -> 3.Monster 
           3.1->->monster from the main deck
           3.2-> -> mosters from extra deck 
               3.2.1>->->Link
               3.2.2>->->Pendulum
                           ....

I also have three type of deck when playing : -> Main deck (accepts spells, traps and mainMonsters) -> Extra deck (accepts monsters that are link, pendulum...) -> Side (accepts everything, it is used if you want to change some cards from your main / extra between matchs)

So the other issue, is to find the best way to make a link between the card and its belonging deck in order to know if I accept to add the card to the deck or not

OPTION one : use the design pattern decorator : The thing is I will create a lot of classes for sometimes nothing. For example, a link monster have 1 more attribute and does't have def points. A pendulum can change to a spell card...

OPTION 2 : Create only one class with all attributes.

I hope that my issue is clear, thank you all for your help

public class Card extends javafx.scene.image.ImageView implements Serializable {
    private int id;
    private String name;
    private String type; //SpellCard, TrapCard, FusionMonster, SynchroMonster, Tuner monster, Pendulum monster
    private String desc; 
    private String race;
    private String image;
    private String imageSmall;
    private Player owner;
    private Limit limit = Limit.NO_LIMITED; 
    private Face face = Face.UP; 
    
    /**
     * This constructor is used to generate a card from data formatted as JSon
     * @param card  its type is JsonNode
     */
    public Card(JsonNode card, Player owner)
    {
        id = card.path("id").asInt();
        name = card.path("name").asText();
        type = card.path("type").asText();
        desc = card.path("desc").asText();
        race = card.path("race").asText();
        image = card.path("card_images").get(0).path("image_url").asText();
        imageSmall = card.path("card_images").get(0).path("image_url_small").asText();      
        this.owner = owner;

        setCardImage();
    }
    
    /**
     * This constructor is used to generate a card from data exported from database 
     * @param cardInfo its type is ResultSet
     */
    public Card(ResultSet cardInfos, Player owner)
    {
        try {
            id = cardInfos.getInt("id");
            name = cardInfos.getString("name");
            type = cardInfos.getString("type");
            desc = cardInfos.getString("desc");
            race = cardInfos.getString("race");
            image = cardInfos.getString("image");
            imageSmall = cardInfos.getString("imageSmall");
            this.owner = owner;
            
            setCardImage();
        } 
        catch (SQLException e) 
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * This constructor is used to generate a card manually
     * @param id  card id
     * @param name card name
     * @param desc card description
     * @param race card race 
     * @param image card images list formatted as csv (;)
     */
    public Card(int id, String name, String type, String desc, String race, String image, String imageSmall, Player owner) 
    {
        this.id =  id;
        this.name = name;
        this.type = type;
        this.desc = desc;
        this.race = race;
        this.image = image;
        this.imageSmall = imageSmall;
        this.owner = owner;
        setCardImage();
    }

    //setters and getters 
}
public class MonsterCard extends Card {
    private int atk;
    private int def;
    private int level;
    private String attribute;
    private Position mode;
    
    /**
     * This constructor is used to generate a monster card from data formated as Json
     * @param card its type is JsonNode
     * @param owner player 
     */
    public MonsterCard(JsonNode card, Player owner) {
        super(card, owner);
    
        this.atk =  card.path("atk").asInt();
        this.def = card.path("def").asInt();
        this.level = card.path("level").asInt();
        this.attribute = card.path("attribute").asText();
    }
    
    /**
     * This constructor is used to generate a monster card from data exported from database 
     * @param cardInfos its type is ResultSet
     */
    public MonsterCard(ResultSet cardInfos, Player owner) {
        super(cardInfos, owner);
        
        try {
            this.atk = cardInfos.getInt("atk");
            this.def = cardInfos.getInt("def");
            this.level = cardInfos.getInt("level");
            this.attribute = cardInfos.getString("attribute");  
        }
        catch (SQLException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    /**
     * @param id
     * @param name
     * @param type
     * @param desc
     * @param race
     * @param image
     * @param imageSmall
     * @param owner
     */
    public MonsterCard(int id, String name, String type, String desc, String race, String image, String imageSmall,
            Player owner) {
        super(id, name, type, desc, race, image, imageSmall, owner);
        
    }
        //getter and setter
[/code]

[code=java]
public  class SpellCard extends Card{

    public SpellCard(int id, String name, String type, String desc, String race, String image, String imageSmall, Player owner) {
        super(id, name, type, desc, race, image, image, owner);
    }

    public SpellCard(JsonNode card, Player owner) {
        super(card, owner);
    }

    public SpellCard(ResultSet cardInfos, Player owner) {
        super(cardInfos, owner);
    }

        //getter and setter
}
public class TrapCard extends Card{

    /**
     * @param id
     * @param name
     * @param type
     * @param desc
     * @param race
     * @param image
     * @param owner
     */
    public TrapCard(int id, String name, String type, String desc, String race, String image, String imageSmall, Player owner) {
        super(id, name, type, desc, race, image, imageSmall, owner);
        // TODO Auto-generated constructor stub
    }

         //getter and setter
}
public class Deck implements Serializable{
    
    private List<Card> cardList ;   
    
    private DeckType type;
    
    public Deck(DeckType type)
    {
        cardList = new ArrayList<Card>(type.getMinCard());
        
        this.type = type;
    }
    
    
    public boolean checkNbCard()
    {

        //size of the deck 
        int size = cardList.size() ;
        
        return (size >= getMinCard()&& size <= getMaxCard());
    }
    
    public boolean checkCardCopies()
    {
        //count each card occurrences
         Map<String,Long> occurrenceMap = cardList.stream().collect(Collectors.groupingBy(card -> card.getName(),Collectors.counting()));
         
         return (cardList.stream().filter(card -> card.getLIMIT().getNbCopies()< occurrenceMap.get(card.getName())).count() > 0);
    }
    
    public boolean isValid()
    {
        return (checkNbCard() && checkCardCopies());
    }

    public void addCard(Card card)
    {
        cardList.add(card);
    }
    
    public void removeCard(Card card)
    {
        cardList.remove(card);
    }
    
    public void clearDeck()
    {
        cardList.clear();   
    }
    //getter and setter
}

Refactoring a WCF Trusted Facade

I'm attempting to refactor a "trusted facade" which currently wraps over 50 service calls to the backend. All calls have different signatures, but everything else is being repeated. The issue with the existing calls was that there was no attempt made to manage the connections, resulting in ephemeral ports remaining in the "BOUND" state.

ORIGINAL CODE:

public class ReportWeb : IReportWeb
{
    ReportService.ReportClient client = new ReportClient();
    ...
    
    public string[] GetData() => client.GetData();
}

NEW CODE:

private ChannelFactory<IReportService> _factory = null;
private IReportService _proxy = null;

private void OpenProxy()
{
    _factory = new ChannelFactory<IReportService>("NetTcpBinding_IReportService");
    _proxy = _factory.CreateChannel();
}

private void CloseProxy()
{
    ((IClientChannel)_proxy).Close();
    _factory.Close();
}

public string[] GetData()
{
    string[] results = null;

    try
    {
        OpenProxy();
        results = _proxy.GetData();
        CloseProxy();
    }
    catch (Exception exception)
    {
        bool faulted = _factory.State == CommunicationState.Faulted;
        _factory.Abort();

        if (faulted)
        {
            throw new ApplicationException(exception.Message);
        }
        else
        {
            throw;
        }
    }
    return results;
}

There are over fifty other methods like GetData() with different signatures. They will all be identical except for the service call in each, which will vary in params and return type. I need a more abstract, or generic, way of coding this and thus adhere to the DRY principle. Would Func<T, TResult> Delegate be appropriate here? Either way, can someone suggest a best approach here with some stub code to illustrate?

dimanche 20 novembre 2022

How to make a 3d shadow on bottom of the container so it looks like the container is standing like this on image?

I need to make a realistic 3d shadow that looks like the container is standing. Just like the image shows.

enter image description here

enter image description here

Azure Function Isolated: simple way to access ILogger in all classes?

I am using Azure Functions in Isolated mode, .NET 7.

I am able to inject a logger into my functions pretty easily by simpler adding an ILogger to the constructor of my functions and having the logging config setup in host.json file.

I can also inject an ILogger to any class, if I make that class an Interface, and inject the interface in my startup method.

However, I find this cumbersome, as often I don't need an interface, so I am making an Interface just for a single class to implement it, and sometimes I want to instantiate my object with property values, and then the DI won't work in those cases.

Is there a simple way/design pattern that allows me to have a single static or Singleton method Logger.Log("Message") from anywhere in my entire solution?

samedi 19 novembre 2022

How to calculate request TPS?

Hello stackoverflow fam,

I am building one backend service, which upon getting a GET request call, invokes 2 APIs of an external service provider "XYZ".

The entire flow looks like this :

Every 1 hour :

A python data scan job completes it's exection, and then gives a GET call to my API endpoint.

My API service then starts processing the request, and invokes 2 APIs of the "XYZ" service proider, which are :

  1. GetVehicleData
  2. UpdateVehicleData

I only have 1 python job, so my backend service will only receive 1 GET request each hour.

"XYZ" service provider has asked me for request TPS, which should cover the average and worst case.

Based on my calculation :

Worst case TPS : 2 API requests/hour = 48 API requests/ day = 48 API requests / 86400 seconds = 5.55555556×10−4 = 0.000555 = <1

Average case TPS : 2 API requests/hour = 48 API requests/ day = 48 API requests / 86400 seconds = 5.55555556×10−4 = 0.000555 = <1

I wanted to check if I am following the correct approach. Thanks.

How to structure an interdependent domain with Kotlin classes and functions

Me and my team are refactoring/rewriting a legacy Java library which basically contains our domain model. We're doing it to modernize our applications and reduce the amount of bugs that a developer can make while using this library due to the 'open' APIs it has in the legacy version.

The problem we're facing is that our domain is quite complex and a lot of its concepts are interdependent with each other.

As an example we've a set of enums that intrinsically depend on each other, something like this:

enum class Type {
    A, B, C, D
}

enum class Model {
    X, Y, Z
}

enum class Frequency {
    FREQUENCY_100,
    FREQUENCY_200,
    FREQUENCY_300,
    FREQUENCY_400,
    FREQUENCY_500,
    FREQUENCY_600,
    FREQUENCY_700
}

data class Status(
    val type: Type,
    val model: Model,
    val frequency: Frequency
) {
    init {
        // validation code
    }
}

The problem is that we've a lot of constraints about which Frequency values are valid depending on the values of Type and Model. For instance, for types A and B, with models X and Y, the frequencies below 500 are available; for types A only, with models Y and Z, the frequencies above 500 are available; and so on. This is not really the real situation, but it illustrates the problem.

I've read about functional domain modeling, some articles about Kotlin lambda functions with receivers and the new experimental feature of context receivers and was thinking if something like this would be possible:

val status = status(type, model) {
    frequency = // only available frequencies checked by the compiler
}

To wrap things up, frequency is just one of the interdependent variables. We've more cases like this and this domain is constantly evolving as the product grows. Any ideas or design principles that I could apply to this case?

What's my mistake on Design Twitter problen on Leetcode?

the problem:

https://leetcode.com/problems/design-twitter/

my solutiion:

class Twitter:

    def __init__(self):
        self.tweet_posted = []
        self.follow_users = []

    def postTweet(self, userId: int, tweetId: int) -> None:
        self.tweet_posted.insert(0, [userId, tweetId])

    def getNewsFeed(self, userId: int) -> List[int]:
        #lst = [ls[1] for ls in self.tweet_posted if ls[0] == userId or list([userId, ls[0]]) in self.follow_users]
        lst = []
        for i in self.tweet_posted:
            if list([userId, i[0]]) in self.follow_users or i[0] == userId:
                lst.append(i[1])
        return lst

    def follow(self, followerId: int, followeeId: int) -> None:
        self.follow_users.append([followerId, followeeId])

    def unfollow(self, followerId: int, followeeId: int) -> None:
        unfollow_user = [followerId, followeeId]
        if unfollow_user in self.follow_users:
            self.follow_users.remove(unfollow_user)

No error, but wrong answer by leetcode: enter image description here

it seems that my solution should be right since the function getNewsFeed must contain ALL the tweets of the user...

vendredi 18 novembre 2022

What creational design pattern should be used for different users [closed]

I have 3 types of user in my forum app: regular, member and special. They all have the same functionalities such as createPost, but the member and special have more such as they can use customEmoji on their post. Regular user have a limit on how many post they can make, while member and special don't have a limit.

Any ideas what design pattern should I use here? I'm relatively new to this, so I'm not sure on what to use.

I've tried using abstract class for user and then another class called for regular, member and special which extends user.

Not able to inject the dependency of Generic Repository

I was working on one POC application for Clean Architecture with Repository Pattern in .Net core.

Below is my application structure -

enter image description here

Which is very straight forward Clean Architecture plain solution.

As per the guidelines of Clean Architecture, I have created Repository Interfaces (With Generic Repository) in "ECommerce.Application" project and the implementation being done in "ECommerce.Infrastructure" project.

My Generic Repos are like below -

public interface IGenericRepository<T>
    where T : BaseEntity
{
    T[] Get();
    T Get(Guid id);
    T Get(Expression<Func<T, bool>> predicate);
    T[] GetWithInclude(params Expression<Func<T, object>>[] includes);
    T GetWithInclude(Guid id, params Expression<Func<T, object>>[] includes);
    void Add(T entity);
    void Update(T entity);
    void Delete(T entity);
    void Delete(Guid id);
    void SaveChanges();

}

public class GenericRepository<T> : IGenericRepository<T>
where T : BaseEntity
{
    private readonly IApplicationDbContext persistenceContext;
    private readonly DbSet<T> dbSet;

    protected GenericRepository(IApplicationDbContext persistenceContext)
    {
        this.persistenceContext = persistenceContext;
        dbSet = persistenceContext.GetDbSet<T>();
    }

    protected virtual Expression<Func<T, bool>> DefaultPredicateBuilder => x => true;

    T[] IGenericRepository<T>.Get()
    {
        return dbSet.Where(DefaultPredicateBuilder).ToArray();
    }

And my Concrete Repos are -

public interface IUserRepository : IGenericRepository<User>
{
}

public class UserRepository : GenericRepository<User>, IUserRepository
{
    protected UserRepository(IApplicationDbContext persistenceContext) : base(persistenceContext)
    {
    }
}

And I have one UserService where its using the UserRepository for business rules -

 public class UserService : IUserService
 {
     private readonly IUserRepository _userRepository;
     public UserService(IUserRepository userRepository)
     {
            this._userRepository = userRepository;
     }

And i have injected the dependencies in "ECommerce.WebAPI" project -

var connectionString111 = builder.Configuration["ConnectionString:eCommerceDB"];
builder.Services.AddDbContext<ApplicationDbContext>(opts => opts.UseSqlServer(connectionString111));

builder.Services.AddScoped<IApplicationDbContext, ApplicationDbContext>();

builder.Services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
builder.Services.AddScoped<IUserRepository, UserRepository>();
builder.Services.AddScoped<IUserService, UserService>();

Now when I run my WebAPI project, i am getting issue -

A suitable constructor for type 'ECommerce.Application.Interfaces.Repositories.UserRepository' could not be located.

I have seen couple of posts related to this error, But most of the people are suggesting to do -

builder.Services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));

Unfortunately it didnt work for me, Can anyone please help.

Full Details of the error -

enter image description here

Is it right to put data members in a C++ interface?

I'm trying to implement the strategy design pattern in C++, as shown in this following schematic: uml diagram

I would like to know, if it's correct to add data members in the interface ? If no, why ? In case if this implementation is correct. How to test is using google mock ?

I share with you the pseudo code of what I trying to accomplish :

#include <cassert>
#include <memory>

constexpr int maxCases = 7 * 5 * 3;

class IStrategy
{
public:
    IStrategy();
    ~IStrategy() = default;
    virtual void algorithm() = 0;
    int method1(const int x) const;
protected:
    int method2(const int x, const int y) const;

private:
    int* allCases{};
};

IStrategy::IStrategy() : allCases(new int[maxCases]) {}

int IStrategy::method2(const int x, const int y) const
{
    int result{};
    assert(sizeof(allCases) /sizeof(*allCases) <= maxCases);
    // ...
    return result;
}

int IStrategy::method1(const int x) const
{
    int result{};
    // ...
    return result;
}

class StrategyA : public IStrategy
{
public:
    virtual void algorithm() override;
};

void StrategyA::algorithm()
{
    int x{0};
    int y{0}; 
    // ...
    int nbrOfCases = method2(x, y);
    // ...
}

class StrategyB : public IStrategy
{
public:
    virtual void algorithm() override;
};

void StrategyB::algorithm()
{
    int x{0};
    int y{0}; 
    // ...
    int nbrOfCases = method2(x, y);
    // ...
}

class StrategyC : public IStrategy
{
public:
    virtual void algorithm() override;
};

void StrategyC::algorithm()
{
    int x{0};
    int y{0}; 
    // ...
    int nbrOfCases = method2(x, y);
    // ...
}

class Context
{
public:
    void setStrategy(IStrategy* stgy);
    void applyStrategy() const;
private:
    IStrategy* strategy;
};

void Context::setStrategy(IStrategy* stgy)
{
    strategy = stgy;
}
void Context::applyStrategy() const
{
    strategy->algorithm();

}

void clientCode()
{
    Context context;
    StrategyA strategyA;
    StrategyA strategyB;
    StrategyA strategyC;
    // ...
    context.setStrategy(&strategyA);
    context.applyStrategy();
    // ...
    context.setStrategy(&strategyB);
    context.applyStrategy();
    // ...
    context.setStrategy(&strategyC);
    context.applyStrategy();
    // ...
}

int main(int argc, const char* argv[])
{
    clientCode();
    return 0;
}

jeudi 17 novembre 2022

Constructor of base class in CRPT pattern

I'm using the CRPT pattern for a complex class (for learning).

I created a complex base class with a derived cartesian class, so I can add a complex<polar> class after. I have this piece of code working properly.

#include <iostream>

template<typename T>
class complex{
    public:
        using value_type = double;
        value_type re(){return static_cast<T*>(this)->re();}
};

class cartesian : public complex<cartesian>{
    public:
        using value_type = double;
        value_type re() const {return 1;}
    private:
        value_type re_;
};

int main(){
    complex<cartesian> c;
    std::cout << c.re();
}

It works, but when I want to add a constructor to initialize the re_ variable:

#include <iostream>

template<typename T>
class complex{
    public:
        using value_type = double;
        complex(){static_cast<T*>(this)->cartesian();}
        value_type re(){return static_cast<T*>(this)->re();}
};

class cartesian : public complex<cartesian>{
    public:
        using value_type = double;
        cartesian() : re_(2){}
        value_type re() const {return re_;}
    private:
        value_type re_;
};

int main(){
    complex<cartesian> c;
    std::cout << c.re();
}

I get this error:

main.cpp: In instantiation of ‘complex<T>::complex() [with T = cartesian]’:
main.cpp:15:28:   required from here
main.cpp:8:42: error: invalid use of ‘cartesian::cartesian’
    8 |         complex(){static_cast<T*>(this)->cartesian();}
      |                   ~~~~~~~~~~~~~~~~~~~~~~~^~~~~~~~~

I guess the implementation for constructors is different? Any solution?

What could be the correct solution for Transforming a Complex request from one form to other? [closed]

I Have got 2 APIs, V1 and V2. V2 is the newer API, on hitting V2 API, I need to convert the request from Type V2 to V1 and hit V1 API, And the conversion itself is highly complex due to lot of business rules for converting from V2 to V1.

I need some kind of design pattern, or LLD using which I can solve this problem efficiently and also it should be highly extendable.

I have implemented using something like chain of responsibility pattern, as the request structure looks like a tree, and I will handle branch by branch from root the leaves.

I can't share the request here due to security issues.

Any advises here will be greatly appreciated, it can be anything like a framework, or the design pattern, or the LLD.

How to have multi options list for one function?

I am using options pattern to configure the behavior of function, there are two function Foo and Bar which one dependent on the other, the code as follow

type fooOptions struct {
    fooName string
}

type FooOptions func(*fooOptions)

func WithFooName(fooName string) {
    return func(options *fooOptions) {
        options.fooName = fooName
    }
}

func Foo(options ...FooOptions) {
    opts := &fooOptions{}
    for _, opt := range options {
        opt(opts)
    }

    // do something
}

type barOptions struct {
    barName string
}

type BarOptions func(*barOptions)


func WithBarName(barName string) {
    return func(options *fooOptions) {
        options.barName = barName
    }
}

func WithBarName(barName string) {
    return func(options *barOptions) {
        options.barName = barName
    }
}

// compile error,unable have multi options list
func Bar(boptions ...BarOptions,fOptions ...FooOptions) {
    bopts := &barOptions{}
    for _, opt := range boptions {
        opt(bopts)
    }
    Foo(fOptions...)
}

I wonder how can I have multi options list for the Bar function,or any other smart way, so I can reuse the code, otherwise I have to flatten fooOptions into barOptions and writing the withXXX again

mercredi 16 novembre 2022

How can I create an algorithm to determine if the certificate presented by a candidate in an interview was issues by university X?

Design an algorithm to find or determine the certificate presented by a candidate in an interview was issued by university X. Assume that the certificate issued by the University X is coded as 200001, 200002, 200003 till 205000, where the first 2 digit indicate the year of insurance and the remaining digit indicate the serial number.

I tried and followed the standard algorithm approach

  1. Understand the problem to be solved
  2. You decide on
  • computation means
  • will your solution be exact or approximate
  • what data structure are you using
  • algorithm design techniques to be used
  1. Design the Algorithm; specifying the algorithm using natural language/pseudocode/flowchart/UML diagram
  2. Proof of correctness of the algorithm
  3. Analyze the algorithm; this determines the performance of the algorithm in terms of time
  4. Code the algorithm; translate algorithm to computer programming language of any of your choice.

but am having issues with step 3

Database design for request / approval process and logging any changes to request ( Vue / Laravel / Oracle )

Sup.

I'm tasked with making an ER Diagram in UML notation for my job. I've hit a problem that I can't find the best way to implement. I'd like some advice from people that are way smarter than me haha.

I'm going to simplify the architecture obviously to not give away exact information and the schema, but I'll try my best.

Let's say you have Users that can request services. A service can have 0, 1, or Many fees attached to it. Before the changes are committed to the database, it needs to be approved. (simplified structure so far). OK so that's easy enough, but here's where it gets weird...

On a request, we're allowing it to be editable. So before the validation process is complete, another user can EDIT the request. This is also logged. To give some working environment background, I'm using Laravel 9, Vue and Oracle Database.

I'm using this Audit Plugin. So I do have an audits table.

I guess what I'm asking is how would you implement this? How does the table structure look? Should I create custom audits? but if I create a custom audit of a request in the audit table, wouldn't that mean I'd have to create an audit of an audit if I want to edit it? I'm open to completely scrapping the auditing and making a custom auditing procedure for this functionality alone... I just need to know the best way to accomplish this.

Thanks! If you need any more info, I'll try to answer it as best I can without breaking confidentiality rules lol.

What I've tried

So, I like how the Auditing plugin allows for Old/New values to be in JSON strings. That takes up a lot less space. The problem is that the new values can be changed as a request should be able to be changed per the requirements. This is also logged. That means if I do this, I have to log the changes of a JSON string if I just add the auditing plugin to the request and fee models? I know it's DOABLE but I just want best practices.

Sorry if that doesn't make sense or I explained badly. Trying my best.

mardi 15 novembre 2022

Architectural design clarrification

I built an API in nodejs+express that allows reactjs clients to upload CSV files(maximum size is atmost 1GB) to the server.

I also wrote another API which when given the filename and row numbers in an array (ie array of row numbers ) as input, it selects the rows corresponding to the row numbers, from the previously stored files and writes it to another result file (writeStream). Then th resultant file is piped back to the client(all via streaming).

Currently as you see I am using files(basically nodejs' read and write streams) to asynchronously manage this.

But I have faced srious latency (only 2 cores are used) and some memory leak (900mb consumption) when I have 15 requests, each supplying about 600 rows to retrieve from files of size approximately 150mb.

I also have planned an alternate design.

Basically, I will store the entire file as a SQL Table with row numbers as primary indexed key.

I will convert the user inputted array of row numbrs to a another table using sql unnest and then join both these tables to get the rows needed.

Then I will supply back the resultant table as a csv file to the client.

Would this architecture be better than the previous architecture?

Any suggestions from devs is highly appreciated.

Thanks.

When to use methods vs classes in SOLID?

My Ruby on Rails app has a User and a Plan model. When someone hops on a paid plan, I create a Stripe::Customer and a Stripe::Subscription on Stripe.

This is being done in an action in a functional programming manner. I'm now applying SOLID principles to this action. For now, I have only applied the Single Responsibility Principle.

This is how the code was before:

def create
  user = User.find(params[:user_id]
  plan = Plan.find(params[:plan_id]

  # The following generates the necessary hashes for Stripe from the user and plan objects
  customer_info = { ... }
  subscription_info = { ... }

  customer = Stripe::Customer.create(customer_info)
  subscription_info[:customer] = customer
  subscription = Stripe::Subscription.create(subscription_info)

  # Rest of the code...
end

This is the new code:

def create
  user = User.find(params[:user_id]
  plan = Plan.find(params[:plan_id]

  subscription = SubscriptionHandler.create_subscription(user, plan)

  # Rest of the code...
end

However, I'm a bit undecided on how break down the code in SubscriptionHandler. I am specifically trying to extract the Stripe::Customer creation code in SubscriptionHandler.create_subscription.

Should that code go in a new class like SubscriptionCustomerHandler, like this:

class SubscriptionHandler
  def self.create_subscription(user, plan)
    subscription_info = { ... }

    customer = SubscriptionCustomerHandler.create_customer(user, plan)
    subscription_info[:customer] = customer
    subscription = Stripe::Subscription.create(subscription_info)
  end
end

class SubscriptionCustomerHandler
  def self.create_customer(user, plan)
    customer_info = { ... }
    customer = Stripe::Customer.create(customer_info)
  end
end

Or should it go in a method like SubscriptionHandler.create_customer, like this:

class SubscriptionHandler
  def self.create_subscription(user, plan)
    subscription_info = { ... }

    customer = SubscriptionHandler.create_customer(user, plan)
    subscription_info[:customer] = customer
    subscription = Stripe::Subscription.create(subscription_info)
  end

  def self.create_customer(user, plan)
    customer_info = { ... }
    customer = Stripe::Customer.create(customer_info)
  end
end

What are the advantages/disadvantages of one or the other? How does one decide which one to go for? Also, how do you feel about the SubscriptionHandler name?

Python - reference class each other (information flow)

I would like to know, what is the concept of information flow in GUI based apps, or any other app with same problem. When you have two seperate classes and their objects, how is the messeging process done between them. For example you have a GUI and AppLogic.

Scenario 1: Button is pressed -> GUI is processing event -> calls AppLogic method image_clicked()

Scenario 2: HTTPServer gets a message -> AppLogic receives image -> AppLogic calls GUI method render_image()

enter image description here

The problem is that you cannot reference classes each other because the first class does not know the second one (here AppLogic does not know GUI class):

class AppLogic():
    gui : GUI

    def image_clicked(self):
        pass #not important
    
class GUI():
    app_logic : AppLogic
    
    def render_image(self):
        pass #not important

I know this is more like go to school and study problem, but I would like to know how these problems are sovled, or some common practices. At least link with some detailed information. I am not able to name the problem right to find the answer.

How to solve flow finish problem in if else statement

I am facing a problem where there are too many if conditions and also multiple return statements. When I write the code like this, it becomes a very difficult code to read. My goal is to get rid of if else statements as much as possible and to finish the code in one place.

Below I will try to explain the problem I am having with a code example.

Let's consider a code where too many external services are called and a response check must be made for each service. For Example:

public class ResponseExternal{
   private Header header;
   private Body body;
   //get set methods
 }       
public class ResponseExternalAnother{
   private Header header;
   private Body body;
   //get set methods
 }   
public class Response{
   private Header header;
   private Body body;
   //get set methods
 }       

Execute method in service class:

   public Response run(Request request){
    
       
       //Some implementation for external services request
    
       ResponseExternal responseExternal = ResponseExternalService.callExternalService(externalServiceRequest);
       if(!responseExternal.getHeader().isSuccess()){  //I have to control external service response but I don't want this statement to be here. Coding these controls reduces the readability of the code.
          response.setResponseHeader(responseExternal.getHeader());
          return response; //I have to finish flow here
       }
    
       if(Objects.nonNull(responseExternal.getBody() && Objects.nonNull(responseExternal.getBody().getExampleField())){
         ExampleField exampleField = responseExternal.getBody().getExampleField();
       }
    
    
       //continue process
     
      ResponseExternalAnother responseExternalAnother = ResponseExternalService.callExternalService2(externalServiceRequest2);
       if(!responseExternalAnother.getHeader().isSuccess()){ //I have to control external service response but I don't want this statement to be here. Coding these controls reduces the readability of the code.
          response.setResponseHeader(responseExternalAnother.getHeader());
          return response; //I have to finish flow here
       }
    
    
      if(Objects.nonNull(responseExternalAnother.getBody() && Objects.nonNull(responseExternalAnother.getBody().getExampleField())){
         ExampleField2 exampleField2 = responseExternalAnother.getBody().getExampleField();
       }
    
    
       
       //I have many conditions like this

   }

I inspected this topic: Replacing if else statement with pattern. This solution couldn't resolve my problem. This solution solve if else statements but I think it didn't solve finish flow problems.

I need to something like that:

public Response run(Request request){

ResponseExternal responseExternal = ResponseExternalService.callExternalService(externalServiceRequest);

// In case of a failed response from the external service, the flow should be interrupted here and the Response object returned working like this "return response;"

ResponseExternalAnother responseExternalAnother = responseExternalService.callExternalService2(externalServiceRequest2);

// In case of a failed response from the external service, the flow should be interrupted here and the Response object returned working like this "return response;"


 // I want to only return one response.

}

I am looking for a solution method that solves both problems.

Replacing If Else Statement [closed]

I am facing a problem where there are too many if conditions and also multiple return statements. When I write the code like this, it becomes a very difficult code to read. My goal is to get rid of if else statements as much as possible and to finish the code in one place.

Below I will try to explain the problem I am having with a code example.

Let's consider a code where too many external services are called and a response check must be made for each service. For Example:

public class Response{
         private Header header;
         private Body body;
    
         //get set methods
    
    }
    
    

Execute method in service class:

    public Response run(Request request){
    
       
       //Some implementation for external services request
    
       ResponseExternalService responseExternal = callExternalService(externalServiceRequest);
       if(!responseExternal.getHeader().isSuccess()){ //I have to control external service response
          response.setResponseHeader(responseExternal.getHeader());
          return response; //I have to finish flow here
       }
    
       if(Objects.nonNull(responseExternal.getBody() && Objects.nonNull(responseExternal.getBody().getExampleField())){
         ExampleField exampleField = responseExternal.getBody().getExampleField();
       }
    
    
       //continue process
     
       ResponseExternalService2 responseExternal2 = callExternalService2(externalServiceRequest2);
       if(!responseExternal2.getHeader().isSuccess()){ //I have to control external service response
          response.setResponseHeader(responseExternal2.getHeader());
          return response; //I have to finish flow here
       }
    
    
      if(Objects.nonNull(responseExternal2.getBody() && Objects.nonNull(responseExternal2.getBody().getExampleField())){
         ExampleField2 exampleField2 = responseExternal2.getBody().getExampleField();
       }
    
    
       
       //I have many conditions like this

   }

I inspected this topic: Replacing if else statement with pattern

This solution couldn't resolve my problem. This solution solve if else statements but I think it didn't solve finish flow problems.

I am looking for a solution method that solves both problems.

Avoiding the use of instanceOf

I have an abstract class with several childs. I want 4 of them to be able to do a thing which the parent class cannot do. What I have implemented so far would be something like this:

Parent class:

  abstract class Parent {
      
      abstract void doSomething();
  }

Intermediate parent class:

  abstract class IntermediateParent extends Parent {

      abstract void performAction();
  }

Some of the concrete classes:

  class ConcreteClass extends Parent {

      @Override
      protected void doSomething() {
          //do something
      }
  }

The other four concrete classes:

 class ChildConcreteClass extends IntermediateParent {

      @Override
      protected void doSomething() {
          //do something
      }

      @Override
      protected void performAction() {
          //perform action
      }
  }

But now, I found myself in this situation.

Class that triggers the call:

     Parent parent = getParent();
     if(class instanceof ChildConcreteClass){
         ChildConcreteClass childConcreteClass = (ChildConcreteClass) parent;
         childConcreteClass.performAction();
     }

I've been told this is a bad design since type check means I have the wrong kind of abstraction and it violates the Liskov substitution principle. What would you do then? How would you fix this bad design?

lundi 14 novembre 2022

State machine with interface-separated states

In a classic version of states, each state implementing some interface. So we can pass execution to any current state

class Context
{
    private State _state;

    public void MethodA()
    {
        _state.MethodA();
    }

    public void MethodB()
    {
        _state.MethodB();
    }
}

But in my case. I have a gameplay feature. It offers something to buy. And it also has states, like "Active", "Buying", "Preparing", "Finished" and so on. From some of them buying is allowed, from others - not. In more abstract way - each of states implement only part of the context's interface methods. And methods may intersect

class ConcreteStateA
{
    public void MethodA()
    {
        // Do A
    }

    // No MethodB
}

class ConcreteStateB
{
    // No MethodA

    public void MethodB()
    {
        // Do B
    }
}

The question: is it any modification to use state machine this way? The current variation cause to directly check whether it's correct state or not before call in context. State classes hierarchy doesn't save from the problem of state type checking

Need to schedule (cron job) a Java app which is deployed in three instances from pipeline

We have a Java app that will be deployed into three instances at the same time due to the pipeline policy, which does the MongoDB clean-up (deletion of unnecessary records). The Java app will use the cron expression to start its cleanup activity, since all three instances will have the same cron expression, the 3 apps will start to do the cleanup in parallel which is going to create a mess. So, I want to avoid all three instances starting at once instead any one instance should be eligible for cleanup.

Can someone help me to resolve this issue?

dimanche 13 novembre 2022

How can I stay in Kafka cluster? I have to transform a data from kafka topic A and then publish it in topic B. What are the way to achieve it?

It's been a couple of weeks since I started learning Kafka. So, looking for small doubts as blogs and videos don't answer. I have to write an API which should read data (raw text) from Kafka Topic-A, and transform the data (in json) and then publish it in Kafka Topic-B.

What is the best way to achieve it?

I can try writing a simple API and deploy it (say ECS/EKS) outside of the Kafka cluster. While, data is in Kafka cluster. So, API will poll the data from Kafka cluster to EKS cluster for transformation and then send it back into Kafka cluster. I believe this will introduce some kind of latency and it should not be a recommended way.

Second thought I had to have a Kafka transformer connector. This way, I'll remain in Kafka cluster but I think there maybe some security concerns.

I can write Kafka Streams, but this will be deployed as a separate API outside of the Kafka cluster, I guess.

Looking forward to suggestions here.

SwiftUI view API patterns

I am writing a SwiftUI framework package where I want to have some APIs that allow presentation of a view. For these views, I always want them presented above the presenting view as a modal sheet view (I want to disallow having these views embedded as a subview in an app's view).

Apple appears to have very few system APIs like this, but I have found this API - which behaves as I expect:

public func fileImporter(isPresented: Binding<Bool>, allowedContentTypes: [UTType], onCompletion: @escaping (_ result: Result<URL, Error>) -> Void) -> some View

https://developer.apple.com/documentation/swiftui/form/fileimporter(ispresented:allowedcontenttypes:allowsmultipleselection:oncompletion:)

Note that Apple has implemented this as a View extension, so you can simply use like so:

Button("Import..") {
    self.showingFileImporter = true
}
.fileImporter(isPresented: $showingFileImporter, allowedContentTypes: [.pdf]) { result in
    // got result
}

So, I'm trying to use this pattern to implement my own API, something like:

func mySomethingSelector(isPresented: Binding<Bool>, completion: @escaping () -> Void) -> some View

However, I'm unsure how to start the implementation. The first thing I noticed is that fileImporter actually returns some View, but this is not the screen that's actually presented. So, we need to return some kind of wrapper view, that then presents above the wrapper view? (Note that I assume that Apple has actually implemented fileImporter by bridging to UIKit - and possibly out of process. But I just want to use standard SwiftUI for my implementation).

Anyway, hopefully this makes sense. Any guidance appreciated.