dimanche 31 juillet 2022

hey , can anyone solve this pattern using for loop in c language? [closed]

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

hey, I need to solve this pattern where pyramid is devided into two parts and there are three space between them, read input from the user.

c++ design with unique_ptr with custom deleter

I am writing a tree data structure. Each node has a fixed size so I use a fixed size allocator for allocating/deallocating Node. This gives me a headache:

struct Node {
  // other attributes ...
  std::array<std::unique_ptr<Node, CustomDeleter>, num_children> children_;
};

Since all allocations/deallocations of Node are managed by my custom Alloc, I can't use std::unique_ptr<Node> for child nodes, I have to ship custom deleter (associated with that allocator) to children.

But Alloc must know the type of Node, because Alloc is a fixed-size allocator for Node, it should be aware of sizeof(Node) and alignof(Node).

But Node must know the type of Alloc, because CustomDeleter cannot be instantiated without Alloc! This is a circular depedency!

Have the C++ committee never considered about implementing a tree structure when they designed std::unique_ptr<Node, Deleter>? How can I resolve this problem?

ps. I can't use std::allocator<Node> because I should be able to use memory resource other than the default memory resource

CQRS Read Model syncronization: right way to "query" the write models between microservices

I'm trying to follow the database per read/write per microservice pattner with HTTP CQRS API.

following this example

Asset Microservice

Write Model:

  • AssetWriteDb (mssql)
  • Asset class/table
public class Asset
{
 public Guid AssetId {get;set;}
 public Guid ContractId {get;set;} //reference to contract of other microservice
 ...
}

Read Model

  • AssetReadDb (mongodb)
  • AssetAggregate class/collection
public class AssetAggregate
{
 public Guid AssetId {get;set;}
 public Guid ContractId {get;get;}
 public string ContractNumber {get;set;} //this comes from Contract Microservice
 ...
}

Contract Microservice

Write Model

  • ContractWriteDb (mssql)
  • Contract class/table
public class Contract
{
 public Guid ContractId {get;set;}
 public string ContractNumber {get;set;}
 ...
}

Read Model

  • ContractReadDb (mongodb)
  • ContractAggregate class/collection
public class ContractAggregate
{
 public Guid ContractId {get;set;}
 public string ContractNumber {get;set;}
 public int AssetCount {get;set;} //this comes from Asset microservice
 ...
}

Contract aggregate syncronization eventHandler example:

public class ContractAggregateHandler :
 IHandleMessage<ContractChangedEvent> // published from ContractWriteDb mssql repository
 IHandleMessage<AssetChangedEvent> // published from AssetWriteDb mssql repository 
{
 
 public async Task Handle(ContractChangedEvent message)
 {
   await _bus.Send(new RefreshContractAggregateCommand(message.ContractId));
 }

 public async Task Handle(AssetChangedEvent message)
 {
   //here i have two options to obtain the contractId from asset microservice:

   //call the AssetApi microservice reading the AssetAggregate collection (mongodb)
   //var contractId = await _mediator.Send(new GetAssetContractIdQuery(message.AssetId);
   
   //call the AssetApi microservice reading the Asset table (sqlserver)
   //var contractId = await _mediator.Send(new GetAssetContractIdFromWriteDbQuery(message.AssetId);


   await _bus.Send(new RefreshContractAggregateCommand(contractId));
 }
}

Following the rule that Queries should always query the Read Model and Commands should always read and write the Write Model, what are the best practices to achive this?

in the first case (reading the mongodb asset read model), I think it's wrong: the AssetChanged event comes from the AssetWriteDb (sql server) and querying the read model is not safe. also, if I base the aggregates generation by other aggregates, I should listen the AssetAggregateRefreshedEvent, but this will create infinites loops between aggregates generation because the AssetAggregates will need to liaste the ContractAggregateRefreshedEvent that these operations will never ends.

in the second case, (reading the sql asset write model) I think it is the safest but I need to manage a lot of queries that are "wrong" because they are not following the rule "queries must get data from read model". That's why to avoid mistakes, I need to differentiate them using a different ending word like "FromWriteDbQuery"

there is a third option that I obviously didn't want to evaluate: directly querying the AssetWriteDb from the Contract Microservice

NOTE: there is a "public" api gateway that "protects" all internal microservices from the external. the api gataway is exposing always right queries needed for clients that are querying mongodb in the right way. this question is just about internal processing of the aggregates and how to "query" Write Models between microservices

NOTE 2: I didn't write the "synchronization" business logic (the RefreshContractAggreagteHandler) because it's simply a "sql query" to the ContractWriteDb projecting a "ContractAggregate", then to map the assetCount I have the same issue, I want to query the AssetWriteDb from the Contract Microservice, so there is exactly the same of the main question)

Problem with implementation of the hierarchical state machine in C++

I have been attempting to implement a hierarchical state machine in C++. I have chosen the approach based on the State design pattern and the Composite design pattern. According to the Composite design pattern I have defined a common abstract base class for the atomic states (simple states) and the composite states (states consisting of state machines)

State.h

class State {
public:
    virtual void notifyCatModeRequested(bool state) = 0;
    virtual void notifyBatModeRequested(bool state) = 0;
    virtual void notifyMainContactorsCloseRequested(bool state) = 0;
    virtual void update() = 0;
};

StateAtomic.h

#include "State.h"
#include "StateComposite.h"

class StateAtomic : public State {
public:
    StateAtomic(StateComposite* parent) : parent(parent) {}
    void notifyCatModeRequested(bool state) {cat_mode_requested = state;}
    void notifyBatModeRequested(bool state) {bat_mode_requested = state;}
    void notifyMainContactorsCloseRequested(bool state) {main_contactors_close_requested = state;}
    virtual void update() = 0;

protected:
    StateComposite *parent;
    bool cat_mode_requested;
    bool bat_mode_requested;
    bool main_contactors_close_requested;
};

StateComposite.h

class StateComposite : public State {
public:
    StateComposite(StateComposite* parent) : parent(parent) {}
    void notifyCatModeRequested(bool state) {active->notifyCatModeRequested(state);}
    void notifyBatModeRequested(bool state) {active->notifyBatModeRequested(state);}
    void notifyMainContactorsCloseRequested(bool state) {main_contactors_close_requested = state;}
    void update() {active->update();}
    void switchState(State * new_state) {active = new_state;}
    
protected:
    StateComposite* parent;
    State* active;
};

According to the State design pattern, I have defined a class for the individual states of the state machine

Ready.h

#include "StateAtomic.h"

class StateMachine;

class Ready : public StateAtomic {
    public:
        Ready(StateMachine *parent) : : StateAtomic(parent) {}
        void update() {
            std::cout << "Ready" << std::endl;
            if (cat_mode_requested && main_contactors_close_requested) {
                parent->switchState(& static_cast<StateMachine*>(parent)->cat);
                std::cout << "Switch to cat." << std::endl;
            } else if (bat_mode_requested && main_contactors_close_requested) {
                parent->switchState(& static_cast<StateMachine*>(parent)->bat);
                std::cout << "Switch to bat." << std::endl;
            }
    }
};

Then I have defined the top-level state machine

#include "StateComposite.h"
#include "StateAtomic.h"
#include "Ready.h"
#include <iostream>

class StateMachine : public StateComposite {
public:

    StateMachine() : StateComposite(nullptr), ready(this) {
        active = &ready;
    }
    void update() {active->update();}

private:

    Ready ready;
    Cat cat;

    friend class Ready;
    friend class Cat;
};

And a very simple application

main.cpp

#include "StateMachine.h"
#include <cstdlib>

using namespace std;

struct command {
    bool cat_mode_requested;
    bool bat_mode_requested;
    bool main_contactors_close_requested;
};

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

    StateMachine state_machine;
    command active_command;

    for (uint8_t i = 0; i < 3; i++) {

        std::cout << "Cat mode requested?" << std::endl;
        std::cin >> active_command.cat_mode_requested;
        std::cout << "Bat mode requested?" << std::endl;
        std::cin >> active_command.bat_mode_requested;
        std::cout << "Main contactors close requested?" << std::endl;
        std::cin >> active_command.main_contactors_close_requested;

        state_machine.notifyCatModeRequested(active_command.cat_mode_requested);
        state_machine.notifyBatModeRequested(active_command.bat_mode_requested);
        state_machine.notifyMainContactorsCloseRequested(active_command.main_contactors_close_requested);
        state_machine.update();
    }
}

I have found that the following steps result in program crash:

  1. Invoking the state_machine.update()
  2. Invoking parent->switchState(& static_cast<StateMachine*>(parent)->cat) inside the Ready::update()
  3. Invoking the state_machine.update()

The problem is obviously in this statement: parent->switchState(& static_cast<StateMachine*>(parent)->cat) called from the Ready::update().

Unfortunately, I don't understand why. Can anybody help me understand what I am doing wrong? Thanks in advance.

WebSocket static methods vs instance methods

I need a module that handles connections and subscriptions to one or more specified WebSockets (URLs are hardcoded inside the module). The module provides various methods to interact with these WebSockets and also REST APIs associated with these WebSockets. It should only establish a connection when there's a request and close when the WebSockets are not needed anymore. But it never exposes the WebSocket instances.

This question is not about the inner workings of the module, but about the API. I see two main ways to create the interface: Through static methods (individually exported functions) or through instancing a class that provides those methods.

Both ways have pros and cons. However, I would argue that it doesn't make much sense to create a class with methods that references these WebSockets, since the WebSockets are static by definition (they're declared at the top level of the module, outside any function definitions). This just adds an unnecessary layer of complexity, it's basically a proxi to the static methods. The only benefit I see in creating an instance is that the connection is guaranteed before interacting with the WebSocket in question (see code example below).

I'm interested in your experience and opinion.

The examples should illustrate how these modules could be used. I've coded both and both work. But still not quite sure which is best.

Static methods:

// Import all the functions
import * as SpecificWebSocketManager from 'specific-websocket-manager.js';

// Subscribing to the private WebSocket requires an authentication token
const token = await SpecificWebSocketManager.getWebSocketToken({ apikey: 'string', secret: 'string' });

// Any private subscription requires this token along with other informations 
const subscription = {
    token: 'string',  
    apikey: 'string', 
    name: 'subscriptionName', 
    callback: subscriptionCallback,
};

