jeudi 30 juin 2022

Grafana Loki pattern syntax error: unexpected IDENTIFIER

try to parse with pattern using Grafana + Loki

i am using

{pod=~"backend-deployment-.*"} |~ pattern `<_> - - <_> "<method> <path> <_>" <status> <_> "<_>" "<_>" <_> <duration> [<service>] [<_>] <_> <_> <_> <_> <_>`  

to parse this log

10.110.1.132 - - [27/Aug/2021:02:37:06 +0000] "GET /main.d8e010115d6aba1bd049.js.map HTTP/2.0" 200 10842370 "https://gym.com/students/edit/173" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.1.1 Safari/605.1.15" 34 20.031 [gymauto-gymauto-frontend-service-v1-8080] [] 10.110.5.217:8080 10842370 20.035 200 a7c4299aaa7ea674e91d13315

but there is error

parse error at line 1, col 35: syntax error: unexpected IDENTIFIER, expecting STRING

not like backtick , what is best solution i try " " also ' ' but same error. can not use pattern

spring boot fat service refactoring

I have a very fat class which hold the code business logic of my application - the class is using other service and sometimes other service's repositories to get data needed for its actions.

the entities in my application are just POJO.

So lets assume the service is InventoryService and it has 200 methods that we want to split up, and its uses the Product, Tax, Customer entities.

would it make more sense to transfer the business logic to the entities themselves to reduce the code on the service level? or rather add more services such as ProductInventoryService, TaxInventoryService and etc.. and move some of the logic to them?

any practical examples would be appreciated, the basic design of the app is controller >service >repository where we aim to use Entities between all layers and return DTO to the client from the controller. Thanks

Micro service architecture in Angular

I have 4 angular apps, let say A,B,C and D. Each apps are independent to each other and having their own node_modules.

(However in future there are possibility, I should be able to use components of app A in app B - this could be another discussion)

I want to create an app which should have navigation for A,B,C and D, lets say this app as Shell app. Shell app should be independent of other apps, it should have its own node_modules.

I am trying to achieve here micro-service architecture but I am not sure what should be my approach to achieve this in Angular. Can anyone please guide or help.

mercredi 29 juin 2022

iOS app project modularisation with cocoa pod

I would like to know the pros and cons of following app architecture.

The app will have 5 features: login, feature1, feature2, feature3, and feature4. Refer to the attached UI.

To modularise the features in this application, each feature will be developed as a separate cocoa pod project. The main app will pod these features as libraries. The main app will do the necessary linking, navigation, etc. Refer to the attached architecture.

enter image description here enter image description here

Business Object is duplicating some properties for Presentation Layer

I have a Business Object (Domain Object) representing an employee's shift timings. Its name is EmployeeWorkShift.

using System;

namespace BusinessObjects
{
  public class EmployeeWorkShift
  {
    public long EmployeeWorkShiftId { get; set; }
    public long EmployeeId { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public TimeSpan StartTime { get; set; }
    public TimeSpan EndTime { get; set; }
  }
}

I have a Repository to create, read, update and delete this Business Object in database. Its name is IEmployeeWorkShiftRepository.

I have a Service which has methods to perform operations with this Business Object. Its name is IEmployeeWorkShiftService.

The User Interface call the Service methods for different events:

  1. To retrieve all EmployeeWorkShift objects of an employee, it calls List<EmployeeWorkShift> GetEmployeeWorkShifts(long employeeId); method

  2. To retrieve a specific EmployeeWorkShift object, it calls EmployeeWorkShift GetEmployeeWorkShift(long employeeWorkShiftId); method

  3. To insert a specific EmployeeWorkShift object, it calls EmployeeWorkShift InsertEmployeeWorkShift(EmployeeWorkShift employeeWorkShift); method

  4. To update a specific EmployeeWorkShift object, it calls EmployeeWorkShift UpdateEmployeeWorkShift(EmployeeWorkShift employeeWorkShift); method

  5. To delete a specific EmployeeWorkShift object, it calls void DeleteEmployeeWorkShift(EmployeeWorkShift employeeWorkShift); method

Now in the User Interface, for retrieve/insert/update, the user wants to use some specific formats for dates and times of EmployeeWorkShift object.

One way to solve this issues, is to add 4 string properties in EmployeeWorkShift object which contains the dates and times in specific formats user desires:

using System;

namespace BusinessObjects
{
  public class EmployeeWorkShift
  {
    public long EmployeeWorkShiftId { get; set; }
    public long EmployeeId { get; set; }
    public DateTime StartDate { get; set; }
    public DateTime EndDate { get; set; }
    public TimeSpan StartTime { get; set; }
    public TimeSpan EndTime { get; set; }
    public string StartDateString { get; set; }
    public string EndDateString { get; set; }
    public string StartTimeString { get; set; }
    public string EndTimeString { get; set; }
  }
}

So in User Interface I don't use the original 4 properties of dates and times and instead use the new 4 string properties.

In Service method for retrieve, once I get data from Repository, I translate the original 4 properties of dates and times retrieved from database into specific formats and populate the new 4 string properties.

In Service method for insert/update, I translate the new 4 string properties into original 4 properties of dates and times before calling Repository.

This looks a crude solution to me. Is there a better way to solve this issue?

Select interface implementation according to parameter

What is correct way to select interface implementation according to passed parameter?

Let's have following code:

interface PaymentProcessor {
  public function process(Order $order): void;
}

class CardPayment implements PaymentProcessor {}
class BankTransfer implements PaymentProcessor {}
class OrderService {
  public function __construct( // Load payment processors from DI
    private CardPayment $cardPayment,
    private BankTransfer $bankTransfer,
  ) {}

  // This is what is not clear to me
  private function getPaymentProcessor(string $paymentMethod): PaymentProcessor
  {
    return match ($paymentMethod) {
      'card' => $this->cardPayment,
      'bank' => $this->bankTransfer,
    }
  }

  public function payOrder(Order $order): void
  {
    $processor = $this->getPaymentProcessor($order->getPaymentMethod());
    $processor->process($order);
  }
}

What is not clear to me is how can I get PaymentProcessor by payment method name.

I would use code above, probably extracted to some "Factory". But according to answer at PHP - Using Interfaces, Strategy Pattern and Optional Method Parameters I am probably breaking open/close principle. Then what should be correct way?

Pattern validation Specific HTML

I need to do the following: in an input text you will be forced to write 3 decimal numbers separated by (,) maximum 3 (,) and that only one "." for each number EXAMPLE:

100.10,100.20,100.30

I have tried it like this:

pattern="([0-9]{,1}[,])([0-9]{,1}[,])([0-9]{,1})"

How to model this case in DDD?

I'm facing the issue where either I can't apply DDD, or the case can't be reformulated to fit the DDD rules.

The requirements:

  1. We have a Product and Location.
  2. Change in Location should be reflected in Product which user then sees. Therefore Product references Location.
  3. Same Location might be used in several Products.
  4. Product might be created and deleted at any time point.
  5. Location might be created at any time point.
  6. Location might be deleted only if there is no Product references this Location.
  7. Delete of a Product does not lead to Location deletion.

There are two more entities in the model exist with the same rules as Location, but solution should be the same as with Location case.

My thoughts:

So the problem which I see, that such requirements creates circular dependency on Product and Location. Because they all have own unlimited life cycle they supposed to be separate aggregation roots, but then this violates the consistency boundary, as basically one AR is trying to control another AR. So, this invariant can't be placed in any of those two. Trying to extract this into third one on the top AR also not clear how this would work.

The question:

How can I satisfy such requirements in DDD? Removing the constraint 6 is not an option. I've already tried to negotiate this with business side.

mardi 28 juin 2022

Execute concurrent events with Step Function

I have a use case where I will show tabular data to user on UI where user can take action on each row (say each row will be having selection dropdown to select some column value). User can take action on multiple rows and submit on UI. As user submits , my backend service API will be invoked which will further invoke an external API (API 1) that will further process the selection values provided by user. Also the page will be enabled for certain duration only (say 'X' minutes) for user to take action.

Complete Flow currently looks like (Flow 1) : UI -> middle_layer -> backend_layer (update DDB with selected values) -> external API(API 1)

I also have state machine (AWS Step Function) workflow where a Step invokes a task to send email notifications to user to take action on UI . Email notification will contain UI link for the page mentioned above

Next step in State machine is to wait for 'X' mins and if no action is taken by user on UI , then with some default values for selection dropdown , it calls the same external API (API 1) for all the rows where user has not taken any action

enter image description here

Race condition arises with 2 actors performing similar operation when user takes action on UI just before time ends (Flow 1) and Step function also executes step to execute row with default selection.

Note : I will also update my backend dynamoDb table with the user selected values . Each row that we will show on UI has unique identifier stored in dynamoDb table. Thus , when step function invokes last step to execute rows (where action is not taken on UI) , it will scan ddb table to find which row is not updated and will call the external API (API 1) with default selection value.

I want :

  1. Backend API when user submits the selection for rows to update only dynamo db table and not invoke external API

New Flow : UI -> middle_layer -> backend_layer (update DDB with selected values)

  1. Step function to take responsibility of executing all the rows parallely (trigger based - if an action is taken with some selection value on UI or after 'X' minutes with default values) .

I read about map states of Step function where each row can have their map state and be invoked when some trigger is there (user takes an action) or else will be executed with default value after 'X' minutes .

Can somebody suggest design pattern/ approach for solving this ?

Creating ORM via design pattern [closed]

How can I create my own ORM with PHP design patterns? For example I have below classes:

class User{
 public function insert(){
    //something 
 }
}

class Article{
 public function insert(){
    //something 
 }
}

class DataBase{
 public function connection(){
//something 
}
}

Where is the controller in the MVVM pattern

I was looking for differences between the MVVM and MVC pattern. The MVC pattern has a controller that checks if what page it needs to show. Where is that check in the MVVM pattern?

lundi 27 juin 2022

Resilience4j bulkhead issue with @bulkhead in springboot

I am implementing bulkhead pattern in springboot using @bulkhead annotation. I have this configuration resilience4j.bulkhead: instances: performanceService: maxConcurrentCalls: 2 maxWaitDuration: 1ms

on my service method I have @Bulkhead(name = "performanceService", fallbackMethod = "getDefaultPerformanceData")

However it is not working. When I call performance endpoint I am directly getting the getDefaultPerformanceData().

is there something I am doing wrong.

How to implement a constructor for an abstract class?

I need to convert(refactor) a given class to abstract class, but I'm having trouble to converts this constructor:

  def __init__(self, app_id, client_id, token):
        self.app_id = app_id
        self.entities_url = f"{URL}/v1/schema/{app_id}/en"
        self.attribute_url = f"{URL2}/v1/schema/{app_id}/attr"
        self.eb_headers = {
            'Content-Type': 'application/json',
            'X_Client_ID': client_id,
            'token': token
        }

Best way to efficiently process millions of forms? [closed]

I am building an application to parse forms and call an api endpoint to process those forms depending on the information they hold. The endpoint will return a single data point for each form which will be returned to the client. The whole process is time sensitive, so I want it to be as fast as possible. My only solution so far is to have multiple instances of the api along with a load balancer. Are there any other designs I can look into?

Can a public abstract class create an object of itself inside itself?

I'm learning the chain of responsibility pattern and this is given as the example:

abstract public class AbstractRequest {

    // Each request is identified by a an integer
    // FireRequest: 1
    // LowFuelRequest: 2
    private int requestCode;

    public AbstractRequest(int requestCode) {
        this.requestCode = requestCode;
    }

    public int getRequestCode() {
        return requestCode;
    }
}

abstract public class AbstractHandler {

    private AbstractHandler next;

    public AbstractHandler(AbstractHandler next) {
        this.next = next;
    }

    public void setNext(AbstractHandler next) {
        this.next = next;
    }