// The manager establishes a connection to the WebSocket 
//     if it has not yet been established. This is an async call 
// This doesn't guarantee that the subscription will be successful, 
//     the connection might fail
SpecificWebSocketManager.subscribe(subscription).catch();

// The manager closes the WebSocket when there are no more subscriptions
SpecificWebSocketManager.unsubscribe(subscription); 

Instancing:

// Import default
import SpecificWebSocketManager from 'specific-websocket-manager.js';

// The manager establishes a connection to the WebSocket 
//     if it has not yet been established. This is an async call 
// The WebSocket token will be fetched internally if it doesn't exist
// This guarantees that a connection is established if the instance is created
// Note that we anyway need to make a static call to create an instance (factory)
const privateInstance = await SpecificWebSocketManager.privateInstance({ apikey: string, secret: string }).catch(); 

// Apikey is already provided and token already fetched
const subscription = { 
    name: 'subscriptionName',
    callback: subscriptionCallback 
};

// Connection is already established, no async call here
privateInstance.subscribe(subscription);

// The manager keeps the connection alive, even if there are no other subscriptions
//     because I might subscribe again at a later point in time
privateInstance.unsubscribe(subscription);

// The manager only closes the WebSocket if all instances are closed
// This will not allow me to subscribe again
privateInstance.close();

// This will allow me to subscribe again 
privateInstance.connect().catch();

samedi 30 juillet 2022

Storing a derived type that will later be created

I have a set of derived Components (logical components, eg And, OR, Wire) from the base class Components.

In my application I want to store the Component Type that is currently selected. I started with the simplest solution, an enum class ComponentType

enum class ComponentType 
{
    Wire = 0, And = 1, Or = 2 
};

class UI
{

    ComponentType selectedComponentType; 
};

// Later in code

switch ( UI->selectedComponentType )
{
    case ComponentType::Wire:
        AddComponentAction<Wire>>();
        break;

    case ComponentType::And2:
        AddComponentAction<And>>();
        break;

    default:
        break;
}

I don't like this solution. I want to believe there is another more elegant way than to basically store a (in my naive eyes) seemingly redundant representation for type data that already exists inside my code.

One idea was to use a std::any variable where I put an instance of whatever component is selected, which at least feels more elegant than defining types again as enums.

    std::any selectedComponentType = And();


    if (selectedComponentType.type() == typeid(Wire))
    {
            AddComponentAction<Wire>>();
    }

    if (selectedComponentType.type() == typeid(And))
    {
            AddComponentAction<And<2>>>();
    }

Another was to create a virtual method in Components (the base class), and implement it seperatly in all derived classes. Then store the selectedComponentType as a pointer to Component, then use dynamic dispatch on it. But influenced by one responsibility principle I don't think I want the components themselves to be responsible or involved in their own creations.

Must there not exist some design pattern that solves this problem? Factory design pattern? The creation of my components is already facilitated by (a slimmed down version of) Command Design Pattern with Actions creating and deleting components, would that mean that I should make:

ActionFactory *selectedComponentType = AddComponentActionFactory<Wire>()

And then dynamically dispatch it's virtual initializeAction() method to get desired effect?

My deeper problem is that I also use the enum ComponentType inside each component to dynamically handle different rendering behaviors, for example: Wire is a line with node points, while the AND component is just a sprite.

Factory design pattern would not help here,

Is the solution always to create a new layer of classes with similar hierarchy structures as the underlaying problem classes, like in Factory Design pattern, to finally at the end be able to use the language built-in dynamic dispatch?

Design Patterns, what does it mean to say they have an "aggressive disregard for originality"

I don't quite understand why a design pattern should not be something original? My take on it is that as long as it helps solve a recurring problem in an efficient manner, It should not matter whether it builds upon old principles or is derived from newer principles?

I would appreciate if someone could decipher the meaning of this quote by Brian Foote.

https://wiki.c2.com/?BrianFoote

Design an Accounting System classes and methods (Models and Services) in Dot Net [closed]

I am working on an Accounting system design problem and I would appreciate any help or ideas to design my classes, properties and methods. I am not looking for any code implementation of functionalities but just the design layouts.

I have to design keeping following things in mind:

  • The goal is to design the classes and methods (Models and Services) required for an invoicing system for IT companies.
  • Company has multiple customers.
  • Customers have one or more projects that are being executed by the company.
  • Each project can be run in one of two billing modes:
  • Time & Material – Hours are logged by people working on the project and client is billed based on a fixed rate by the hour.
  • Milestone Based – Project has milestones and clients are billed a fixed amount when a milestone is completed.
  • System should have the ability to generate invoices for customers and email them to customers at the end of every month.
  • We need to keep SOLID principles in mind and also focus on making code loosely coupled.

Thanks For investing your time in this.

Java program to display number pattern

Please write a Java program to display the following output using for control statement. Your code shall acquire the user to input a single digit number between 0 till 2 via window and the output should look like the outputs shown below. If the user keyed in more than a digit or other than 0/1 or 2, prompt an error message and urge the user to key in the digit again. You are encouraged to use exception handling. 0
101 21012 3210123 432101234
or 0 000 00000 0000000 000000000 or 0 202 42024 6420246 864202468

Local Ternary Pattern(LTP)

Can anyone provide me MATLAB code for calculating Local Ternary Pattern(LTP) for an input image? I have tried it but could not be able to solve this issue. So please provide me the code for this one.

vendredi 29 juillet 2022

C++ Conversion operator with multiple inheritance

Consider this case with multiple (implementation) inheritance with mixin pattern:

#include <string>
#include <iostream>

template <typename... Bases>
struct Overloads : public Bases... {};

struct Human {};

struct Animal {};

struct Named {
  std::string name_;
  void setName(const std::string& name) {
    name_ = name;  
  }
  const std::string& getName() const noexcept { return name_; }
};

template <typename OverloadsType>
struct Actor : public OverloadsType {

  Actor() : OverloadsType() {}

  template <typename OtherOverloads>
  Actor(const Actor<OtherOverloads>& other_actor) {
      // ???????
      this->setName(other_actor.getName());
  }

};

int main() {
    Actor<Overloads<Human, Named>> named_human;
    named_human.setName("Bob");
    std::cout << named_human.getName() << '\n';
    Actor<Overloads<Animal, Named>> named_animal;

    Actor<Overloads<Animal, Named>> animal_once_a_human (named_human);
    std::cout << animal_once_a_human.getName() << '\n';    
}

The code works correctly, printing two Bobs: Link

I want two things

  1. Make the conversion operator compiles even when OverloadsType and OtherOverloads aren't derived from Named (this->setName(other_actor.getName()); should be ignored or not compiled at all)

  2. Generalize "transferring" information from (common) base classes, not only name

How can I do this?

Go - Builder Pattern in Containerd

I am relativly new to Golang and learning about Containerd. While reading the docs; I came along some code:

containerd/client_opts.go

type clientOpts struct {
    defaultns       string
    defaultRuntime  string
    defaultPlatform platforms.MatchComparer
    services        *services
    dialOptions     []grpc.DialOption
    callOptions     []grpc.CallOption
    timeout         time.Duration
}

// ClientOpt allows callers to set options on the containerd client
type ClientOpt func(c *clientOpts) error

// WithDefaultNamespace sets the default namespace on the client
//
// Any operation that does not have a namespace set on the context will
// be provided the default namespace
func WithDefaultNamespace(ns string) ClientOpt {
    return func(c *clientOpts) error {
        c.defaultns = ns
        return nil
    }
}

// WithDefaultRuntime sets the default runtime on the client
func WithDefaultRuntime(rt string) ClientOpt {
    return func(c *clientOpts) error {
        c.defaultRuntime = rt
        return nil
    }
}

// WithDefaultPlatform sets the default platform matcher on the client
func WithDefaultPlatform(platform platforms.MatchComparer) ClientOpt {
    return func(c *clientOpts) error {
        c.defaultPlatform = platform
        return nil
    }
}

// WithDialOpts allows grpc.DialOptions to be set on the connection
func WithDialOpts(opts []grpc.DialOption) ClientOpt {
    return func(c *clientOpts) error {
        c.dialOptions = opts
        return nil
    }
}

// WithCallOpts allows grpc.CallOptions to be set on the connection
func WithCallOpts(opts []grpc.CallOption) ClientOpt {
    return func(c *clientOpts) error {
        c.callOptions = opts
        return nil
    }

containerd/client.go

func New(address string, opts ...ClientOpt) (*Client, error) {
    var copts clientOpts
    for _, o := range opts {
        if err := o(&copts); err != nil {
            return nil, err
        }
    }
    ...

So I was wondering. Is there a name for this paradigm? passing var parameters that are functions and setting fields with a for a loop. This seems like a builder pattern but I'm just curious as to why it's done this way; the returning of functions from functions and the builder use, if that's what it is, in this nontraditional way.

Once again, new to Go so maybe this is idiomatic of Go.

jeudi 28 juillet 2022

Add Additional Custom Attributes in Template (Slightly)

I'd like to use additional attribute when using data-sly-call

Here's the template:

<template data-sly-template.button="${ @ model}">
    <button data-info="Body"
            class="${model.moreClass}">
        ${model.label}
    </button>
</template>

When I use the button template, if there are additional css class that I'd like to add that the template does not have, what's the syntax that I should use?

Currently I have tried the following:

(1)

<sly data-sly-use.btnTemplate="button/button.html"></sly>
<div data-sly-call="${btnTemplate.button @ model= btnModel.btn}" aria-expanded="false" toggle-style="${model.toggleStyle}" aria-controls="${model.id}" data-alternate-aria-label="${model.altAriaLabel}">${model.label}</div>

(2)

<sly data-sly-use.btnTemplate="button/button.html"></sly>
<sly data-sly-call="${btnTemplate.button @ model= btnModel.btn}" aria-expanded="false" toggle-style="${model.toggleStyle}" aria-controls="${model.id}" data-alternate-aria-label="${model.altAriaLabel}">${model.label}</sly>

(3)

<sly data-sly-use.btnTemplate="button/button.html"></sly>
<sly data-sly-call="${btnTemplate.button @ model= btnModel.btn}" data-sly-attribute.aria-expanded="false" data-sly-attribute.toggle-style="${model.toggleStyle}" data-sly-attribute.aria-controls="${model.id}" data-sly-attribute.data-alternate-aria-label="${model.altAriaLabel}">${model.label}</sly>

All the above are not working. I was wondering what's the correct syntax?

I'd like it to render as:

<button data-info="Body" class="${model.moreClass}" aria-expanded="false" toggle-style="${model.toggleStyle}" aria-controls="${model.id}" data-alternate-aria-label="${model.altAriaLabel}">
            ${model.label}
        </button>

Can someone explain these desig-patterns to me? [closed]

Hi all can someone explain me the pros and cons of these desinge patterns "object pool, mvc pattern, open-close" principle. "? Thanks for your answers.

How to print numerical pattern with for loop in c

I have tried like this but I can print this pattern correctly only for 4. when I gives 5,2 or other numbers as input the code fails... how can i modify this program to match the exact output.. I have searched in many platfroms but cannot got the answer..

 #include <stdio.h>
 #include <string.h>
 #include <math.h>
 #include <stdlib.h>

int main() 
{

   int n;
   scanf("%d", &n);
   // Complete the code to print the pattern.
   int limit=(n*2)-1;
   int row,coloum;

   for( row=1; row<=limit; row++){
      for( coloum=1; coloum<=limit; coloum++){

        if(coloum==1||coloum==7||row==1||row==7) printf("%d ",n);
          else if(coloum==2||coloum==6||row==2||row==6) printf("%d ",n-1);
          else if(coloum==3||coloum==5||row==3||row==5) printf("%d ",n-2);
          else if(coloum==4||coloum==4||row==4||row==4) printf("%d ",n-3);
    
     }
     printf("\n");
   
 }

  return 0;

}

Best way to create classes that only differ by one method?

I am implementing multiple RL agents which share a lot of common attributes and methods but differ in only one. Namely the one that calculates the td_error. Out of the top of my head I can think of 3 options to implement this:

  1. Use an Agent abstract class (ABCMeta) and let the subclasses each implement all their methods.
  2. Use a normal base class Agent, implement all the common methods and just do pass on the one that is specific to each subclass.
  3. Use just one class Agent and use an attribute to specify the type of td_error to calculate and then just use if else to achieve the specific behavior.

Here is what I don't like about each option:

  1. I would need to repeat myself when implementing the common methods in each subclass.
  2. It would be possible to create instances of the base class Agent but it wouldn't work since the specific function is not defined.
  3. It is ugly and seems very naive.

I have been presented with this situation before and I normally go with option 2. but I am pretty sure there is a more correct way of achieving this.

How to implement the State design pattern?

Let's say I am going to implement (in the C++) following finite state machine consisting of 5 states where the transitions between the states occur based on value of 6 boolean flags. In each of the states only a couple of the total number of the boolean flags is relevant e.g. in the State_A the transition into the State_B is conditional by following condition: flag_01 == true && flag_02 == true and the value of the rest of the flags is irrelevant.

enter image description here

I would like to exploit the State design pattern for implementation of the state machine enter image description here

I have unfortunately stuck at the very beginning. Namely on definition of the interface of the common base class for all the state subclasses. It seems to me that my situation is little bit different from the examples mentioned in the literature where the state transitions occur based on single events with a guard condition. Can anybody give me an advice how to define the interface for the common base class in my situation where the transitions between states occur based on logic expressions with several operands?

mercredi 27 juillet 2022

Suppose a web-server has a threshold to serve 10 requests, what shall happen when it receives the 11th request

I recently came across a system design question which asks --> What happens when a server with threshold of 10 request receives the 11th requests? Since i have very little knowledge , i would need some help.

Some queries in my mind regarding the design --> shall we use message queues? or may be a load balance with messaging queues.

Thanks in advance.

Chain of responsibility for Creating Entity

I want to know whether we could use the Chain of responsibility to perform create operations. I have a set of entities to create and can I use this pattern?

It would be helpful if I get some code also?

Nestjs Middleware - how to organize the api calls to third api

I have some issue to decide how to organize my code. I'm building a middleware using an external api. My wondering is how i should manage the api calls to this external api. I was thinking about creating a service file which will just manage it, or to have just one service file with all methods in it (the ones to call the external api, and the ones who will manage the datas). But neither of the two proposals I made really appeal to me.

Maybe i've missed a good design pattern which can handle it.

Mongo generate dynamic docs from static docs best practice

I have a software design best practice question.

Lets say i have two types of collections:

  1. Static - template of data with which to genreate the second type, rearly changed.
  2. Dynamic - should have all the data from the first type but with additional data that can be changes frequently.

For example: Lets say Car is a static collection with data such as {name, brand, size, price}. And now when user buy a car I want to create a dynamic documents collection for the UserCar with the same data {name, brand ... } and also new data { condition, accidents, buyingDate ..}. The second data can be changed a lot while the first collection is more like a template for creating the second one.

My question is as follow, should I use a reference key in the second document and not duplicate the data, or should I duplicate the data to the UserCar for each new document?

first approach will require me to do some joins between the two collection each time I want to fetch the cars, while the second approach will require me to save a lot of duplicate data. Which one is better?

mardi 26 juillet 2022

Am I using the Visitor Pattern correctly?

I'm not sure if SO is the right place to post software design questions, so if there is a better place please let me know and I'll move this post there.

TL;DR: I have a class that is going to have a lot of methods. I don't want it to become bloated, so I want to find away to extract these methods using the Visitor pattern. However, I'm not sure if this is the intent of the pattern, or if I am mis-using it.

I'm playing around with a Matrix class right now. I keep wanting to add new methods to it, but I don't want to wind up with a bloated large class.

Some of these methods might be:

  • getInverse(): Matrix
  • getRREF(): Matrix
  • transpose(): Matrix
  • getDeterminant(): Matrix
  • subtract(m: Matrix): Matrix
  • multiply(m: Matrix): Matrix
  • The list can go on and on and on.

So instead, what I've been thinking about doing is using the Visitor Pattern that I just learned about, but I'm worried that I'm using it incorrectly, or over-using it. Basically my plan is to expose a minimum interface for Matrix like this:

type VectorForEachCallback = (val: number, idx1: number) => void;

type VectorMapCallback = (val: number, idx1: number) => number;

type VectorReduceCallback<T> = (
  prevVal: T,
  currVal: number,
  idx1: number,
  vec: IVector
) => T;

interface IVector {
  size(): number;

  getValue(idx1: number): number;

  setValue(idx1: number, val: number): number;

  forEach(cb: VectorForEachCallback): void;

  map(cb: VectorMapCallback): void;

  dot(other: IVector): number;

  reduce<T = number>(cb: VectorReduceCallback<T>, initialValue: T): T;

  toArray(): number[];
}


interface IMatrix {
  isSquare(): boolean;

  getValue(row1: number, col1: number): number;

  getNumRows(): number;

  getNumCols(): number;

  getRows(): IVector[];

  getCols(): IVector[];

  getRow(idx1: number): IVector;

  getCol(idx1: number): IVector;

  forEach(cb: (val: number, row: number, col: number) => void): void;

  map(cb: (val: number, row: number, col: number) => number): IMatrix;

  accept<T>(visitor: IMatrixVisitor<T>): T
}

Then I would have a MatrixVisitor interface as follows:

interface IMatrixVisitor<T> {
  visit(m: IMatrix): T;
}

Some example visitors might be:

class MatrixMinorVisitor implements IMatrixVisitor<IMatrix> {
  row: number;
  col: number;

  constructor(row: number, col: number) {
    this.row = row;
    this.col = col;
  }

  visit(m: IMatrix): IMatrix {
    const result = ConcreteMatrix.makeZero(m.getNumRows() - 1, m.getNumCols() - 1);

    m.forEach((val, oldRow, oldCol) => {
      if (oldRow === this.row || oldCol === this.col) return;
      else {
        const newRow = oldRow < this.row ? oldRow : oldRow - 1;
        const newCol = oldCol < this.col ? oldCol : oldCol - 1;

        result.setValue(newRow, newCol, val);
      }
    });

    return result;
  }
}

class MatrixDeterminantVisitor implements IMatrixVisitor<number> {
  visit(m: IMatrix): number {
    if (!m.isSquare()) throw new Error("must be square");

    if (m.getNumRows() === 1) return m.getValue(1, 1);
    else {

      return m.getCols().reduce((sum, col, col0) => {
        const minorVisitor = new MatrixMinorVisitor(1, col0 + 1);
        const minor = minorVisitor.visit(m);
        const minorDet = this.visit(minor)
        const factor = (col0 + 1) % 2 === 0 ? -col.getValue(1) : col.getValue(1);
        return sum + factor * minorDet;
      }, 0);
    }
  }
}

As a final example, I could calculate a matrix determinant as follows:

function main() {
  const matrix = new ConcreteMatrix([[1, 2], [3, 4]]);

  const det = matrix.accept(new MatrixDeterminantVisitor());
  console.log(`The determinant is ${det}!`);
}

Best practice when creating a "draft version" of an entity

I'm not sure if there's an answer to this question somewhere but I wasn't able to find the right keywords to look for something like this. If I've missed something, please point me in the right direction.

This is a general design question. I have an entity with a lot of fields (linked with an ORM and database - Doctrine, Hibernate whatever). Naturally, I put "not-nullable" constraints wherever needed.

For the sake of understanding let's take the example of a job offer entity called Offer. So the fields will be title, description, domain, typeOfOffer, companyName, experience, location etc. None of the fields can be null in this case.

Now a new requirement was that there a draft version of the offer can be saved to the database. Which means, all the fields can be null and edited later before a final submit.

Now I can think of two ways to do this.

  1. Create a draft version of the entity with the exact same fields and make it all nullable. When finally the draft is submitted, create the actual entity and delete the draft. While this seems easy and straightforward, it's a lot of code duplication so it does not sit well with me (even if I create a base class and inherit, it doesn't reduce code unless, I'm missing something).

  2. Make all the fields nullable to boot and then handle validation in the code (and not leave it to the ORM) based on a field that stores the status of the entity (like OfferStatus [draft, final] in this example). I'm not sure if this is the right way as I feel like constraints need to be the job of the database.

If you think there's a better design pattern or way to implement this, please let me know.

How to put the link of the file on our another file which will redirect people to my fist file

I had made 2 files of html name are index.html and index2.html respectively. Suppose if I had used the anchor tag in my index.html file to redirect to my index2.html file which contains some sort of information. Than how should I use the anchor tag if both of my file are in the same directory but are on the different folder or the sub folder on the same directory let's suppose the name of the directory be Project and the sub folder for index.html and index2.html be folder1 and folder2 respectively.

lundi 25 juillet 2022

managing global state with parameterization (without singleton) but with a templated class

I am writing a small pub/sub application in c++14/17 for practice and self-learning. I say 14/17 because the only feature of c++17 I have used for this project so far has been the std::scoped_lock.

In this toy application, the publishers and subscribers are on the same OS process (same compiled binary).

A reasonable thing is to do in this case, is have a single class that stores the messages in an std::unordered_map<std::string, std:enque>. I plan on instantiating this class in main and passing it to the constructors of the publishers and subscribers.

The problem comes when I attempt to hold the messages into a custom queue class, with a template for different messages; for example using protobuf.

Please consider the following:

// T here represents different
// protobuf classes
template <class T>
class Queue {
public:
    std::mutex mutex_;

    void enqueueMessage(const T* message);
    const T* dequeueMessage();
    const int length() { return messages_.size();};
private:
    std::string id_;
    std::deque<const T*> messages_;
};

class Node
{
public:
    Node();
    template <class T>
    Publisher<T>* createPublisher(std::string const topic_name, Broker broker);
};

class Broker {
    public:
        template <class T>
        Publisher<T>* createPublisher(std::string const topic_name);
    private:
        /** THE PROBLEM IS HERE **/
        std::unordered_map<std::string, Queue<T*>*> queues_;
};

int main(int argc, char** argv)
{
    // this object holds the global state
    // and will be passed in when needed
    auto broker = std::make_shared<Broker>();

    EmployeeMessage empMessage = EmployeeMessage(/* params */);
    WeatherMessage  weatherMessage = WeatherMessage(/* params */);
    
    auto nodeEmp = std::make_shared<Node>();
    auto nodeWeather = std::make_shared<Node>();

    nodeEmp.createPublisher<EmployeeMessage>("name1", broker);
    nodeWeather.createPublisher<EmployeeMessage>("name2", broker);
    

}

The queues_ member of the Broker class cannot have a Type T because the Broker is not a template class.

I cannot make Broker into a template class because then I would have an instance of broker for each type of message.

How can I fix this design?

Can I have an instance of a "presenter" class in my UIVIew.class?

As the title indicates, I want to know if it is recommended that my UIView.class have an instance of a "presenter layer" in it?

Example: enter image description here

Design pattern discussion - advantage of abstract class holding concrete classes and their instances

Its a very open ended question about a particular design, so hope people dont vote it down.

In my team's codebase, i see a pattern about API Error Codes (that are returned when someone invokes our API). We have an abstract class with bunch of private and public member variables. The abstract class itself have concrete classes inside it. And it also has instances of those concrete classes.

I am not sure whats the advantage of this design? Couldn't we just have an enum? Has anyone worked on any use case with similar design pattern (and can shed light on where it is useful and what are the advantages)?

Here is how the abstract class looks like (I have omitted detailed code for constructors etc to keep it short) -

public abstract class ApiErrorCodes{
    private static final int XMLRPC_UNKNOWN_EXCEPTION = -1;
    private final int xmlRpcErrorCode;
    private final String statusCode;
    private final String exceptionCode;
    private final AppVersion minExceptionSoapVersion;
    private final ApiErrorCodes fallbackExceptionCode;
    private final AppVersion minStatusSoapVersion;
    private final ApiErrorCodes fallbackStatusCode;
    private final Scope scope;
    private final HttpStatusCode httpStatusCode;
    private static List<ApiErrorCodes> ALL_CODES = new ArrayList<ApiErrorCodes>();
    

    public static List<ApiErrorCodes> getAllCodes(){ return ALL_CODES;}

    //constructor to populate above variables
    private ApiErrorCodes(int xmlRpcErrorCode, String statusCode, String exceptionCode,
        AppVersion minExceptionSoapVersion, ApiErrorCodes exceptionFallbackErrorCode, AppVersion minStatusSoapVersion,
        ApiErrorCodes statusFallbackCode, Scope scope, HttpStatusCode httpStatusCode){}

    //bunch of public getters to retrieve values of variables above. Skipping over them.

    //classes that extend the abstract class
    public static class ApiStatusCode extends ApiErrorCodes{ /*bunch of constructors that call super to populate variables*/}
    public static class ApiExceptionCode extends ApiErrorCodes {}
    public static class ApiStatusCodeAndExceptionCode extends ApiErrorCodes{}
    public static class XmlRpcErrorCode extends ApiErrorCodes{}

    //instances of above classes
    public static final ApiErrorCodes BAD_XML = new ApiStatusCodeAndExceptionCode(0, null, null HttpStatusCode.BAD_REQUEST);
    public static final ApiErrorCodes NULL_PARAMETER_LIST = new XmlRpcErrorCode(1000);
    public static final ApiErrorCodes API_CURRENTLY_DISABLED = new ApiExceptionCode(1007, "API_CURRENTLY_DISABLED", HttpStatusCode.FORBIDDEN);

}

and in rest of the code, we access specific error code by referencing them like this -

return(ApiErrorCodes.BAD_XML)

Implementing reactivity in vanilla JS

I use vanilla JS on webpages, and I'm trying to understand whether my design pattern is correctly implementing the principle of reactivity.

(Note: I'm not referring to the library React -- though I'm happy for answers to draw on features or strategies of such libraries).

My basic understanding is that you have some data which acts as your single source of truth, you listen for changes, and when that data changes, your page|app|component re-renders to reflect that.

Here's a simplified version of what I do, with questions after.

Let's say I have my single source of truth:

let data = {}
data.someContent = 'Hello World'
data.color = 'red'

and my app's markup in a template string for dynamic rendering:

function template(data) {
  return `
  <div id="app" style="color:${data.color}">${data.someContent}</div>
`
}
// assume there are also plain HTML inputs on the page, outside of what gets re-rendered.   

a function that renders based on the data:

function render(data) {
  document.getElementById('app').innerHtml = template(data)
} 

then, for the equivalent of reactivity from client-side updates:

document.addEventListener('input', (e) => {
  data[e.id] = e.target.value // update data to reflect input
  render(data) // re-render based on new data
})

and from server-side updates:

function fetchDataAndReRender() {
  data.propToUpdate = // fetch data from server
  render(data) // again, re-render
return
}

So, we've got the single source of truth and re-rendering based on data updates.

  • Is there another pillar to this, beyond the trio of data, listeners, and rendering?
  • I understand that libraries usually listen directly to changes on the data object, e.g. via Proxies. It seems like the only advantage to that is avoiding manually calling render(). Is that correct?

How can I write an interface where a class returns the same type as itself?

Consider this code, it's written in Typescript but the language I don't think really matters.

interface IXY {
  x: number;
  y: number;

  scale(n: number): IXY;
}

interface IXYZ extends IXY {
  z: number;

  scale(n: number): IXYZ;
}

// this is not my real code, just an example.
function flip<T extends IXY>(v: T, flip: boolean): T {
  if (flip) return v.scale(-1); // Error here
  else return v;
}

This gives me the following error:

Type 'IXY' is not assignable to type 'T'.
'IXY' is assignable to the constraint of type 'T',
but 'T' could be instantiated with a different subtype of constraint 'IXY'

Now, I understand why this error is occuring. It's because any interface that extends IXY only has to ensure that scale returns something that extends IXY. Consider this example, where IABC just returns an IXY.

interface IABC extends IXY {
  scale(n: number): IXY; // does not have to return IABC.
}

I guess my question is, how can I write IXY's .scale to make sure whatever is extending it is returning the same type as that extension? When I call flip with an IXYZ I want to know that what I get out is also going to be an IXYZ.

How do I write an interface that ensures inheritors return the same type as themselves? How do I make sure I don't lose the z in IXYZ?

Many thanks.

Designing a global event handler

We're currently looking at setting up standards for events that are shared across the system. We work with data that changes often and having a way for all our independent systems to communicate and perform event driven tasks we believe a global event system will be the key to success.

Our product has a large amount (Actually, probably not that large, but I can imagine we're looking at about 1-2 million updates a day) of everchanging data and we need to keep up with these changes. We are able to track changes on the front end, through state management, but on the back end, due to having a large amount of microservices, it is a much bigger task.

A common change, for example, is when a user decides to pay for an order. We have a microservice that handles that order processing, but our analytics service wants to pick up on that processing to track it as a paid order and contribute it towards the daily earnings.

My belief is that we should have a standardised approach using topics for each domain object (eg. Orders/Customers/Payments) in a global event bus with a standardised object with fields like:

  • Object Id
  • Version (To track protocol changes, etc)
  • The object itself (Potentially through graphql instead of the entire object, though there are some pitfalls to this)

I'd then look to push all this information in to something like Amazon SNS where each sub-system could digest the notifications however they like.

My question is really looking for advice on how to approach this and for some anecdotes from people that have attempted this before (Even if you've done something different that would be awesome to hear) to not make too many mistakes.

Replacing Multiple If statements to reduce cognitive complexity

So I have a go application that is trying to authorize the user using two mechanisms:

  1. CSP (in which the app-key (ak) request header must be present in the request)
  2. OAuth (i will use the azp claim to set the name of service)

So I have to do the name-spacing in my service on the basis of type of authorization the user has used (User is free to choose any one of them).

So there is a design issue which I am not able to resolve:

func setServiceName(appKeys, oAuthUserMap map[string]string, logger log.Logger) func(inner http.Handler) http.Handler {
    return func(inner http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
            
            ak := req.Header.Get("ak")

            claims, _ := req.Context().Value(oauth.JWTContextKey("claims")).(jwt.MapClaims)
            
            authClaim, errorMessage, keyMap, middlewareError := checkAuthType(ak, claims, appKeys, oAuthUserMap)

            if authClaim == "" || authClaim == "<nil>" {
                // return error for "Invalid Authorization" as none of the request header is present
            }

            if val, ok := keyMap[authClaim]; ok {
                // if value is not empty, then there must be a mapping existing between authClaim and service name
                
                // serve the request
                
            }

            // return error according to the type of authorization used i.e. Invalid APP KEY in case of CSP or Invalid Credentials in case of Oauth
        })
    }
}


// this function checks the type of authorization used and returns the paramters respectively
func checkAuthType(ak string, claims jwt.MapClaims, appKeys, oAuthUserMap map[string]string) (authClaim,
    errorMessage string, keyMap map[string]string, middlewareError error) {
    
    if ak != "" {
        keyMap = appKeys
        errorMessage = "Invalid APP KEY provided"
        middlewareError = // i will return a custom error here
        authClaim = ak
    }

    azp := claims["azp"]
    oauthClaim := fmt.Sprint(azp)

    if oauthClaim != "<nil>" {
        keyMap = oAuthUserMap
        errorMessage = "Invalid Credentials"
        middlewareError = // i will return a custom error here
        authClaim = oauthClaim
    }

    return authClaim, errorMessage, keyMap, middlewareError
}

Things to keep in mind while seeing the code:

  1. This setServiceName is a middleware that i will be using in my application
  1. I have to return different errors on basis of type of authorization mechanism used
  1. The appKeys and oAuthUserMap are two maps that i will populate on the basis of environment variables set in configs and i have to use appKeys map for name-spacing in case of CSP and the later in case of OAuth
  1. authClaim will help me in finding the value from the key in map that will be used for namespacing

Problems I am facing:

  1. If I keep all the if statements inside the setServiceName middleware function the cognitive complexity will increase and that's not acceptable
  2. the function checkAuthType is not a very good function as it is performing simple if-else logic that can be shifted inside the middleware function only

Please help me in solving this design issue. The function checkAuthType doesn't seem to be much useful as it contains only if-else logic but at the same time i have to take care of cognitive complexity of setServiceName.

Rust - MVP Pattern implementation

I'm trying to find the best way to implement MVP pattern at RUST Language. Actually I'm using Clean Architecture pattern and now I'm trying implement MVP pattern inside. Whats the better way to do it?

For example: I have trait of some view:

pub trait ILoginView{
    fn new(presenter: LoginPresenter) -> Self;
}

And some presenter for it:

pub struct LoginPresenter{
    view: &mut dyn ILoginView,
}

Finally impl of view trait:

pub struct LoginView{
    presenter: LoginPresenter,
}

impl ILoginView for LoginView{
    fn new(presenter: LoginPresenter) -> Self {
        Self{
            presenter
        }
    }
}

And I don’t know how best to connect them with each other, so that the presenter, for example, changes the state of the view, and the view receives the login result.

P.S. I think that this question will be quite useful, because there are practically no answers to a similar question in the search results for Rust Lang.

dimanche 24 juillet 2022

Strange Pattern in a Java Db Manager, uses Inner Class for creating connections to db

I found a db manager class that uses a strange pattern in a Java project (the project is in production), i am trying to understand it's purpose, the comments left by the author give only hints:

public class MongoDBManagerFactory {

    /**
     * Using thread local and proxies for storing database
     * 
     * One thread = one db connection = one transaction
     */
    final class MongoDBManager implements IMongoManager {

       private MongoClient client = null;
       private DB db = null;
       private Jongo jongo = null;

       /*
        * New instance management
        */

       private MongoDBManager(String domain) {
            // ...code for entering credentials and connecting to the db
            db = client.getDB(domain);
            jongo = new Jongo(db);
       }

       public Jongo getJongo() {
            return jongo;
       }

       public MongoClient getClient() {
            return client;
       }

    }

    /*
     * Singleton Replace by Spring, seam or other later on
     */
    private static MongoDBManagerFactory instance = new MongoDBManagerFactory();

    private Map<String, IMongoManager> mapDBManager = new HashMap<>();

    private MongoDBManagerFactory() {}

    public static MongoDBManagerFactory getInstance() {
        return instance;
    }

    public IMongoManager getManager() {
        IMongoManager mongoManager = null;
        String domain = "dnName";
        if (domain != null && mapDBManager.get(domain) == null) {
            mongoManager = new MongoDBManager(domain);
            mapDBManager.put(domain, mongoManager);
        } else if (domain != null && mapDBManager.get(domain) != null) {
            mongoManager = mapDBManager.get(domain);
        }
        return mongoManager;
    }

}

English is not the first language for whoever wrote this code but they may give an idea about what they were trying to achieve. Questions:

  1. what are they trying to achieve?
  2. What is the purpose of the single threaded connection/transactions?
  3. How using this pattern (whith the inner class and signleton) helps in achieving the above?

Best design patterns for quiz game

I need to develop a question and answer game for a university discipline, where questions are created and maintained by the game's own community, being more specific, any player can add questions, which will be sent to other players for approval ( or not), all done with database and graphical interface. I wanted to know which design patterns would be best for this type of application. Thanks in advance.

Best structure for multiple payment rules based on employee type in C#

I have an Employees class:

public class StaffMember
{
    public int Id { get; set; }
    public string ContractType {get; set;}
    public string JobTitle {get; set;}
    public int DaysWorked {get; set;}
}

and I have a PaymentRule class:

public class PaymentRule
{
    public string ContractType {get; set;}
    public string JobTitle {get; set;}
    public int DailyRate { get; set; }
    public int MaxPayAmount { get; set; }
    public int MinPayAmount { get; set; }
    public int MaxWorkedDays { get; set; }
    public int MinWorkedDays{ get; set; }
}

now, there are multiple payment rules which depend on both ContractType and JobTitle, for example, one rule might be as follows:

 if ContractType = full time and jobTitle = sales and DaysWorked > MinDaysWorked: pay 100$
    else pay DaysWorked * DailyRate

there are many other rules like this with changing structure, I want have a form where I search with the member ID and the member is retrieved from database then the rule is also retrieved and applied and I get the payment for the employee.

The problem is the rules are complex, so I want a structured and generalized way to implement the current rules and extend more rules without the code becoming spaghetti.

I understand that maybe I need to implement an interface and extend it, but I can't wrap my head around the full image

samedi 23 juillet 2022

How to the same Interface to different QT Classes

Goal

I want to benchmark some drawing libraries and gather diagnostics. I thought of implementing in each benchmark the same interface and then instantiating different classes in the main window.

The Challenge

The problem is that some benchmarks use QWidget and other QOpenGLWidget. So even if I implement the same functionality I can not use it, without dynamic casting to each possible instance.

What I tried so far

My first thought was to create an interface and use virtual multiple inheritance. But that doesn't seem to work and I am not sure if that's even the right solution.

I also thought of the Composite Pattern or Adapter Pattern, but seem some problems, as I want to override some functions of QWidget like resizeEvent in each benchmark. Of course I could duplicate that code or put it into some non-member function. But maybe there is something more elegant?

QWidgets Addin

class BenchmarkAddin : virtual public QWidget {
public:
    BenchmarkAddin() {
        connect(&timer_, SIGNAL(timeout()), this, SLOT(update()));
    }

    double get_fps() {
        // use frames_ and time to estimate fps
    }

    void count_frame() {
        ++frames_;
    }
    
    void set_parameters(int param1_) {
        param1_;
    }

protected:
    void resizeEvent(QResizeEvent* event) override {
        init();
    }

    virtual void init() = 0;

    int param1_;
private:
    int frames_;
    QTimer timer_;
}

Raster Benchmark

class RasterBenchmark : public BenchmarkAddin {
protected:
    void init() override {
        // create buffers
    }

    void paintEvent(QPaintEvent* event) override {
        // do drawing using param1_
        count_frame();
    }
}

OpenGL benchmark

class OpenGLBenchmark : virtual public QOpenGLWidget, public BenchmarkAddin {
protected:
    void paintGL() override {
        // do GL drawing using param1_
        count_frame();
    }
}

Main Window Example Usage

BenchmarkAddin *widget; 
if (benchmark == "raster") {
    widget = new RasterBenchmark(this);
else
    widget = new OpenGLBenchmark(this);

widget.set_parameters(100);

...

std::cout << widget.get_fps() << std::endl;

Obviously this doesn't work, as QOpenGLWidget doesn't use virtual inheritance for QWidget. Also there is a problem with Qt's object meta system.

Question:

Any idea how I could implement an interface that is both accessible within a subclass of QWidget and QOpenGLWidget?

Flask-SQL Alchemy how to union two different models from different tables

Hello I'm new to flask and I have an application where i am creating different models and schemas for my entities. These two models and schemas are very close to each other except with few differences. I have base classes for my model and schema so i could inherit and re-use the same class. However, i'm having a problem when i need to deserialize them with marshall and return the union result.

I'm using marshmallow,sql-achemy and flaskapi-spec. I am not sure if there's a way to use the marshall_with decorator with multiple schemas since I want to union my results and return the aggregated model.

Here is the endpoint,models and classes I have.

Models;

class BasePublisher(Model):
    __abstract__= True
    id= Column(db.String(80),primary_key=True,nullable=False)
    date = Column(db.DateTime, default=dt.datetime.utcnow, primary_key=True, nullable=False)
    views = Column(db.Numeric)
    clicks = Column(db.Numeric)
    publisher = Column(db.String(80),primary_key=True,nullable=False)

class Facebook(BasePublisher):
    __tablename__='facebook_table'

    def __init__(self, **kwargs):
        db.Model.__init__(self, **kwargs)

class Pinterest(BasePublisher):
    __tablename__='pin_table'
    
    def __init__(self, user, **kwargs):
        db.Model.__init__(self, user=user, **kwargs)

Schemas

class PublisherSchema(Schema):
    date = fields.DateTime(dump_only=True)
    type = fields.DateTime(dump_only=True)
    views = fields.Number(dump_only=True)
    clicks = fields.Number(dump_only=True)
    publisher = fields.Str(dump_only=True)

class FacebookSchema(PublisherSchema):
     @post_dump
     def dump_data(self,data):
           data["type"]="Facebok"

class PinterestSchema(PublisherSchema):
     @post_dump
     def dump_data(self,data):
          data["type"]="Pinterest

"

-View

@blueprint.route('/api/sample/publishers/<id>', methods=('GET',))
@use_kwargs({'type': fields.Str(), 'start_date': fields.Str(),'end_date':fields.Str()},location="query")
@marshal_with(facebook_schema)
def get_data(id, type, start_date=None,end_date=None):
    facebook_data = Facebook.query.filter_by(id=id)
    .filter(Facebook.date.between(start_date,end_date))
    .limit(10).all()

Ideally i would like to do this in my view;

     pinterest_data = Pinterest.query.filter_by(id=id)
    .filter(Pinterest.date.between(start_date,end_date))
    .limit(10).all()
    facebook_data.query.union(pinterest_data)

Union like this throws an error in flask application and also i have slightly different schemas for each publisher and i don't know how i can return both of them when i de-serialize with marshall

something like this maybe?

@marshal_with(facebook_schema,pinterest_schema)
    

Does this architecture exist within Kubernetes?

I'm familiar with Kubernetes and Docker, but am very much a beginner as far as deployment is concered. Nevertheless, I have an idea for a project using two services where users can reserve a "room" which has set resources at it's disposal.

One will be effectively a front end where users can reserve and abandon rooms, and one is responsible for hosting the rooms. The room host will be able to host x number of rooms and I'd like to make it scale horizontally as requests exceed that limit, using headers to route users to their reserved room. Similarly, as rooms are abandoned (either by a manual request to do so or exceeding an inactivity timer) I'd like the room hosts to scale down.

My question is, how could I go about implementing this design pattern? Is Kubernetes the best way of going about it? Would I need to use CRDs and write a custom operator, or are there better ways of going about it?

vendredi 22 juillet 2022

What design patterns can improve code testability? [closed]

What design patterns can improve code testability? Is factory pattern OK? Is singleton pattern OK?

Encrypt files in background while using the application (Design Problem)

I've to design a functionality which encrypts and decrypts files(around 30) based on user input.

During the encryption, I want the user to be still able to use the system just like before. (which means that files can be updated during the encryption process)

I'm looking to find the best approach to implement it. There are few different approaches (that are still incomplete) which I want to discuss.

Simple Approach:

  • Start encrypting 30 files in parallel.
  • If user updates one of the file, the change will be missed in the encrypted file as the change was not there when encryption was called.

Cons: Dirty read = data loss. (failed)

2nd Approach:

  • save all operations that can change the files (difficult to achieve).
  • wait for encryption to complete.
  • when encryption completes, perform all those operations manually.

Cons: User updates are not reflected during the process, as we're only saving operations and not performing them unless process is completed.

3rd Approach:

  • When encryption starts:
  1. use current files as "old".
  2. current system works fine as old (updates saved in old files if any change)
  3. start encrypting files and save them with different name.
  • when all files are encrypted, there are two cases:
  1. No file was updated during process (best case). -> replace encrypted files name and delete old files.
  2. Files changed. Find out which files change(easy to check) and only encrypts those again. (with the hope user doesn't update again, if he does keep repeating the process unless he stops)

Cons: Can end up in an infinite loop if user doesn't stop updating files.

Pros: User can use the system just like before and data won't be lost.

I'd love to read better approaches from you guys.

I'll be using AWS KMS to encrypt S3 files inside lambda function.

How can I solve the problem of script blocking?

I want to give users the ability to customize the behavior of game objects, but I found that unity is actually a single threaded program. If the user writes a script with circular statements in the game object, the main thread of unity will block, just like the game is stuck. How to make the update function of object seem to be executed on a separate thread?

De facto execution order

The logical execution sequence I want to implement

Multiple channel Notification system - LLD -

You have to design the classes for building a notification system that supports multiple channels such as email, SMS, Whatsapp. It should be easily extensible.

My design :

class Message {
NotificationType type ; //email, sms
msgId;
String content ;
}
MessagingServiceImpl {
static {
//map from notification type to the respective handler
map.put("SMS",new SMSHandler());
map.put("Email",new EmailHandler();
}
void processMessage(Message message) {
Handler handler = map.get(message.getNotificationType();
handler.handleMessage();
}
}
public abstract class Handler {
public abstract void handle(Mesage message) ;
}
public EmailHandler extends Handler {
public void handle(Message message) {
System.out.println("Sending email"): // similar class for phone.
}

Note: This design was rejected in the interview. Questions:

  1. Should we make Message abstract - EmailMessage,SMSMessage etc ?
  2. Note that the content of the message varies depending on the channel. For eg. In email,the content will be large. For SMS,it is much smaller. So,should Message be astract?
  3. How can you support a new channel eg..telegram messages with minimal changes?

What actually is a subdomain in domain-driven design?

So I was reading the book "Implementing domain-driven design by Vaugh Vernon" and there's something that I don't understand. To make it clear, Let's look at the picture that I took from the book. Here's how he describes DDD concepts such as bounded context, subdomain and etc.

example

So as you can see in the picture, it describes the domain of a retail company. You have implicit bounded context and also a subdomain inside of a bounded context, but after reading a few pages further I found this picture.

enter image description here

So now it makes me confuse because in the first picture subdomain is living inside of a bounded context, but in the second picture bounded context is living inside of a subdomain (Core, Support, Generic) instead. So what is actually a subdomain that he describes in the first picture. Are they the same thing as the second picture?

jeudi 21 juillet 2022

FastAPI - Best practices for writing REST APIs with multiple conditions

Let's say I have two entities, Users and Councils, and a M2M association table UserCouncils. Users can be added/removed from Councils and only admins can do that (defined in a role attribute in the UserCouncil relation). Now, when creating endpoints for /councils/{council_id}/remove, I am faced with the issue of checking multiple constraints before the operation, such as the following:


@router.delete("/{council_id}/remove", response_model=responses.CouncilDetail)
def remove_user_from_council(
    council_id: int | UUID = Path(...),
    *,
    user_in: schemas.CouncilUser,
    db: Session = Depends(get_db),
    current_user: Users = Depends(get_current_user),
    council: Councils = Depends(council_id_dep),
) -> dict[str, Any]:
    """

    DELETE /councils/:id/remove (auth)

    remove user with `user_in` from council
    current user must be ADMIN of council
    """

    # check if input user exists
    if not Users.get(db=db, id=user_in.user_id):
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND, detail="User not found"
        )

    if not UserCouncil.get(db=db, user_id=user_in.user_id, council_id=council.id):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Cannot delete user who is not part of council",
        )

    # check if current user exists in council
    if not (
        relation := UserCouncil.get(
            db=db, user_id=current_user.id, council_id=council.id
        )
    ):
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Current user not part of council",
        )

    # check if current user is Admin
    if relation.role != Roles.ADMIN:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="Unauthorized"
        )

    elif current_user.id == user_in.user_id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Admin cannot delete themselves",
        )

    else:
        updated_users = council.remove_member(db=db, user_id=user_in.user_id)
        result = {"council": council, "users": updated_users}
        return result

These checks are pretty self-explanatory. However, this adds a lot of code in the endpoint definition. Should the endpoint definitions be generally minimalistic? I could wrap all these checks inside the Councils crud method (i.e., council.remove_member()), but that would mean adding HTTPExceptions inside crud classes, which I don't want to do.

What are the general best practices for solving situations like these, and where can I read more about this? Any kind of help would be appreciated.

Thanks.

scroll bar with using gradient in css with three color

i wanted to create same scroll bar with using css gradient, i have done this but not able to get exact design.

<div id="style-9" ></div>

#style-9::-webkit-scrollbar-track
{
    -webkit-box-shadow: inset -1px 0px 0px #6A6561;
    background-color: #3D3938;
}

#style-9::-webkit-scrollbar
{
    width: 10px;
    background-color: #141413;
}

#style-9::-webkit-scrollbar-thumb
{
    background-color: #3B8526;
     background: linear-gradient(to bottom,
     #3B8526 25%, #52A435 25% 50%, #6BC349 50% 75% );
}

#style-9::-webkit-scrollbar {
  width: 14px;
}
#style-9::-webkit-scrollbar-track {
  background-clip: content-box;
  border: 4px solid transparent;
}
#style-9::-webkit-scrollbar-corner, .scrollbar-1::-webkit-scrollbar-track {
  background-color: #b0b7c4;
}