    public void handleRequest(AbstractRequest request) {
        if (next != null) {
            next.handleRequest(request);
        }
    }
}

I can't understand how an abstract class can create an object.

Moreover, how can a class be instantiated inside itself?

Wouldn't it cause indefinite recursion?

EDIT: The above questions are raised w.r.t this line: private AbstractHandler next;

I have to make a program integrated into html (i chose javascript/p5.js but i'm still new to it) that creates a 4x4 grid and draws like Armin Hoffman

So far, I've done research into the design by Armin Hoffman (rubber band design). The objective is to create a grid of circles which can be selected to change from white to black and connect these circles in a natural fluid shape that avoids white circles but never traps them. I've been using Codecademy to learn the basics while copying and studying examples on the p5.js website and additionally following The Coding Train on Youtube (specifically: 7.4 mouse interaction and 7.6 clicking on objects).

[Armin Hofmann's Design][1] [1]: https://ift.tt/UcDvVlk

Check @MauriceMeilleur on Twitter between Feb 2021 and Aug 2021

Also: https://discourse.processing.org/t/shape-generator-help-armin-hofmanns-rubber-band-shape-generator/33190

...

Anyway every time i try to make a matrix or array of x and y values stored and to be used in the for loop within the function draw/ function setup, it becomes invalid and it doesn't show the shapes i would like.

I know I'm missing info and I look like a total beginner, I apologize for any migraines i cause.

This is my latest trial:

class boundingBox {

  createBox() {
    stroke(0);
    strokeWeight(3);
    fill(255, 255, 255, 255);
    rect(100, 100, 700, 700);
  }
}

//___________________________________________________________
function Bubble(x, y, x1, y1, x2, y2, x3, y3) {
  // creating a distinction from x/y private and x/y public
  this.x = x;
  this.y = y;

  this.x1 = x1;
  this.y1 = y1;

  this.x2 = x2;
  this.y2 = y2;

  this.x3 = x3;
  this.y3 = y3;

  //this.x = x = [225,350,475,600];
  //this.y = y = [225,350,475,600];
  // creating color public for later use
  this.col = color(255);

  // this expression works to make a public function within a private function
  this.display = function() {
    stroke(0);
    fill(this.col);
    // creating the ability to display the circles within the parameters set
    //ellipse(this.x, this.y, 48,48);

    // in theory this should loop through the x array position values against all the y values in it's array creating multiple circles
    for (i=0; i<4; i++) {
      ellipse(this.x/*[i]*/, this.y, 100, 100);

      ellipse(this.x1, this.y1, 100, 100);

      ellipse(this.x2, this.y2, 100, 100);

      ellipse(this.x3, this.y3, 100, 100);
    }
  }

  //this.move = function() {
  //  //making the circles change position and act like they are moving within air
  //  this.x = this.x + random(-0.5, 0.5);
  //  this.y = this.y + random(-0.5, 0.5);

  //  this.x1 = this.x1 + random(-0.5, 0.5);
  //  this.y1 = this.y1 + random(-0.5, 0.5);

  //  //this.x = this.x + random(1, 0.5);
  //  //this.y = this.y + random(1, 0.5);
  //}

  // again expression to make function but this time implementing a clicking function
  this.clicked = function() {
    // calculating the distance from the circle center to help fill it with color and nothing else
    var d = dist(mouseX, mouseY, this.x, this.y)
      // diameter of the circle
      if (d < 50) {
      this.col = color(0, 0, 0)
    }
  }

  

  //joinBubbles(bubbles); {
  //  bubbles.forEach(element => {
  //    let dis = dist(this.x, this.y, element.x, element.y);
  //      stroke(200, 200, 200, 127);
  //      line(this.x, this.y, element.x, element.y);
  //  });
  //}
  
  
//}

//class lines {
//  constructor(){
//  this.x4 = x4;
//  this.y4 = y4;
//  this.x5 = x5;
//  this.y5 = y5;
//  }
  
//  this.displayLine = function(){
//    stroke(0)
//  }
  
}

let bubbles = [];
let boxii = [];

function setup() {
    
  createCanvas(1536,1250);
  
    for(let i = 0; i<1; i++){
    boxii.push(new boundingBox());
    }
  
    for (let i = 200; i < 860; i+=165) {
    //var x = random (width);
    var x = 200;
    var y = i;
    bubbles.push(new Bubble(x,y/*x1,y1*/));
    }
    
    for (let i = 200; i < 860; i+=165) {
    //var x = random (width);
    var x1 = 375;
    var y1 = i;
    bubbles.push(new Bubble(x1,y1/*x1,y1*/));
    }
    
        for (let i = 200; i < 860; i+=165) {
    //var x = random (width);
    var x2 = 550;
    var y2 = i;
    bubbles.push(new Bubble(x2,y2/*x1,y1*/));
    }
    
        for (let i = 200; i < 860; i+=165) {
    //var x = random (width);
    var x3 = 700;
    var y3 = i;
    bubbles.push(new Bubble(x3,y3/*x1,y1*/));
    }
    
    //for (let i = 0; i < 1; i++) {
    //var x1 = 400;
    //var y1 = 200;
    //bubbles.push(new Bubble(x1,y1));
    //}
    
    //for (let i = 200; i < 1000; i+=200){
    //var x2 = 200;
    //var y2 = i;
    //bubbles.push(new Bubble(x2,y2));
    //}
    
}

    function mousePressed(){
  // checking where the mouse presses so that clicking outside the circle does nothing
  for (let i = 0; i < bubbles.length; i++) {
    
  //for (let i = 0; i < 4; i++) {
  // using this function on all the circles and again using .this to bring properties from /bubble
  bubbles[i].clicked();
  }
  }

function draw() {    background(140);

  for(let i = 0; i<1; i++) {
    boxii[i].createBox();
  }

      for (let i = 0; i < bubbles.length; i++) {
    //bubbles[i].move();
    bubbles[i].display();
  }
  
  if (mousePressed) {
    for (let i = 0; i < bubbles.length; i++) {
    bubbles[i].display(fill(0))
  }}

}

Service and Controller Layers, Business Logic and Project Structure with Node.js

I come from a decade of experience with Java EE, SE and Java with Spring. If there's something that was drilled in me by myself and other fellow developers, was how to make use of design patterns, separation of responsibility, separating definition from implementation, interface segregation, etc. Also, we were always worried about testable code (unit testing and integration tests).

When I was learning Java, there wasn't a single book, magazine or website that didn't implemented things with those rules in mind, to the point of boredom. So we always new how things should be done from an architectural point of view when starting new stuff or maintaining code. With time, projects like Spring Boot and JBoss Seams started to give you out of the box a basic project layout witch you simply followed to success(or at least you should...).

Now that I delve deep in Node.js, I miss that so much. There seems to be only a handful (and I mean it! google it and you'll see...) of people on the web worried about it and trying to teach newcomers how to write good backend code with Node.js.

The smashing majority of people teach you how to boot express and put all of your code (database, logging, mailing, error handling and so on) inside an express route and they walk out of it fine, as if they have done a great service to mankind, and you supposedly are now already able to go out and find a good paying job for yourself.

Of course, when I started learning Java, there was nothing preventing you from using Servlets directly with some JDBC code thrown inside, or even worse, Scriptlet inside JSPs... But if you did that, that meant you were lame, slow-witted, unfit for serious duty, or suffered from some kind of brain damage. The cool guys wouldn't want to be seen around in your company, and you would have lunch alone in the cantina every day, on a table reserved only for yourself.

So here I am, asking please, can you guys point me into the right direction? Or at least, away from the wrong ones. I would appreciate so much to know how you guys for instance implement a service layer, where do you put your business logic? that sort of thing... Do you put it in classes or functions that returns other functions? How to write easily testable code by Mocha for instance... Do I really need a controller layer, or can I trust my routes to cover that responsibility? I'm totally lost on that. Of course, I've come around with some solutions of my own (some even silly...), but I want to hear from the pro, from the battled people, from the veterans.

I'm interested in JavaScript only on the Backend, using Express.js, Socket.io, RabbitMQ, Passport.js, and GraphQL(in the future). Not interested in any rendering engine or template engines, much less JavaScript on the Browser. I'm already very proficient with Sequelizer and Mongoose.

Thank you guys and girls so much and sorry for my frustration, I hope you guys understand, and could perhaps even relate.

dimanche 26 juin 2022

Is there more to the builder pattern than what named optional parameters offer?

Head First Design Patterns only briefly describes the builder pattern in the appendix, without dedicating to it as much space as to other patterns.

Design Patterns: Elements of Reusable Object-Oriented Software treats it just like other design patterns.

Refactoring Guru also considers the builder pattern as a "true" pattern, without relegating it to an appendix.

Anyway, the first and the third sources put a strong focus, in my opinion, on how the pattern is useful to construct an object with just as many "ingredients" as the client wants.

In other words, a bad solution would be having a constructor like this

Ctor::Ctor(Param1* param1, Param2* param2, Param3* param3 /*, and many more */);

that needs to be called like this by a client who doesn't want to set the first two parameters

auto obj = Ctor(null, null, some_param3 /*, null, null */);

whereas the builder pattern would allow one to construct an object like this:

auto obj = Builder().setParam3(some_param3).build();

However, if all the builder pattern solved was the problem above, then I feel like named parameters would offer the same solution (and I'm not the only one to wonder about it). In turn, I'd have called the "builder pattern" the "named parameters pattern", that guides you to implement this feature in a language that lacks it.

Indeed, there are sources on the web that claim other languages don't need this pattern (or, if you like, the pattern is just less visible in them):

  1. here a convincing example of how Clojure's destructuring power just gives all you need as regards passing only the arguments you want to a constructor;
  2. a research engineer at Facebook (at least at the time he wrote this stuff), claims that Haskell's type classes and smart constructor are all you need to go on without the builder pattern, even though he doesn't go into any depth on the topic.

So, in view of the above point 1, my question is whether the builder pattern really offers more than a language feature like named parameters.

(I'm leaving point 2 out of the question because I'm not sure I've understood it.)

Can we force all implementations to be singleton (objects)?

Let's say we have an abstract class (same question for traits also):

abstract class TypeParser[C <: Changes : TypeTag] extends Serializable {

  val enrichmentType: EnrichmentType
  protected def parseChanges(row: Row): C

}

Where implementations look like the following:

object PlaceholderParser extends TypeParser[PlaceholderChanges] {

  val enrichmentType: EnrichmentType = PlaceholderType
  override protected def parseChanges(row: Row): PlaceholderChanges = ???

}

The above implementation is a singleton, however, it can't be forced to be a singleton for future implementations. So one can simply implement it as a class, for example:

class PlaceholderParser2() extends TypeParser[PlaceholderChanges2] {

  val enrichmentType: EnrichmentType = PlaceholderType2
  override protected def parseChanges(row: Row): PlaceholderChanges2 = ???

}

Is there any way of forcing implementations to be a singleton?


side question: is there any advantage of forcing it?

samedi 25 juin 2022

Howto do this in Dartt $current_segment =~ s/([a-zA-Z]+)\.([a-zA-Z]+)/$1 punto $2/g;

I do appreciate if anyone could help me with this seemingly easy question:

$someText =~ s/([a-zA-Z]+)\.([a-zA-Z]+)/$1 : $2/g;

This perl statement finds all patterns of the form www.xyz and changes them to www:xyz. I need an equivalent code in Dart; I am new to Dart. Thanks, Bid

Reuse and extend Angular component logic and template in child component

I have a form that is used to choose customer details. It is used in more than one places in my app but with extended logic and UI. I would like to be able to reuse my basic component in other components but also to extend(or override) it's template and logic. To don't have to copy paste the same UI & logic in each component and have one common basic place for changes.

base component with template & logic:

@Component({
selector: 'app-base',
template: `<h1> Base component </h1>
           <label>getLabel() </label>
           <ng-content> </ng-content> `
})

export class BaseComponent implements OnInit {

constructor() {
    // base init        
}

ngOnInit(): void {
    // base ngOnInit
}

getLabel(): string {
    return "label";
    }
}

Parent component that is suppose to reuse template, being able to extend methods and lifehooks and extend the UI as well.

@Component({
selector: 'app-parent',
template: `<app-base> <h1> extended </h1> </app-base>`, 
   })

export class ParentComponent extends BaseComponent {

constructor() {
    super();    
}

ngOnInit(): void {
    super.ngOnInit();
    // extended fancy stuff        
}

getLabel(): string {
    let a = super.getLabel();
    return a + "a"; // extended logic       
       }
}

It sort of works using this approach but one problem that I noticed is that the ngOnInit is called twice. Once from the base component since I'm using its template in parent component and second time because of parentComponent ngOnInit being triggered.

Question: Is there a way to reuse the template like using <app-base></app-base> with all shared logic in one place but without actually executing the lifehooks twice from both components?

Solution(?): The only thing that I came up is to wrap the basic component logic with a service. So there will be something like this:

@Component({
selector: 'app-base',
template: `<h1> Base component </h1>
           <label>getLabel() </label>
           <ng-content> </ng-content> `})
export class BaseComponent implements OnInit {

constructor(IBasicService basicService) { // <-- injected service
    // base init        
}

ngOnInit(): void {
    this.basicService.onInit(); // <-- using ngOnInit from service
    // base ngOnInit
}

getLabel(): string {
    return this.basicService.getLabel(); <-- using getLabel from service
     }
}

With this approach I'll be able to simply reuse my base component but with different injected services that will implement IBasicService interface and also simply extend the UI using or but is this correct way? Isn't there any better solution?

Thanks in advance!

How scared should I be of creating new DbContexts?

I often has a situation like this. I have to create a bunch of lines/row to show the user for each row in some database table. And if the user then clicks on the row it should update in the database.

One way of handling this is scetched below (It might not compile, but I think you get the idea).

This creates and closes a DbContext everytime the user interacts.

public class MainViewModel
{
   public ICollection<RowViewModel> Items 
   {
      get
      {
        var allRows = new List<RowViewModel>();
        using var dbContext = CreateDbContext();
        foreach(var item in dbContext.items) 
        {
           var row = new RowViewModel(item);
           allRows.add(row);
        }
        return allRows;
      }
   }
}

public class RowViewModel
{
  private Item _row;
  public RowViewModel(Item row)
  {
    _row = row;
  }
  public void OnDoubleClick()
  {
     using var dbContext = CreateDbContext();
     dbContext.Items.Attach(_row);
     _row.SomeValue += 1;
     dbContext.SaveChanges();
  }
}

An alternative would be to keep the DbContext alive in MainViewModel and then pass it around.

public class MainViewModel : IDisposable
{
   private MyDbContext _dbContext;

   public MainViewModel()
   {
     _dbContext = CreateDbContext();
   }

   public void Dispose()
   {
     _dbContext?.Dispose();
   }


   public ICollection<RowViewModel> Items 
   {
      get
      {
        var allRows = new List<RowViewModel>();
        foreach(var item in _dbContext.items) 
        {
           var row = new RowViewModel(item, _dbContext);
           allRows.add(row);
        }
        return allRows;
      }
   }
}

public class RowViewModel
{
  private Item _row;
  private MyDbContext _dbContext;
  public RowViewModel(Item row, MyDbContext dbContext)
  {
    _row = row;
    _dbContext = dbContext;
  }
  public void OnDoubleClick()
  {
     _row.SomeValue += 1;
     _dbContext.SaveChanges();
  }
}

I'm torn between the two designs.

Any thoughts/preferences?

Yours
/peter

vendredi 24 juin 2022

Each blog page to a different component or have static html files and one component?

So I’m new to angular and was making a blog website in angular. Right now it has 4 blog posts in total.

What I’m doing right now is I’m storing the title, date, author, image and the whole blog in json files and read them according to the blog I’m visiting. I have one component named blog which which gets rendered according to the JSON data it gets.

I want to know what design philosophy you guys use. Do you have one component named blog post and have static JSON files or do you have each blog a different component.

The problem is if I have each blog different component, then it removes the scalability of blogs, say I add new blogs. But this allows me to have a lot of feature rich web page with images and styles.

If I have each blog, different JSON and a single component; then my website is dynamic but I have to store HTML for each blog in JSON which would be a very big line for JSON and doesn’t feels natural. Also I cannot simply save texts because I want to format web page, have images in the middle, have some text on bold.

Any suggestions?

numba @jit(nopython=True): Refactor function that uses dictionary with lists as values

I have several functions that I want to use numba @jit(nopython=True) for, but they all rely on the following function:

def getIslands(labels2D,ignoreSea=True):
    islands = {}
    width = labels2D.shape[1]
    height = labels2D.shape[0]
    for x in range(width):
        for y in range(height):
            label = labels2D[y,x]
            if ignoreSea and label == -1:
                continue
            if label in islands:
                islands[label].append((x,y))
            else:
                islands[label] = [(x,y)]
    return islands

Is there any way to redesign this function so it's compatible with numba @jit(nopython=True)? The JIT fails since the function uses features of python dictionaries that are not supported (i.e., dictionaries containing lists as values.)

numba==0.52.0

Iterating over an Service API with different request

I have a requirement of to run a script which iterates over an existing API of a service with different requests. We could write it for a single API, I wanted to create a pattern out of it and reuse the iterating logic to any API with writing the boilerplate code of iterating every time. Can you pl. suggest an applicable design pattern or any other way we can generalise this .

Programming language : preferably Java

Best design for a generic reader [closed]

I'm trying to implement a text reader, agnostic to the document nature/type (reading word, pdf, etc ...).

Each reader has:

  • common functionnality and attributes: for exemple we want to extract whole text of the file in input and store the text in a "fulltext" attribute. So i created a Document class to store the common attributes and i have to get a function to read the whole text.
  • but for further applications needs (like NLP application for example), i am interested by specific attributes specific to document type. For example, with word api we can extract the text with a granularity "paragraph" with the win32 api since word let the possibility to the word creator to embed a portion of text with paragraph delimitation. In that way we can get the author intention structuring its document. (getting this paragraph splitting in pdf is not easy since the "paragraph spacing" differ from a pdf to an other, way more complicate thant retrieving a sentence splitting easy with regex). This functionnality can be really interesting for my further nlp treatment, and since only the win32 api can help me to do that i need to treat that inside the read_doc function. (I can imagine other specific things: for exemple for read_pptx extract text at the slide granularity,...)

I feel like my current api and implementation choice is not good and am a bit lost how to design all that. What would you suggest?

I was thinking:

  • to remove the "document" input in read_pdf, read_img etc ... (it is not natural to pass that as a variable) which is noit natural and kind of ugly
  • perhaps create read_doc, read_ppt class rather than function to allow different method (to extract whole text but other functionality) which would inherit from a generic Reader class (kind of abstract class). This Reader class would have minimally: a document attribute, and an extract_fulltext method.
import os
import fitz
import docx
import win32com.client as win32
import subprocess
from tempfile import TemporaryDirectory
import traceback

class Document():
    def __init__(self,filepath):
        self.filepath = filepath
        self.filename = os.path.basename(filepath)
        self.readable = None
        self.fulltext = ""
        self.doctype = None
        self.extension = filepath.lower().split('.')[-1] 

    def to_dict(self,drop=None):
        data=vars(self)
        return data

def read_pdf(filepath,document):
    try:
        doc = fitz.open(filepath)
    except Exception as e: 
        logger.error("Lecture PDF impossible.|{}|{}".format(e,filepath))
        raise
    fulltext = []
    pagetext = {}
    for i,page in enumerate(doc):
        page_text = page.get_text()
        pagetext[i]= page_text
        fulltext.append(page_text)
    document.fulltext = '\n'.join(fulltext)
    document.pagetext = pagetext
    return document

def read_pptx(filepath,document):
    return ""

def read_docx(filepath,document):
    return ""

def read_img(filepath,document):
    return ""


def is_textdoc(text):
        """
        Based on volume of text (nchar), sort doc in two classes: scanneddoc (image),  textdoc
        :param text: text of the pdf file
        :return : bool True if scanned image, false in case of textual pdf
        """
        nchar = 20
        if len(text) > nchar:
            return True
        else:
            return False

def build_doc(filepath):
    document = Document(filepath)
    ext = filepath.lower().split(".")[-1]
    #import pdb;pdb.set_trace()
    app_ref = {'pdf':read_pdf,'doc':read_doc,'docx':read_docx,'pptx':read_pptx,'ppt':read_ppt}
    try:
        print("Reading: {}".format(filepath))
        document = app_ref[ext](filepath,document)
        document.readable =True
    except Exception as e:
        logger.error("Format not read.|{}|{}".format(e,filepath))
        traceback.print_exc()
        document.readable = False
    if is_textdoc(document.fulltext):
        document.doctype = 'text'
    else:
        try:
            document = read_img(filepath,document)
            if is_textdoc(document.fulltext):
                document.doctype = 'img'
        except:
            raise
    return document

jeudi 23 juin 2022

Self learning python for data analysis. Dataframes and designing programs with functions, classes, and modules

I wanted see if folks here could help expedite my efforts to self learn python with the intent of doing data analysis using dataframes and designing programs with functions, classes, and modules. I've had a few classes in the past but never spent much time putting the knowledge into practice. The focus in the course work was not too practical and was pretty academic. Never heard of a dataframe until a coworker pointed them out for example. If there are any resources whether books or what have you, your suggestions are welcome. Thanks for any help in my efforts!

Specific repository pattern with configurable fluent api

I'm trying to extend the capabilities of the Specific Repository Pattern by implementing fluent configuration for the navigation properties eager loading (on top of the automapping).

What I'm trying to achieve is to have this experience:

ISpecificRepository repo = new SpecificRepository()
var entries = repo.WithIncludes(x => x.NavProperty).GetAllTheEntriesWithLevel(5);

Here's my IRepository interface

public interface IRepository<TEntity, TDto>
{
    Task<List<TDto>> GetAllAsync(params Expression<Func<TDto, object>>[] properties);

    Task<TDto> GetAsync(object id);

    Task AddAsync(TDto dto);

    Task AddRangeAsync(IEnumerable<TDto> dtos);

    void Update(TDto dto);

    void Remove(TDto dto);

    void RemoveRange(IEnumerable<TDto> dtos);

    Task<bool> ContainsAsync(Expression<Func<TEntity, bool>> predicate);

    Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate);

    IRepository<TEntity, TDto> WithIncludes(params Expression<Func<TDto, object>>[] properties);
}

Now, I build a base abstract implementation called RepositoryBase

public abstract class RepositoryBase<TEntity, TDto> : IRepository<TEntity, TDto>
{
    protected readonly DbSet<TEntity> _set;

    protected readonly IMapper _mapper;

    private readonly DbContext _context;

    /// <summary>
    /// Backing field for PropsToInclude.
    /// </summary>
    private Expression<Func<TDto, object>>[] _properties;

    protected RepositoryBase(DbContext context, IMapper mapper)
    {
        _context = context;
        _mapper = mapper;
    }

    /// <summary>
    /// Gets the rroperties to eager load in the resultset.
    /// </summary>
    protected Expression<Func<TDto, object>>[] PropsToInclude
    {
        get
        {
            if (_properties.Length == 0)
            {
                return Array.Empty<Expression<Func<TDto, object>>>();
            }

            Expression<Func<TDto, object>>[] propertiesToReturn =
                _properties.Select(x => Expression.Lambda<Func<TDto, object>>(x.Body, x.Parameters)).ToArray();
            _properties = Array.Empty<Expression<Func<TDto, object>>>();
            return propertiesToReturn;
        }

        private set
        {
            _properties = value;
        }
    }

    public async Task<List<TDto>> GetAllAsync(params Expression<Func<TDto, object>>[] properties)
    {
        IQueryable<TEntity> entities = _context.Set<TEntity>().AsQueryable();
        return await _mapper.ProjectTo<TDto>(entities, null, PropsToInclude).ToListAsync();
    }

    public async Task<TDto> GetAsync(object id)
    {
        TEntity entity = await _context.Set<TEntity>().FindAsync(id);
        return _mapper.Map<TDto>(entity);
    }

    public async Task AddAsync(TDto dto)
    {
        TEntity entity = _mapper.Map<TEntity>(dto);
        await _context.Set<TEntity>().AddAsync(entity);
    }

    public Task AddRangeAsync(IEnumerable<TDto> dtos)
    {
        IEnumerable<TEntity> entities = _mapper.Map<IEnumerable<TEntity>>(dtos);
        return _context.Set<TEntity>().AddRangeAsync(entities);
    }

    public void Update(TDto dto)
    {
        TEntity entity = _mapper.Map<TEntity>(dto);
        _context.Set<TEntity>().Attach(entity);
        _context.Entry(entity).State = EntityState.Modified;
    }

    public void Remove(TDto dto)
    {
        TEntity entity = _mapper.Map<TEntity>(dto);
        _context.Set<TEntity>().Remove(entity);
    }

    public void RemoveRange(IEnumerable<TDto> dtos)
    {
        IEnumerable<TEntity> entities = _mapper.Map<IEnumerable<TEntity>>(dtos);
        _context.Set<TEntity>().RemoveRange(entities);
    }

    public async Task<bool> ContainsAsync(Expression<Func<TEntity, bool>> predicate)
    {
        return await CountAsync(predicate) > 0;
    }

    public Task<int> CountAsync(Expression<Func<TEntity, bool>> predicate)
    {
        return _context.Set<TEntity>().Where(predicate).CountAsync();
    }

    public IRepository<TEntity, TDto> WithIncludes(params Expression<Func<TDto, object>>[] properties)
    {
        PropsToInclude = properties;
        return this;
    }
}

Now, with the base methods implemented, I declare a specific Interface

public interface ISpecificRepository : IRepository<EntityA, MappedEntityA>
{
    Task<List<MappedEntityA>> GetAllTheEntriesWithLevel(int level);
}

And let the implementation to implement it and extends the base to inherit base implementations.

public class SpecificRepository : RepositoryBase<EntityA, MappedEntityA>, ISpecificRepository
{
    public SpecificRepository(DbContext context, IMapper mapper)
        : base(context, mapper)
    {
    }

    public async Task<List<MappedEntityA>> GetAllTheEntriesWithLevel(int level)
    {
        IQueryable<EntityA> entities= _set.Where(x => x.Level = level);
        return await _mapper.ProjectTo<MappedEntityA>(entities, null, PropsToInclude).ToListAsync();
    }
}

The problem with this approach is that the RepositoryBase expose a WithIncludes() method which returns an IRepository and then the specific repository implementation (that inherits it) does not have its specific methods after calling the method itself. I know that this implementation violates SRP but in which way can I achieve what I mentioned before?

Add: The desired is to centralize the implementation in a BaseClass (i.e. RepositoryBase) without the needing of implementation for each new Repository that I want to create.

Generic factory for type T

I've been a software developer for more than a year now and I wanted to try and create my own generic factory, to instantiate new objects.

Overall the goal is, to create a generic solution to instantiate different kinds of objects from the Java Collections, with different arguments in the diamonds.

The problem: I'm receiving multiple errors up on calling that method.

  • java.lang.NoSuchMethodException: java.util.List.<init>(com...AccountDTO) after I call the method.
  • Change variable accountDTOs to type List, instead of List<AccountDTO> warning in the editor.

The code which doesn't work: I've written a brief explanation in a commented line of code

public static <T extends Collection<?>, E> T getInstance(Class<T> t, Class<E> args) {
    try {
        // This is not working because I can not pass the identifier as a constructor argument
        return t.getDeclaredConstructor(args).newInstance(args);
        // This is the goal I _kind of_ want to achieve
        return new T<E>();
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalArgumentException();
    }
}

And last but not least, the line of code, which is calling the factory to create a new instance of that object:

List<AccountDTO> accountDTOs =  EntityFactory.getInstance(List.class, AccountDTO.class);

mercredi 22 juin 2022

C++ Covariant Return Types for Multiple Hierarchies

Okay I've scrounged around the depths of SO and haven't been able to understand why this implementation of covariant return types is not working.

Say I have a return type hierarchy as follows:

class BaseData{
public:
    BaseData() = default;
    virtual ~BaseData() = 0;    //can't implement this
};
class DerivedData : public BaseData{
public:
    DerivedData() = default;
};
class DerivedData2 : public BaseData{
public:
    DerivedData2() = default;
};

and then I have some other hierarchy which would like to change which type of data is returned, depending on the class type. E.g.

class A {
public:
    A() = default;
    virtual ~A() = default;
    virtual BaseData* get_data() = 0;    //inheriting classes must implement this
};
class B : public A{
public:
    DerivedData* get_data();
};
class C public A {
public:
    DerivedData2* get_data();
};

Why do I get an "invalid covariant return types" error here since the derived data classes are instances of the base data class?

What design pattern is preferred here when I am trying to change the return-type depending on the sub-class, but would like to specify this function in the base through a pure virtual function?

Ideal environment for web service usage

According to the response (numerical data) from any json web service, I will update the database according to the case of large-small. I want it to do this every 20 seconds. What is the ideal environment for this (connecting to json, extracting and updating data..)?

Example json web service link; https://abcde.com/json/

Technicial Specifications;

  • Windows Server
  • MSSQL Server database

A) Opening a new stored procedure in the database and calling it continuously with job

B) In the web browser on the server, the page with the json link on the web page that I coded myself is open 24/7 and the page is constantly automatically refreshed.

C) By establishing a database connection in the desktop software, it constantly checks and processes this loop with linq.

D) you create

What is the best environment, taking into account the ram-cpu and possible compute-intensiveness?

How to provide an opaque public handle in public API while still able to touch the implementation detail inside internal component?

I am refactoring a biometric recognition SDK, which public API provide feature extraction and some CRUD feature management interface like:

class PublicComponent{
public:
  FeaturePublic extract_feature();
  int add_feature(const FeaturePublic&);
  void update_feature(int id, const FeaturePublic&);
  void delete_feature(int id);
}

The actual feature that all other private implementation component must to deal with is complicated, it contains many fields that we don't want to expose to the API user, like:

struct FeatureDetail{
  int detail1;
  int detail2;
  // ...
  float detailN;
};

And basically the PublicComponent just forward its job to these internal components.

So the gap occurred, basically all the public API accept or give back FeaturePublic as argument/result. However all other existed internal implementation heavily depends on FeatureDetail, they must touch the internal data member of feature. It just seems that we need to retrieve concrete type from the type erased public handle, but unable to publish the retrieve method. I've came up with two solutions, but either of them seems quirky.

Solution 1

Just use type erased raw buffer like std::vector<std::byte> or std::pair<std::byte*, size_t> as FeaturePublic.

It is simple, however, the cons is pretty straightforward: We just throw away the type safety that we already have, and i have to insert all the input data integrity check and serialize/deserialize code at all the public API border even though the caller might just add a feature that generated right before.

Solution 2

Use pimpl like idiom to hide FeatureDetail inside FeaturePublic.

// public api header
class FeatureDetail; // forward declartion

class FeaturePublic{
private:
  std::unique_ptr<FeatureDetail> detail_;
};

Under which we can maintain the type safety, however, to let the internal component to touch the concrete type FeatureDetail, we must have some way to let them retrieve a FeatureDetail from PublicComponent passed FeaturePublic. But since the detail_ field is a private member, The two ways that i can think of is to provide a get_raw method on FeaturePublic or make the field public, any of them seems pretty ugly.

mardi 21 juin 2022

Which of the following Design Patterns doesn't respect Dependency Inversion Principle?

Out of these design patterns: Factory Method State Observer Strategy Command Simple Factory Decorator I have to specify which one doesn't respect the Dependency Inversion Principle. I'm guessing it's Simple Factory?

Design Architecture for Async API Service returns JobID

I guess it's super basic, but I don't even know the name of the design to even search for it (and I've looked).

I need to create an API service in golang that upon request from a client, it responses with JobId for the client to check on some subscription or something. When the service is done executing the request (preparing a file for instance) it would publish it to some channel/broker/topic for the client to pick it up.

What is the name of such design so I can look for examples? Thank you

lundi 20 juin 2022

Designing composable function

I am new to android composables. I just had a discussion with my senior on the way we write composable functions. He suggested that passing objects as funtions parameter would result in recomposition if object value changes (not state objects. plain data objects like json) and it generally a bad practise If functions acccepts 10-12 parameters is a bad way to pass data class as funtion params?. For normal funtions we can go for builder patterns but what about compose?

@Composable
fun reusableComp(val params:Params){
   ........
   .........
 }

Vs

@Composable
fun reusableComp(val param1:String ,val param2:Int?=0..........,val pram12:Int?=0){
   ........
   .........
 }

Make microservice application resilient to db downtime

We have a microservice application which is saving the data into an Oracle Db.

So far the DB is our single point of failure which we want to improve (we are using a single Oracle DB with a cold failover instance).

Now the company is asking us to upgrade the oracle DB, the issue is that it requires downtime. For that reason we were thinking about:

  1. add a global/geo replicated cache layer (e.g redis) between the microservice and the DB
  2. for each new record that should be saved on the db:
    1. Add the record in the cache (storing the entries on the HD in case the whole cache layer crashes)
    2. throw an event to a queue (we have RabbitMQ). On the other side of the queue we can create a new service to consume the events and add them to the DB in an asynch way.

It's basically adding a write-behind cache layer.

In the above scenario we are confident that we can save easily 1 week data in the cache or more.

If the DB is down the new service which is listening to the queue will simply re-trying adding the rows in the DB, as soon as an event is added to the Db then the event can be ack and the next one will be consumed. In this way, if the DB is down or if we have to do some maintenance, it should not affect the main application: the users can still "save" the data and retrieve it (with the 1 week max constraint whenever the db is down).

The down side is that the architecture is more complex and we can have now data eventual consistency.

Is there another design pattern to better deal with database downtime without having the users feel that something is wrong?

Do you know any already-existing tools that we can use to automatically read an event from Rabbit and save it in the db? (we are already doing it with logstash to automatically forwards some rabbit events to elastic).

The next step would be to have a cluster of DB (cassandra,mongo etc) but for now we do not have the capacity for that.

dimanche 19 juin 2022

Where to put implementation templates realized by C macros?

I want a write a C library with macro-templates depending on a type.

A very simplified example for the header file:

#define PAIR_TEMPLATE(Type) \
typedef struct { Type a[2]; } PAIR_ ## Type; \
Type Pair_ ## Type ## _Sum (PAIR_ ## Type *pPair); \

PAIR_TEMPLATE (char)

PAIR_TEMPLATE (int)

This should expand to

typedef struct { char a[2]; } PAIR_char;
char Pair_char_Sum (PAIR_char *pPair);

typedef struct { int a[2]; } PAIR_int;
int Pair_int_Sum (PAIR_int *pPair);

The implementation for Sum can also be templated:

#define PAIR_Sum_TEMPLATE(Type) \
Type Pair_ ## Type ## _Sum (PAIR_ ## Type *pPair) { \
  return (Type) (pPair->a [0] + pPair->a [1]); \
}

Please note that this is only a very simplified example. My real template will have multiple other functions and will be also applicable for almost any struct type. Think of it as of a template for a dynamic array.

My library itself will use this template for some data types. On the other hand, the user of the library should also be able to use this template for other types.

Now I am facing a design problem:

If I put the implementation template (not the header template!) into a separate code file which is supposed to be compiled in a translation unit different from the user's code, it will be difficult for the user to expand the implementation template for his own types.

On the other hand, if I put the implementation template into the library header file such that the user of my library will expand the implementation in the same translation unit, then he will have difficulties ensuring that, for every type, there is at most one implementation expanded.

Is there a good design solution for this conflict? Thank you.

find all subpaths of paths starting at the root that are labeled with pattern P

I am currently studying Dan Gusfield book (Algorithms on Strings, Trees and Sequences) and I am trying to solve the below exercise:

Suppose we are given a tree where each edge is labeled with one or more characters, and we are given a pattern P. The label of a subpath in the tree is the concatenation of the labels on the edges in the subpath. The problem is to find all subpaths of paths starting at the root that are labeled with pattern P. Note that although the subpath must be part of a path directed from the root, the subpath itself need not start at the root (see Figure 2.3). Give an algorithm for this problem that runs in time proportional to the total number of characters on the edges of the tree plus the length of P.

enter image description here

To be honest i am completely stuck and I can't think of an algorithm that can solve this. I guess we will use dynamic programming?

Which Design Pattern(s) for CPQ - Configure Price Quote

I’m going to create a Configure Price Quote functionality. Example you have a table which you can configure:

  • Size of the table
  • 5 different table tops
  • 6 different table legs
  • 10 different colors for the table legs

You start by selecting the size of the table. It limits the number of table tops you can select (some table tops does not exist in some sizes). After you have selected the table top – the options of selectable legs are now limit etc. Any suggestions for which design pattern/patterns I should look into?

A more advanced but preferable solutions would be that you can start anywhere in the sequence e.g., selecting the table legs and all the other –color, size, and table top would all be limited.

Polymorphism on a REST service

I am trying to clean and refactor my service code which currently looks like this-

public void generateBalance(Receipt receipt) {

if (receipt.getType().equals(X) && receipt.getRegion.equals(EMEA)) {

// do something to the receipt that's passed 

} else if (receiptType.equals(Y)) {

// do something to the receipt 

} else if (receipt.getRegion.equals(APAC) {
// call an external API and update the receipt
}....

...
// finally

dataStore.save(receipt);

Basically there's a bunch of conditionals that are in this main service which look for certain fields in the object that is being passed. Either it's the type or the region.

I was looking to use this design pattern- https://www.refactoring.com/catalog/replaceConditionalWithPolymorphism.html However, I am not sure how this would work for a service class. Currently my REST handler calls this particular service. Also how can I do polymorphism for both the "receiptType" and "region"?

Is there a way I can just do all the updates to the receipt once in different services, then finally save the receipt at one location? (maybe a base class?) I am really confused on how to start. TIA!

samedi 18 juin 2022

How to use decorator pattern while using builder pattern? [closed]

I'm trying to do class library for client.I'm writing classes that do a logging. And these logs have more than one feature. For example, printing in HTML or XML format, adjusting the font size and color, the name of the logging person, logging level, logging to Oracle or mssql database, etc. I made this work using the builder pattern. However, when using the client, I want it to be able to change these names or add new features. I thought the most suitable design pattern for this was the decorator, but I don't know how to use it with the builder pattern. Do you have any code example for this Or does anyone have a better suggestion? How can I handle this problem ?

Assigning function output to many variables: good or bad practice

Is it an unusual design pattern to assign output of function to many variables? Imagine each variable below representing complex data, such as nested dictionaries.

def step_1():
    a = ...
    ...
    i = ...

    return a, b, c, d, e, f, g, h, i

def step_2(a, b, c, d, e, f):
    ...
    return j
    
def step_3(g, h, i, j):
    ...
    return k


a, b, c, d, e, f, g, h, i = step_1()
j = step_2(a, b, c, d, e, f)
k = step_3(g, h, i, j)
# do something with k

Somehow it feels odd doing things like

a, b, c, d, e, f, g, h, i = step_1() or

return a, b, c, d, e, f, g, h, i or

j = step_2(a, b, c, d, e, f).

vendredi 17 juin 2022

Which design pattern I can use for this project?

I will develop a document management application. Users will upload documents to the application. The document can be in any format.

The client portfolio of the application consists of holdings. Users in the human resources, sales and information technologies departments within the Holding can use the application.

The document uploaded by each user is uploaded to the folder of the department they work in. Users can open the document and make changes through the application. This change consists of changing the document name for now. A version of the document is created with each change.

Users can revert to previous versions if they wish. The application has a report section that shows how many users and documents there are. When the user and the document are added, the numbers here must be updated instantly. The application should log when users upload and modify documents. It should also log errors that may occur during operation. To perform these log operations The log library detailed below should be used. However, this library should be developed so that it can be used in other projects.

The data that should be in the system while writing the log are the log message, the user who performed the operation, the log date and the log level. Developers who will use this library should be able to add different data to them if they wish, or change the name of the data containing this information. The system should be able to log data in HTML or Text format. Developers using the library should be able to choose from these formats. Logs can be written to a file or to a database. The system should support MSSQL and Oracle databases. It should be noted that there may be different databases in the projects to be used. When the database preference is made, the connection settings to be used will be taken.

Developers using the library should be able to do the work they want before or after logging. For example, when logging the file, it should be able to make folders and filings as it wishes. The system should be able to view the recorded logs. Developers using the library should be able to customize when viewing logs if they wish. They can view it as it is or by changing the font size and color. One can change, just as both can change.

When using this log library, settings such as in which format the log will be and which source it will be saved should be defined in a config file. This config file can be XML or JSON. In whatever format the developer uses the config file, he should have the settings read by calling the appropriate structure in the system. If logging to the database is preferred, the connection string information should be transferred to the system via this config file.

Approaches to Apply Incremental Row Changes Based on a RAW table?

I have inherited a collection of data that is divided into two parts: A master record file and many incremental update files. These records are saved in a single table. I have two primary requirements:

  1. I would like to properly update my database model to have an active table tracked as a temporal table.
  2. I would like to start with my master record data and then apply each incremental update file from the raw table in some defined order (a date received column).

Is there a method for doing this without a cursor, while loop, or SSIS job to load each file again? If such a way exists, I would basically configure my new temporal table and then merge each incremental file in my specified order. Any approaches to consider?

How to better engineer "generic argument list"?

I find myself hesitating between multiple solution but never finding something that I’m fully satisfied with when it comes to encapsulate some functionalities.

This came especially problematic in my recent desktop GUI projet where I want to generalize a functionality that encapsulate a set of well-defined views along with some logics, but one view must be “injected” and can take multiple forms that is largely up to the user. To do that, I defined an interface for the view that can be passed through a constructor.

A process is launched by the user and the result is return to the caller by callback once finished.

the interface:

interface ICustomMecPathViewModel : IScreen, IMecPathViewModel
    {
        public Dictionary<string, object> getStepResult(); //subview must return its result 
        public void Reload(Dictionary<string, object> preset); //subview will be reloaded for each new iteration
    }

the constructor:

public PreparePathViewModel(ILogger logger, IConfiguration config, ICustomMecPathViewModel customParameterViewModel, ITool tool, Action<MecPathModel> callback)
        { ...  }

The issue here is that this process includes multiple steps and the the view implementing ICustomMecPathViewModel might need different configuration for these steps. I see here two solution and struggle to find the best answer (maybe none of those two ? )

Either I can pass something very generic such as a list of Dictionnaries (the list to allow various configurations depending on the step) with no type restriction as it is for my preset values:

List<Dictionary<string, object>> settings

Or I can pass a List of intefaces where I define exact settings, adding new elements each time I add a new configuration:

List<IStepSettings>

the First solution is not pleasing to be because of the absense of type check and the latter might become an interface with a lot of random stuff that have no coherence between them, which just feels wrong. (and it would no be as extensive as a general API)

The first solution appears better to me for this reason. And my thought are : generalizing things come with a cost and this is it.

What do you think ? Something wrong with this kind of design ? Another better solution ?

jeudi 16 juin 2022

What do red, blue, green functions mean in software development? [closed]

In a PHP developer discussion group red, blue, green functions were often mentioned. To be honest, I never heard this before and didn't know what it meant. I did a search for "what mean green red blue functions". I did not find a simple explanation. The best I found was a blog article from a game developer. Unfortunately I did not understand his text. I hope there is a short and simple explanation of what is meant by this. Thank you!

My Note: I suspect it is not a PHP specific question but a general question. Maybe a design pattern?

SML - See if two unordered lists are equal (have same values, and the values appear the same amount of times)

Like the title says, I'm trying to see if two unordered lists include the same values and if these values appear the same amount of times in these lists. The assignment given asks not to order the lists. Here's what I've done so far:

  • my logic was to compare recursively if the second list (from now on l2 ) includes the hd (= first element) of the first list ( from now on l1 ) if it does, compare the tl of l1. And as long as I call this isEqual function I would remove the hd of l1 and the first position in which the same value appears in l2. My base case would be that the 2 lists have different lengths then I would know for sure they are not equal. Here's the code:
fun doesExist l =
    List.exists (fn x => x = true) l
; (* returns true if there's at least one 'true' in the list of bool *)

fun getFirstIndex target (a::b) index =
    if (a::b) = []
    then index
    else
        if target = a
        then index
        else getFirstIndex target b index+1
; (* returns the index of the first element = to 'target', in this case 'true', 
looking into the list (a::b) *)

fun delete (_,   nil) = nil
  | delete (0, _::xs) = xs
  | delete (i, x::xs) = x::delete(i-1,xs)
; (* should delete an element from a list, given the index gotten with the function above *)

fun isEqual [] [] = true
 | isEqual [] _ = false
 | isEqual _ [] = false
 | isEqual _ _ = false
 | isEqual l1 l2 =
    if List.length l1 <> List.length l2
    then false
    else
        if doesExist(List.map (fn n => n = hd l1) l2)
        then 
            isEqual(tl l1, delete(getFirstIndex(true, l2, 0), l2))
        else
            false
; (* this function puts altogether and should return either false or true *)

Below the output this function should return based on the lists passed:

isEqual [] []; (* true *)
isEqual [1] [1]; (* true *)
isEqual [1,4,2,8] [8,1,4,2]; (* true *)
isEqual [1,2,4,3] [11,24,56,7]; (* false *)
isEqual [7,5,12,88] [7,88,12,5,5]; (* false *)
isEqual [7,5,12,88,88] [7,88,12,5,5]; (* false *)
isEqual [7,5,12,88] [7,5,12,88,13,15]; (* false *)

The error in which I encounter is the following:

error: Type error in function application.
   Function: delete : int * 'a list -> 'a list
   Argument: (getFirstIndex (true, l2, 0), l2) :
      ((bool * ''a list * int) list -> int -> int) * ''a list
   Reason:
      Can't unify int to (bool * ''a list * int) list -> int -> int
         (Incompatible types)
Found near
  if doesExist (List.map (fn ... => ...) l2) then
  isEqual (tl l1, delete (...)) else false
es13.sml:24: error: Type of function does not match type of recursive application.
   Function:
      fun
         isEqual [] [...] = true |
            isEqual [...] ... = false |
            isEqual ... = false |
            isEqual ... = ... |
            ... : ''a list -> ''a list -> bool
   Variable: isEqual : ''a list * 'b list -> bool
   Reason: Can't unify ''a list to ''a list * 'b list (Incompatible types)
Found near
  fun
     isEqual [] [...] = true |
        isEqual [...] ... = false |
        isEqual ... = false |
        isEqual ... = ... |
        ...
Exception- Fail "Static Errors" raised

I apologize if this is a banal error but this is my first week trying to learn SML. Thanks in advance to everyone who will contribute to get to the solution. Peace 🙏🏼

mercredi 15 juin 2022

R - replacing dataframe values using a pattern from a separate dataframe

i need to use an R script to replace barcodes in a column of an existing dataframe retroactively using a pattern of barcodes generated in a separate dataframe. Easier to give an example:

tubeList <- data.frame(Barcode = c(1:20),
                        sampleType = c("a", "a", "a", "a", 
                               "b", "b", "b", "b", 
                               "c", "c", "c", "c", 
                               "d", "d", "d", "d", 
                               "e", "e", "e", "e")
                        )

combo <- data.frame(Barcode_1 = c("1", "1", "1", "1", "1",
                              "2", "2", "2", "2", "2", 
                              "3", "3", "3", "3", "3", 
                              "4", "4", "4", "4", "4",
                              "5", "5", "5", "5", "5"),
                    SampleName_1 = c("a", "a", "a", "a", "a", "a", "a", "a", "a", "a",
                               "b", "b", "b", "b", "b", "b", "b", "b", "b", "b",
                               "c", "c", "c", "c", "c", "c", "c", "c", "c", "c",
                               "d", "d", "d", "d", "d", "d", "d", "d", "d", "d",
                               "e", "e", "e", "e", "e", "e", "e", "e", "e", "e")
                        )

I need to replace the barcodes in the Barcode_1 column of combo so that they repeat the same pattern the barcodes follow in the Barcode column of tubeList if the SampleName_1 column of combo matches the sampleType column of tubeList, and keep repeating the pattern from tubeList until all the SampleName_1 in combo have a new associated barcode in the Barcode_1 column.

This is what the ideal output would look like:

comboReplaced <- data.frame(Barcode_1 = c("1", "2", "3", "4", "1", "2", "3", "4", "1", "2",
                              "5", "6", "7", "8", "5", "6", "7", "8", "5", "6",
                              "9", "10", "11", "12", "9", "10", "11", "12", "9", "10",
                              "13", "14", "15", "16", "13", "14", "15", "16", "13", "14",
                              "17", "18", "19", "20", "17", "18", "19", "20", "17", "18"),
                    SampleName_1 = c("a", "a", "a", "a", "a", "a", "a", "a", "a", "a",
                               "b", "b", "b", "b", "b", "b", "b", "b", "b", "b",
                               "c", "c", "c", "c", "c", "c", "c", "c", "c", "c",
                               "d", "d", "d", "d", "d", "d", "d", "d", "d", "d",
                               "e", "e", "e", "e", "e", "e", "e", "e", "e", "e")
                        )

Thank you!

Best way to design/implement Google Drive's group folders/sharing features?

I'm trying to think about the best way to design a shared folder feature for my website (React + Firebase) similar to Google Drive/Pinterest. Users should be able to create a new folder and either at creation or afterwards be able to add other users to have edit permissions (to add or delete products from the folder) in the shared folder.

My website currently lets users create their own folders that all other users can view but only the user who created the folder can edit it. In Firebase, each user is mapped by their email address and under this email address, we have a field called folders, an array storing the following object fields, createdAt (JavaScript timestamp), id (a uuidv4), isSelected (boolean to change the folder's CSS style if selected), and the title (folder name).

We also have a list of product objects in our database where there is a userID field which is the email address of the user who has saved the product under their account. When a user comes to our website, we filter for all products where the userID field equals the user’s email address, giving us the user’s products. By default when the user comes to our website, they are in their “All products” folder, and have a list of their other folders they can click on. After they click another folder, we then filter the user’s products to show only those that belong to the selected folder’s contents by checking if a product’s folder field is equal to the title field of the selected folder.

Is there an easy way to extend the current design we have to also have the shared folder feature? How would this differ from the most optimal design?

I’m struggling a bit to think of the correct design pattern and database design. Right now each user’s folders are under their “user” document in the database, but I think it needs to be pulled out so I will need to create a new collection in my Firebase database. In this collection, each document has a uuidv4 as the key and one of the fields is an array of users’ email addresses to store who has edit access. When a user first creates a new folder, we still add the folder object I defined above to the list of folder objects in their “user” document, but we also need to create a new uuidv4 in the folders collection and initialize the list of users with edit access to include this user. Then when the folder creator adds another person to the folder, we add that new person’s email address to the list of users with edit access by indexing for that folder with the given folder’s uuidv4.

The above design makes sense to me in terms of letting users have shared folders but I’m having difficulty thinking about how to ensure that products are handled properly since right now since the userID field of each product is only a specific user’s email address. If I change this to an array of user email addresses, I can no longer easily filter for which products belong to which user when a user logs into our website.

Any help in thinking about how to improve this design is greatly appreciated. Thank you!

Text replacement Excel to Notepad

Hi guys I hope you are doing well, I have a big concern and I don't know from where to start.

So the main process is to reproduce (rewrite) a xsd 264 times with a different value from an Excel Column as shown in the pictures : https://imgur.com/a/ZyOl2m9 Those are filter patterns to include or exclude some files As a final result I must get 264 output parameters with these 264 values in the Excel Column

I don't know if there's an Excel or Notepad function that makes possible to make this please help it's been 3 days that I'm stuck :(

I've been trying to make a validation for phone number where it will alert the user if they did not follow the format. How do I do it?

var form = document.getElementById('form-body')

var error = []

form.addEventListener('submit', function(e){ e.preventDefault();

var name = document.getElementById('name');
var phone = document.getElementById('phone');
var email = document.getElementById('email');
var bday = document.getElementById('bday');

if (phone.value !== [0]{1}?[9]{1}?[0-9]{9})
    alert('Follow the correct format (09XXXXXXXXX)')    

})

What are the good practices when boostrapping an application with Dependency Injection?

I'm currently writing a GUI desktop application that may become quite large with a lot of module. I'm using caliburn.micro for bootstrapping, MVVM needs and DI.

Regarding the design, I was wondering : what are the good practice regarding the boostrapping process and dependency injection ? what is not enough and what is too much ?

First I'm registering services that would be used through my application. that's I would say the easy part:

container.Singleton<IWindowManager, WindowManager>();
container.Singleton<IEventAggregator, EventAggregator>();
container.Instance<ILoggerFactory>(loggerFactory);
container.Instance<IConfiguration>(config);

But then when It gets a little bit more complicated is for all my viewmodels : Should I Initialize everything in the bootstrapper ? Should I only initialize the main components and let them pass the references to subviews in a more traditional way? (I chose the latter, but it feels sometimes wrong).

An idea that feels good in theory but that I could not find a proper way to implement is to setup a bootstrapper for any loaded module. However, it seems for now to bring more problems than solutions...

Is there good practice regarding this process ? Does anyone have some pointers regarding the design of this kind of application ?

Thank you,

mardi 14 juin 2022

Best way to design a time-measuring structure in C++?

I am struggling to do the following in the best way possible:

I have to measure the execution time of a C++ functionality implemented in C++. I have access to the code, so I can extend/modify it. The structure of what I have to do would be something like:

for (int k=0;k<nbatches;k++) {
   //Set parameters from config file
   parameters=readFromFile(k);
   s=startTime();
   for(int i=0;i<niters;i++)
   {
       o=namespacefoo::foo(parameters);
       writeToFile(o,i,k);
   }
   e=endTime();
   times[k]=e-s/niters;
}
return times;

I am quite sure that I will have to use the same structure to measure other functionalities from other namespaces.

I am not sure if it makes sense to transform each functionality into a derived-class from a base-class. Each derived-class would implement the virtual read/write wrappers and there would be a measuring function, non-member non-friend convenience function, which would implement my previous structures. Also, the number/type of the parameters is also dependent on each derived-class. Maybe I would have to do the same derived-class strategy for the parameters too. Finally a factory function would set everything.

Does this seem very cumbersome for the simple task I want to solve? I am sure this is not the first time that someone needs something like this and I do not want to rediscover the wheel.

Thanks

Is using Observer design pattern instead of Provider in flutter a good idea?

The thing is that i have an app where i need to manage data across widgets, and listen to modifications (like perform an action in widget "X" whenever the value of a variable in widget "Y" changes).

So i was thinking, instead of using a whole package and adding a library to my dependencies (i mean provider) and since dart is an Object-oriented programming language... i can use the observer design pattern (pub-sub). this way i can listen to variables' modifications and perform rebuilds only where needed!

Every interaction is highly appreciated!! THANK U!

btw this is my first question on stackoverflow xD

Is this class a builder?

Thanks to this class:

https://github.com/WebPajooh/TeleBot/blob/master/src/InlineKeyboard.php

I can build keyboards step by step:

$keyboard = new InlineKeyboard()
    ->addCallbackButton('Start', 'start_callback')
    ->addCallbackButton('Help', 'help_callback')
    ->addUrlButton('FAQ', 'https://example.com/faq')
    ->get();

The output of get() method is an object encoded by json_encode().

My question is:

  1. Can we consider this class a builder?
  2. If answer is no, why?
  3. Its output is not an object, but a string; does it mean that it is not implementing builder pattern?

lundi 13 juin 2022

How to print V in c programming in 10X10 row and column in a optimized way?

I printed V using * in specific rows and columns. I had lots of if statements. I am sharing my code below.

Is there any optimised way to print the V pattern in 10X10 row column? (without many if conditions)?

#include<stdio.h>
int main() {
  int row, column;
  for (row = 1; row <= 10; row++) {
    for (column = 1; column <= 10; column++) {
      if (row == 1 && (column == 1 || column == 10)
          || row == 3 && (column == 2 || column == 9)
          || row == 5 && (column == 3 || column == 8)
          || row == 7 && (column == 4 || column == 7)
          || row == 10 && column == 5)
        printf("*");
      else
        printf(" ");

    }

    printf("\n");
  }
  return 0;
}

choosing correct handler based on CLI options

I am currently building a simple command-line application in C#. To help me with parsing and other under-the-hood stuff I use .NET System.CommandLine library. The approach for implementing options and setting handlers is identical to what Microsoft uses in their docs for the library. The tool is meant to be used as follows:

program -a aArgument -b -c cArgument
program -b -c cArgument

-a, -b and -c are all CLI options. Then, I implemented a handler method, which executes the correct set of methods depending on which options are used.

internal static void HandleOptions(string aOpt, string bOpt, string cOpt){
    if (aOpt != null && bOpt != null && cOpt != null)
    {
        method1();
        method2();
    }
    else if (aOpt == null && bOpt != null && cOpt != null) 
    {
        method3();
    }
    else if (aOpt != null && bOpt == null && cOpt != null)
    {
        method4();
    }
...
}

However, this approach is not extensible in the long run, since as I continue adding more options, the if-else statements get complicated. What would be a good design pattern to solve this issue?

In your company what design patterns junior or intern must know? [closed]

Requirements for intern developers are raising. Please tell me, knowledge of which design patterns will guarantee a job.

Is there any framework/design pattern for storing scheduled tasks in database and retrieve them as needed?

I want to develop an application that manages tasks that have been assigned either by a user or by the core logic itself, but these tasks are not going to be invoke immediately (maybe even a year later).

So, these tasks need to be stored in a database somehow. I want something that acts as a scheduler (like TaskScheduler) that manages tasks, but also interacts with database simultaneously.

I appreciate anyone to point me in the right direction by name some design pattern to implement this by myself or a library that is been written for this exact purpose.

dimanche 12 juin 2022

Chained creational OOP design pattern problem

I am creating a class that is responsible for validating a configuration. This class calls other classes that validate said config by creating new instances in the form of a chain. At first glance, the code structure looks horrible, but It works. Anyway, I think it's not the best way to handle this logic.

I leave here a simplified version of the code in TypeScript, but I also leave it in Python and Java for reference only:

class Validator {
    private _notValidatedConfig: NotValidatedConfig

    constructor(notValidatedConfig: NotValidatedConfig) {
        this._notValidatedConfig = notValidatedConfig
    }

    validateConfig(): ValidatedConfig {
        return (
            new Phase4Validation(
                new Phase3Validation(
                    new Phase2Validation(
                        new Phase1Validation(
                            this._notValidatedConfig
                        ).validate()
                    ).validate()
                ).validate()
            ).validate()
        )
    }

    // Alternative
    validateConfig2(): ValidatedConfig {
        const validatedPhase1Config: ValidatedPhase1Config = new Phase1Validation(this._notValidatedConfig).validate()
        const validatedPhase2Config: ValidatedPhase2Config = new Phase2Validation(validatedPhase1Config).validate()
        const validatedPhase3Config: ValidatedPhase3Config = new Phase3Validation(validatedPhase2Config).validate()
        const validatedPhase4Config: ValidatedPhase4Config = new Phase4Validation(validatedPhase3Config).validate()
        return validatedPhase4Config;
    }
}
  • Python
  • Java Disclaimer: I don't have any experience with Java, so maybe there are some syntax errors.

The "alternative" is the same code, but not directly chained, instead, for every validation, it's creating a new variable. I think the "alternative" is more readable but performs worse.

What do you think about this code? what did you change? How would you face this problem or with what design pattern or framework? (programming language doesn't matter for these question)

How to create database first approach exact class project

I just doing a simple CRUD operation using database first approach. I have an ASP.NET MVC project and another a class library project.

I already mentioned ManageEmployee.Management is a class library project, and ManageEmployee.Web is the ASP.NET MVC web project.

Scaffold-DbContext -Connection "Server=MCH-DESKTOP\SQLEXPRESS; Database=AutoSoftSystems; Trusted_Connection=True; MultipleActiveResultSets=true;" 
                   -Provider Microsoft.EntityFrameworkCore.SqlServer 
                   -OutputDir "Models" 
                   -ContextDir "Data" -Context "EmployeeDbContext"

Running this command on the Package Manager console works fine, but the file is generated in the web project.

I want to change path direction. How can I change my path to the ManageEmployee.Management folder?

How to find common patterns in thousands of strings?

I don't want to find "abc" in strings ["kkkabczzz", "shdirabckai"]

Not like that.

But bigger patterns like this:

If I have to __, then I will ___.

["If I have to do it, then I will do it right.", "Even if I have to make it, I will not make it without Jack.", "....If I have to do, I will not...."]

I want to discover patterns in a large array or database of strings. Say going over the contents of an entire book.

Is there a way to find patterns like this?

I can work with JavaScript, Python, PHP.

samedi 11 juin 2022

How to design User class

Suppose I have a requirement where I have to deal with users accessing my website. There can be two kinds of users an Admin and Normal user.

  1. Single user class that will be inherited by two child classes Admin and Normal. If so how to do this properly with JPA.
@Getter
@Setter
@Entity
@Inheritance
public class User{
    private String name;
    private String userId;
}
@Data
@Entity
public class Admin extends User{
    private String adminId;
}
@Data
@Entity
public class Normal extends User{

}
  1. One and only one User class and which will have an attribute stating the role of that user.

Which will be the best design strategy and if we are looking towards inheritance should we persist those in a single table or multiple tables with a super table or should the parent not have a table and details should be persisted along with the sub tables using mapped super class.

Also if we shouldn't use inheritance then where should we probably use that and what should be the usecase and vice versa.

Is the UML/Design Pattern for my portfolio correct or how could it be improved (should?)?

First of all, I'm trying to create my web portfolio with Django and React to start as a Full Stack developer. I thought it would be a good idea to show already on my portfolio some of the things I can do (my portfolio would be ALREADY a fullstack project). So this is what I want to do: A web portfolio that is managed by me, with kind of a blog/comment functionality.

  1. I can add a project whenever I have sth new to display
  2. Those projects can be reviewd by users (who may or may not register to my site)
  3. Those projects can be liked only by registered users (I figured that might be simpler)
  4. Reviews can be answered by anyone

It doesn't need to be complicated, so if you think that might work, just say so BUT, if you notice ANY problem I might run into with this design, please let me know. I don't know much about UML, but I noticed it makes your life so much simpler to actually create the backend once you designed your tables.

The Tables shown on the graphic below will be represented by the Models on Django.

This is the UML that I came up with:

UML / Design/Pattern for my portfolio website

vendredi 10 juin 2022

How to print this pattern in C (for loop)

78910 456 23 1

How to print this program in C. in this pattern I can not insert numbers like this please help me.

Is there a common pattern to instantiate a library class as a singleton and have the library able to access that instance internally?

Say I have a library project which provides a class MyService.

I'd like clients to be able to instantiate MyService as a singleton and at the same time, I'd like the library to be able to access that singleton internally.

Now I can do the standard MyService.getInstance() sort of thing, but that doesn't lead to a very testable code if my library has MyService.getInstance() calls all over the place.

Perhaps any classes in the library that need an instance of MyService can take in MyService as a constructor parameter:

class MyTestableClass(val myService: MyService) {
    // Now this class can be unit tested with a mock/fake MyService
}

But at some higher level in the library I'm still going to have to pass MyService.getInstance() to this class.

Is there a standard pattern to accomplish this? Basically I want the client to be able to instantiate MyService as a singleton and also have the library able to access that instance internally, while having the ability to swap out the singleton instance with a mock/fake for unit testing.

How to structure laravel projects properly?

Recently started working with laravel and have a hard time structuring my project related to the current feature I'm working on.

Basically there exists a Subscription model that contains info about a subscription and most notably contains an expiry date. The feature I'm working on is to automize subscription expiry reminders to "customers" and also auto renew if the customer has not unsubscribed.

The problem is that I'm not sure how to structure the logic for this properly. Currently I have created a class called SubscriptionManager that has 2 functions. notifyExpiring($subscription) and renewExpired($subscription).

These functions require logic based on the subscription. For example: a customer should only be notified by email if the sub is 2 months from expiring. Where should this function be?

Currently I have it as a static function in class SubscriptionHelper called isExpiring($subscription).

As i've understood, logic in a Model class is a no go and I 'm not sure if a Service class is something for this.

Thanks in advance

mercredi 8 juin 2022

Is it okay to pass an endpoint string to a repository?

I have a question regarding the repository design pattern. Let's say I have a datatype Foo. In several places in my application, I must fetch a list of Foo from a remote database. For example, let's say I need to fetch a list of trending Foos and somewhere else a list of the most recent Foos. In my mind I have two options:

  • I could define two repository classes, one called TrendingFoosRepository which fetches from /foos/trending and another called RecentFoosRepository which fetches from /foos/recent.
  • However, since TrendingFoosRepository and RecentFoosRepository do exactly the same thing just at different endpoints, I could define one repository class called FoosRepository which takes in an endpoint argument, and instantiate FoosRepository('/foos/trending') and FoosRepository('/foos/recents').

To me, the second option is more concise and reusable and is therefore preferable. However, something feels odd to me about passing in endpoints into a repository. Is this antipattern? If so, why and what is the alternative?

Rust: How to implement Command pattern with Dependent Components

Business Requirements

I need to deploy a handful of services to an server environment. The services have dependent relationships (directed acyclic graph). For example, ServiceB relies on ServiceA to be deployed first and then ServiceB needs to configure ServiceA (e.g. MyWebService is dependent on Nginx to be deployed beforehand for its reverse proxy needs)

Problem

Attempt #1

I tried to implement this with Command pattern, using Vec, trait objects similar to what Rust book described:

trait Service {
    fn deploy(&self){}
}

struct ServiceA {}
impl Service for ServiceA {}

struct ServiceB<'a> {
    dep: &'a ServiceA,
}
impl<'a> Service for ServiceB<'a> {}

struct Environment {
    services: Vec<Box<dyn Service>>
}
impl Environment {
    fn deploy(&self) {
        for service in &self.services {
            service.deploy();
        }
    }
}

fn main() {
    let service_a = Box::new(ServiceA {});
    let service_b = Box::new(ServiceB { dep: &service_a });
    let environment = Environment {
        services: vec!(service_a, service_b)
    };
    environment.deploy();
}

This results in compile errors:

error[E0597]: `service_a` does not live long enough
  --> src/main.rs:26:45
   |
26 |     let service_b = Box::new(ServiceB { dep: &service_a });
   |                                             ^^^^^^^^^ borrowed value does not live long enough
27 |     let environment = Environment {
28 |         services: vec!(service_a, service_b)
   |                                   -------- cast requires that `service_a` is borrowed for `'static`
...
31 | }
   | - `service_a` dropped here while still borrowed

error[E0505]: cannot move out of `service_a` because it is borrowed
  --> src/main.rs:28:24
   |
26 |     let service_b = Box::new(ServiceB { dep: &service_a });
   |                                              --------- borrow of `service_a` occurs here
27 |     let environment = Environment {
28 |         services: vec!(service_a, service_b)
   |                        ^^^^^^^^  -------- cast requires that `service_a` is borrowed for `'static`
   |                        |
   |                        move out of `service_a` occurs here

Attempt #2

I added Rc for shared ownership:

use std::rc::Rc;

trait Service {
    fn deploy(&self){}
}

struct ServiceA {}
impl Service for ServiceA {}

struct ServiceB<'a> {
    dep: &'a ServiceA,
}
impl<'a> Service for ServiceB<'a> {}

struct Environment {
    services: Vec<Rc<Box<dyn Service>>>
}
impl Environment {
    fn deploy(&self) {
        for service in &self.services {
            service.deploy();
        }
    }
}

fn main() {
    let service_a = Rc::new(Box::new(ServiceA {}));
    let service_b = Rc::new(Box::new(ServiceB { dep: &service_a }));
    let environment = Environment {
        services: vec!(Rc::clone(&service_a), Rc::clone(&service_b))
    };
    environment.deploy();
}

Now the errors become:

error[E0308]: mismatched types
  --> src/main.rs:30:34
   |
30 |         services: vec!(Rc::clone(&service_a), Rc::clone(&service_b))
   |                                  ^^^^^^^^^^ expected trait object `dyn Service`, found struct `ServiceA`
   |
   = note: expected reference `&Rc<Box<dyn Service>>`
              found reference `&Rc<Box<ServiceA>>`

error[E0308]: mismatched types
  --> src/main.rs:30:57
   |
30 |         services: vec!(Rc::clone(&service_a), Rc::clone(&service_b))
   |                                                         ^^^^^^^^^^ expected trait object `dyn Service`, found struct `ServiceB`
   |
   = note: expected reference `&Rc<Box<dyn Service>>`
              found reference `&Rc<Box<ServiceB<'_>>>`

Can you help shed some light on the errors? Thanks!