enter image description here

What are possible patterns for vue3 component export function?

I'm developing vue 3 table component that will have data export feature. Table component can be nested and parent/higher level components should have ability to trigger export and receive underlying data.

One way to achieve this that comes to my mind is to reference table component from parent component level and call export methods directly on table component.

Another idea would be to watch one of the props which could be incremented and change would trigger export event.

Do you have experience with other patters for this scenario (expose component internal method / feature and consume result in parent component). Do you find any drawback of ideas listed above?

Best regards, It_man

mercredi 20 juillet 2022

C++ How can I move or swap pair

I'm writing a B-Tree class. I want to support for all four cases like std::set, std::multiset, std::map, std::multimap.

I verified that my code works correctly for first two cases. The problem is the latter two. Their declarations are like this:

template <typename T>
concept Containable = std::is_same_v<std::remove_cvref_t<T>, T>;

using index_t = std::ptrdiff_t;

template <Containable K, index_t t = 2, typename Comp = std::ranges::less,
          typename Alloc = std::allocator<K>>
using BTreeSet = detail::BTreeBase<K, K, t, Comp, false, Alloc>;

template <Containable K, index_t t = 2, typename Comp = std::ranges::less,
          typename Alloc = std::allocator<K>>
using BTreeMultiSet = detail::BTreeBase<K, K, t, Comp, true, Alloc>;

template <Containable K, Containable V, index_t t = 2,
          typename Comp = std::ranges::less,
          typename Alloc = std::allocator<std::pair<const K, V>>>
using BTreeMap = detail::BTreeBase<K, std::pair<const K, V>, t, Comp, false, Alloc>;

template <Containable K, Containable V, index_t t = 2,
          typename Comp = std::ranges::less,
          typename Alloc = std::allocator<std::pair<const K, V>>>
using BTreeMultiMap =
    detail::BTreeBase<K, std::pair<const K, V>, t, Comp, true, Alloc>;

BTreeBase is like this

template <Containable K, typename V, index_t t, typename Comp, bool AllowDup,
          typename Alloc>
requires(t >= 2) class BTreeBase {

// ... details ...
};

For BTreeMap the value_type is std::pair<const K, V>. For associative containers, changing keys via dereferencing iterators is unacceptable.

This line gives me a headache:

x->keys_[i] = std::move(y->keys_[t - 1]);

It doesn't compile. std::iter_swap or std::swap don't work

Here x and y are BTreeBase::Node and keys_ is std::vector<value_type, Alloc>.

Standard library containers std::map, std::unordered_map uses the same approach but they don't have this problem, because it is based on red-black trees and hash tables, so a node has exactly single key, so you can just move a node, not a key.

But B-Tree is a different beast. A node has many keys, and moving or swapping keys between nodes should be possible. (user still should not be allowed to change key from outside)

How can I deal with this?

Best way to call different APIs based on user input in C#?

I am developing one console application using C#. I need to call different-2 get APIs based on the input provided by the user and write the response on console.

So if user enters 1, I need to call a group weather api. If user enters 2 then I need to call temperature API. If user enters 3 then call some other API and if enters other then this just write invalid input.

For now I have just written multiple if and else if. Is there any better approach? Because this way there are multiple if else. And same goes for switch case as well.

I have also thought of creating mapping of input the endpoint like defining them in config file and then read into a dictionary.

So in future it can support below things.

if I need to call another API for input 4….. or No need to call any API for input 2. Or call different API on input 2.

How to handle retrieving data from a different table based on environment?

I am intentionally keeping this question agnostic to any specific language as I am looking for a solution in the realm of design.

I am working on a program that selects data from an external table using a dblink. Depending on what environment I am working in, the dblink changes. For example, if I am in the production environment, the dblink will also be for production. When in a lower environment the dblink will be for development.

To accommodate this we concatenate a SQL query together, placing the appropriate table name and dblink in which is determined by checking which environment we are currently in. See the psuedocode below:

If ENV = "PRD"
 dblink = "table@production";
Else
 dblink = "table@development";

SQL = "SELECT * FROM " + dblink + "WHERE...";

I just feel there may be a better way of doing this whether inside the program or through database setup. Any information or resources on this would be appreciated.

Singleton pattern doesn't work in Xamarin multi-platform project MVVM

I have a C# (Xamarin) solution structured like this:

📦 Solution
 ┣ 📂 Main application
 ┃ ┣ 📂 ViewModel Project
 ┃ ┃ ┣ 📜 ...
 ┃ ┣ 📂 Android Project
 ┃ ┃ ┣ 📜 MyActivity.cs
 ┃ ┃ ┣ 📜 ...
 ┃ ┣ 📂 iOS Project
 ┃ ┃ ┣ 📜 ...
 ┗ 📂 Multiplaftorm Library
   ┣ 📂 Android-specific Library Project
   ┃ ┣ 📜 MyModuleAndroid.cs
   ┃ ┣ 📜 ...
   ┣ 📂 iOS-specific Library Project
   ┃ ┣ 📜 MyModuleiOS.cs
   ┃ ┣ 📜 ...
   ┣ 📂 Shared Library Project (.shproj)
   ┃ ┣ 📜 MyLibrary.Shared.projitems
   ┃ ┣ 📜 Service.cs
   ┃ ┣ 📜 Factory.cs
   ┃ ┣ 📜 IMyModule.cs
   ┃ ┣ 📜 ...

The module requires very device specific initialization, that I must do in the platform specific part (I make the example with Android)

// MyActivity.cs

[Activity(Label = "", WindowSoftInputMode = SoftInput.AdjustPan]
public class MyActivity
{   
    protected override void OnCreate(Bundle savedInstanceState)
    {
        MyModuleAndroid.Init(this); // I need an Activity as input
    }

...

The Init involves a singleton pattern:

// MyModuleAndroid.cs

public class MyModuleAndroid
{
    public static void Init(Activity activity)
    {
        Factory.GetInstance().DoSomething();
    }
}
// Factory.cs

public class Factory
{
    private static Factory instance;

    public static Factory GetInstance()
    {
        if (instance == null)
        {
            // only if no instance existing, I create a new one
            instance = new NFCModuleFactory();
        }

        return instance;
    }
...
}

Then, the instance is used inside the Service (shared project) that is called always from view model. But... here is the problem: the first time I try to access the instance (the second, after the initialization), I found it's null, so the singleton re-creates a new instance! If I call again from service the instance is mantained, but I already lost all my initalization data.

How can I solve this?

As a workaround, I noticed that If I structure my library like this, so by creating a fourth project that manages the factory (so the singleton), it works perfectly:

 ┗ 📂 Multiplaftorm Library
   ┣ 📂 Android-specific Library Project
   ┃ ┣ 📜 MyModuleAndroid.cs
   ┃ ┣ 📜 ...
   ┣ 📂 iOS-specific Library Project
   ┃ ┣ 📜 MyModuleiOS.cs
   ┃ ┣ 📜 ...
   ┣ 📂 Shared Library Project (.shproj)
   ┃ ┣ 📜 MyLibrary.Shared.projitems
   ┃ ┣ 📜 Service.cs
   ┣ 📂 Standard Project (.csproj)
   ┃ ┣ 📜 Factory.cs
   ┃ ┣ 📜 IMyModule.cs
   ┃ ┣ 📜 ...

As I said, in this way it works... but I really cannot understand why! :-(

Which design pattern to apply when I send multiple requests to external services, merge them and then return a response?

Let's assume I have an endpoint that receives a request on endpoint:

[POST] /search?product=Apple

Based on receiving product filter I send multiple requests with different request payloads to external services like WebsiteApple1, WebsiteApple2, ...

Now once I get all the data back from all websites I merge responses into an array and return the cheapest product to end user.

Here what kind of design pattern I should use?

mardi 19 juillet 2022

Confusion regarding usage of templated base class pointer pattern

This is a regular old polymorphism design scenario except that

template<typename Params> class Base {
   Base(Params& params):
     params_(params) {
     }
   virtual void run() = 0;
   Params params_;
};

class Derived1: public Base<Derived1Params> {
   Derived1(Derived1Params& params):
    Base(params) {
   }
   void run() {
   }
};

In the above situation, I cannot use the regular old, "use base_ptr to point to derived object" technique for run-time polymorphism, due to the templates, like below

Base* bp; // An error!!!
Derived1 dr;
bp = &dr;

What is the best pattern for this scenario?

Obtaining items based on chance percentage

I am working on a Laravel project. I will explain the problem and I would be grateful if you help me. I want to add a feature to the project. First I want to explain the entities of the project:

User,Car,CarClass, Box.

each Car has a CarClass. User can buy a Box and open it.

When the user opens the box he bought, he can win a car from a certain CarClass by chance. for example:

Red box: street 45%, sport 30%, muscle 30%, hyper 0%

Yellow box: street 20%, sport 50%, muscle 10%, hyper 20%

User who buys the Red box has a 45% chance to win a car with street class car, 30% chance to win a car with sport class and so on... .

And we have different boxes with different percentages.

Should there be one method for unboxing? Should a special design pattern be used?

Whether it is a complete answer or a clue that can help me, I would be grateful.

C# method that determines if given object is a singleton instance

I need to complete the piece of code to write a method that takes a factory method that returns an object and determines if the object is a singleton instance.This is for an exercise of a course i am taking about design patterns. All the previous exercises were about implementing the pattern but this one is about testing and i dont have any idea how to test this

 public class SingletonTester
{
  public static bool IsSingleton(Func<object> func)
  {
    // todo        
  }
}

lundi 18 juillet 2022

Add an extra property to an element without inheritance

I am thinking about the best practice in OOP for the following problem:

We have a program that is working with an external API.

The API has an object of type Element which is basically a geometric element. Our application is a validation application that runs on a geometric model The application takes a collection of those elements and performs some geometric tests on them.

We wrap this API element with our own class called "ValidationElement" and save some additional information to this wrapper element that can not be obtained directly from the API Element but is required by our application.

So far so good, but now the application should expand and support other types of models (basically we can say that the app is running in a different environment). Specifically for this environment (and it does not apply to the previous cases), we want to save an additional parameter that obtaining it results in low performance.

What is the best practice option to implement it? On one hand, I would like to avoid adding extra parameters that are not relevant to a specific(the first) part of the program. And on the second hand, I am not sure that I want to use inheritance and split this object just for this small additional property.

public class ValidationElement
{
        public Element Element { get; set; }
        public XYZ Location {get; set;}//The extra property
}

The first and easy option is that the same class will have the additional property and calculation method:

public class ValidationElement
{
        public Element Element { get; set; }
        public XYZ Location {get; set;}//The extra property
        public string AdditionalProperty { get; set; }
        public void HardProcessingCalcOfAdditionalProperty()
        {
            //hard processing
            AdditionalProperty = result
        }
}

The second option that I mentioned is the inheritance

public class SecondTypeValidationElement : ValidationElement
{
        public string AdditionalProperty { get; set; }
        public void HardProcessingCalcOfAdditionalProperty()
        {
            //hard processing
            AdditionalProperty = result
        }
}

What do you think is the best practice for this? Is there any other way or design pattern that should help me achieve the goal?

Java : Cannot use generic in abstract class

In my Spring Boot app, I am trying to implement Template Method and in my concrete class, I am trying to use generic as shown below:

template interface: Not sure if I need to use it?

public interface PDFGenerator {

    String createHtml(UUID uuid);
}

template abstract class:

public abstract class AbstractPDFGenerator<T> implements PDFGenerator {

    @Override
    public String createHtml(UUID uuid) {
        T dto = getDTO(uuid);

        Context context = new Context();        
        context.setVariable(getName(), dto.getName());

        // ...
    }

    protected abstract T getDTO(UUID uuid);

    protected abstract String getName();

    // code omitted
}

concrete classes:

@Service
@RequiredArgsConstructor
public class BrandPDFGenerator extends AbstractPDFGenerator<BrandDTO> {

    private static final String NAME = "brandName";
    private final BrandService brandService;

    @Override
    protected String getName() {
        return NAME;
    }

    @Override
    protected BrandDTO getDTO(UUID uuid) {
        return brandService.findByUuid(uuid);
    }

    // ...
}
@Service
@RequiredArgsConstructor
public class ProductPDFGenerator extends AbstractPDFGenerator<ProductDTO> {

    private static final String NAME = "productName";
    private final ProductService productService;

    @Override
    protected String getName() {
        return NAME;
    }

    @Override
    protected ProductDTO getDTO(UUID uuid) {
        return productService.findByUuid(uuid);
    }

    // ...
}

I get "Cannot resolve method 'getName' in 'T'" at the dto.getName() line in AbstractPDFGenerator.

My questions are:

1. In order to fix the problem, I think of extending T from a base class from which BrandDTO and ProductDTO are inherit. However, I do not want to inherit them from a base class as they have not used similar purpose. So, how can I fix that problem ("Cannot resolve method 'getName' in 'T'")?

2. Do I need to use PDFGenerator interface? Or should I remove it?

How to include update in Builder pattern

I want to use Builder pattern to create my entities in django, but I discover something very useful, the create_or_update method. If I stick to Build design principles, I think I should not use this method, but for me it's very useful, because this let me make it transparent for the client.

I can create other class, and maybe an intermediate one to use the builder or the method, maybe the Director class? I don't know.

Have any idea? should I use Builder, Director, or another different pattern?

dimanche 17 juillet 2022

What if i instantiate all the classes in one function and call that function every where?

if i have n classes and instantiate all the classes in one function, what are the major drawbacks for this . ex bellow :-

class A{}
class B{}
class C{}
.
.
class Z{}



main(){
new classA()
new classB()
.
.
.
new classZ()

}

and where ever I need any class. I just call the main method. I know that this is bad , but and IOC should be used , but what are the major disadvantages of using this ?

What is the name of this design pattern with "cascading attributes"?

Say I have the following classes:

DO_NOT_OVERRIDE = type() # this dictates if an attribute won't be overridden.

class Parent():
    def __init__(self, a: int = 0, b: int = 0):
        self.a = a
        self.b = b

class Child():
    def __init__(self, parent: Parent, a: int = DO_NOT_OVERRIDE, b: int = DO_NOT_OVERRIDE):
        self.parent = parent
        
        self._a = a
        self._b = b

    @property
    def a(self):
        if self._a is DO_NOT_OVERRIDE:
            return self.parent.a

        return self._a

    @a.setter
    def a(self, value: int):
        self._a = value


    @property
    def b(self):
        if self._b is DO_NOT_OVERRIDE:
            return self.parent.b

        return self._b

    @b.setter
    def b(self, value: int):
        self._b = value

Now, let's create some objects.

parent_obj = Parent(a = 1, b = 2)
child_obj_1 = Child(parent = parent_obj)

child_obj_1.a would return 1 and child_obj_1.b would return 2, which are both values from parent.a and parent.b respectively

But consider another Child:

child_obj_2 = Child(parent_obj, a = 20)

child_obj_2.a would return 20 which is a value set in child_obj_2, though child_obj_2.bwould still return2sinceb` is not "overridden" by the child object.


What is this design pattern?

samedi 16 juillet 2022

Pixelpattern of a rasterlayer

I have a rasterlayer with following stats:

class : RasterLayer dimensions : 23320, 37199, 867480680 (nrow, ncol, ncell) resolution : 0.02, 0.02 (x, y) extent : 341668.9, 342412.9, 5879602, 5880069 (xmin, xmax, ymin, ymax) crs : +proj=utm +zone=33 +ellps=WGS84 +units=m +no_defs source : r_tmp_2022-07-16_110243_24217_93736.grd names : layer values : 2.220446e-16, 0.2999999 (min, max)

And if i plot it it looks like this: Raster

Now i want a function that shows me were the most pixel clump togehter or have the most density. I hope u know what i mean.

I tried the clump() function but its not working how i want it.

Pixel<- MyRaster Clump_Pixel <- clump(Clump_Pixel,directions=4, gaps=FALSE) plot(Clump_Pixel)

Well it looks like this: Pixel_Raster

My other idea is to use the density() function. But for that i need to use the ppp () function and i cant create a window with as.owin. Its because i have a Raster.

Raster_Owin <- as.owin(MyRaster)

So i dont know how to use this function and i dont know another way to do my analysis.

What data model to use for tables in Blazor

I am building a .Net 6 Blazor web app. I needs to display lots of html tables with data. For example I need tables that look like this:

       |Jul 17 | Jul 16  | Jul 15
--------------------------------- . . .
Hour 1 | 11.213 | 123.23 | 123.54
Hour 2 | 12.234 | 234.45 | 54.34
.
.
.

Code:

I want to display a lot of tabular data and I would like to be able to compute new tabular data based on the ones I already have, like calculating averages of an existing "table" models rows.

I considered having a data structure like this:

public class DataTable
{
    public DataTable(Dictionary<string, Dictionary<string, decimal?>>? values)
    {
        Values = values ?? new Dictionary<string, Dictionary<string, decimal?>>();
    }

    public Dictionary<string, Dictionary<string, decimal?>>? Values { get; set; }
}

Questions:

  • Is this a good approach?
  • How can I store optional row and column headers?
  • What if I want to create a table with strings? I can't restrict extension methods for a generic class to "number" types, so it seems to no be good design.

PEP8, blank line convention and reduced readability in dense code

Most of the time, PEP8 does not allow more than 1 blank line inside function or more than 2 blank lines between functions. When code is dense, even 2 blank lines can reduce readability.

Is there any guidance how to overcome this? Use some visual elements composed of ASCII characters?

def fun1():
    """
    This does x
    """

    ## Problem 1

    # Subproblem 1.1    
    ...

    # Subproblem 1.2
    ...

    ## -------------------
    ## Problem 2
    ...

# ------------------------
def fun2():
    """
    This does y
    """
    pass   

vendredi 15 juillet 2022

Circular design pattern?

I have a class A and class B. Class A has a parameter which is a list of objects of class B. Class B has a parameter which is an object of instance A.

Would inheritance help me somehow here?

What would be the best design pattern to solve this problem?

constructing completely private and anonymous static singleton

I was trying to think of a way how to deal with C libraries that expect you to globally initialize them and I came up with this:

namespace {

class curl_guard {
public:
    curl_guard()
    {
        puts("curl_guard constructor");
        // TODO: curl_global_init
    }
    ~curl_guard()
    {
        puts("curl_guard destructor");
        // TODO: curl_global_cleanup
    }
};

curl_guard curl{}; // nothing is ever printed to terminal

}

But when I link this into an executable and run it, there's no output, because it is optimized out (verified with objdump), even in debug build. As I understand, this is intended, because this type is never accessed in any way. Is there any way to mark it so that it is not excluded? Preferably without making it accessible to the user of the library. I'd prefer a general solution, but GCC-only also works for my purposes.

I am aware of typical singleton patterns, but I think this is a special case where none of them apply, because I never want to access this even from internals, just simply have a class tucked away which has one simple job of initializing and deinitializing a C library which is caused by the library being linked in and not something arbitrary like "just don't forget to construct this in main" which is as useful as going back to writing C code.

jeudi 14 juillet 2022

How to determine design pattern from time complexity

I've encountered this question on an informal test.

T(n) is a reccurance relation

If the time complexity of an algorithm with input size of n is defined as:

T(1)=A

T(n)=T(n-1)+B when n>1

Where A and B are positive constant values.

Then the algorithm design pattern is best described as:


A. Decrease and Conquer - Correct answer

B. Divide and Conquer

C. Quadratic

D. Generate and Test

T(n) converges down to T(n) = nB + A -> O(n)

  1. What's the difference between answer A and B?

  2. Why is the answer Decrease and Conquer?

Chain of transformations based on generic types

I'm thinking about a chain, that will allow me to perform a set of transformations with data type changing from transformation to transformation. So far I've got something like this:

public abstract class TransformationStep<T, TY>
{
    public abstract TY Execute(T input);
}

public class Times2<TY> : TransformationStep<int, TY>
{
    public Times2(TransformationStep<int, TY> next)
    {
        Next = next;
    }

    public TransformationStep<int, TY> Next { get; set; }

    public override TY Execute(int input)
    {
        var res = input * 2;
        return Next.Execute(res);
    }
}

public class ToString<TY> : TransformationStep<int, TY>
{
    public ToString(TransformationStep<string, TY> next)
    {
        Next = next;
    }

    public TransformationStep<string, TY> Next { get; }

    public override TY Execute(int input)
    {
        var res = input + "!!!";
        return Next.Execute(res);
    }
}

The only problem I see is the end chain type, where I can't convert T to TY.

public class End<T, TY> : TransformationStep<T, TY>
{
    public override TY Execute(T input)
    {
        return input;
    }
}

Do you have any solution? Also what do you think about this design and do you know any good materials on stuff like that?

Should I improve something in this Node.js code? Iam newbie please help me I can't sign up my webapp that Iam creating (error 404 server) [closed]

I just want to make sure that this is the right code for using node.js ? or am i missing something ? Iam not tough backend guy please suggest me

const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const morgan = require('morgan');
const cors = require('cors');
require('dotenv').config();
const mongoose = require('mongoose');

mongoose.connect(
  process.env.MONGO_DB_URI,
  { useNewUrlParser: true, useUnifiedTopology: true },
);


const usersRouter = require('./routes/users');
const listRouter = require('./routes/list'); 
const databaseRouter = require('./routes/database');

const publicPath = path.join(__dirname, 'build');

const app = express();
app.use(cors());


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(morgan('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// I just import my logic 
app.use('/users', usersRouter);
app.use('/database', databaseRouter);
app.use('/list', listRouter); 

app.get('*', (req, res) => {
  res.send(path.join(publicPath, 'index.html'));
});


app.use((req, res, next) => {
  next(createError(404));
});

// error handler
app.use((err, req, res) => {
 
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;

and file that I want to execute (have shabang -> #!/usr/bin/env node )

const app = require('../app');
const debug = require('debug')('backend:server');
const http = require('http');
 


 
//Create HTTP server
const server = http.createServer(app);
 
 
  //Get port from environment and store in Express
const port = normalizePort(process.env.PORT || '4000');
app.set('port', port);
 //Normalize a port into a number, string, or false
function normalizePort(val) {
   const port = parseInt(val, 10);
 
   if (isNaN(port)) {
     // named pipe
     return val;
   }
 
   if (port >= 0) {
     // port number
     return port;
   }
 
   return false;
 }
 
  //Listen on provided port, on all network interfaces
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);


//This function will check which type of error occurred,
// log something different, and exit gracefully from our nodejs server.
function onError(error) {
   if (error.syscall !== 'listen') {
     throw error;
   }
 
   const bind = typeof port === 'string'
     ? `Pipe ${port}`
     : `Port ${port}`;
 
  
   switch (error.code) {
     case 'EACCES':
       console.error(`${bind} requires elevated privileges`);
       process.exit(1);
       break;
     case 'EADDRINUSE':
       console.error(`${bind} is already in use`);
       process.exit(1);
       break;
     default:
       throw error;
   }
 }
 
//Event listener for HTTP server "listening" event
 
function onListening() {
   const addr = server.address();
   const bind = typeof addr === 'string'
     ? `pipe ${addr}`
     : `port ${addr.port}`;
   debug(`Listening on ${bind}`);
}

Any mistake that I made please correct me or want some information that need to show please tell me. Thankyou