mardi 31 janvier 2023

How to match a value from a string using regex in bash shell?

I am in bash shell and I have this strings "abc" "abc-abc-abc" "abc_abc_abc" "abC" "aBc" "A_A-A"

i want regex pattern match

capturing occurrences and finding its count in a list

I have a situation where a list of last occurrences is available. Say the list is. ['user', 'user', 'sys', 'sys', 'user', 'user', 'sys', 'user'] So the ask is if a user has occurred how many times did it occur consecutively? if there is a change in element say 'sys' instead of 'user' the count should start fresh. The output I am looking for is [('user', 2), ('sys', 2), ('user', 2), ('sys', 1), ('user', 1)] this would help me identify the pattern the user and system is following. Any help is much appreciated.

Uploading files using design pattern with python

I used to upload csv, excel, json or geojson files in my a postegreSQL using Python/Django. I noticed that the scripts is redundant and sometimes difficult to maintain when we need to update key or columns. Is there a way to use design pattern? I have never used it before. Any suggestion or links could be hep!

lundi 30 janvier 2023

Regex php - Match some escape characters inside attribute values

Well, basically I'm triying to match some escape characters inside some attributes ("name" & "author").

I'm working on a file uploader where one of the files which is uploaded is a .xml file.

Before parsing it to an XML Format, I'm trying to replace those characters with right format. IE: < to &lt; or ' to &apos; ...etc

These characters are inside single ' quotes or double quotes "

The format of the raw data is:

<info name="Name containing ' apostrophe" author="Lower than < Character" ></info>
<info name='Name containing ' apostrophe' author='Lower than < Character' ></info>

The patter I have just tried is the following one

(name|author)="(\\\\[\\\\"]|[^\\\\"])*"[<|']

However it stopped matching content inside tags.

python if list_item == re.match

I'm trying to practice regex patterns with conditions in python (googlecollab), but stuck in (if... and...) by getting proper numbers from the list[000 to 999] - i need only numbers, ending with one digit '1' (not 11, 111, 211 - I need only 001, 021, 031, 101), but it returns nothing with multiple condition... if I clear code starting with 'and' in condition - it returns all ones, elevens, hundred elevens...

list_ = []
list_.append('000')
for a in range(999):
    list_.append(str(a+1))

for i, el in  enumerate(list_):
    if len(el) == 1:
        list_[i] = '00'+el
    elif len(el) == 2:
        list_[i] = '0'+el

for item in list_:
    try:
        if item == re.match(r'\d\d1', item).group() \
        and item != re.match(r'\d11', item).group():
            print(item) 
    except:
        pass    

OpenCV Python remove object/pattern from images

I have been facing this problem from some days: i need to remove this image/pattern from images like this or this using OpenCV. I know that the problem is a Template Matching problem and I have to use filters (like canny) and and "slide" the template over the image, once this has been transformed by the filters.

I tried some solutions like this or this, but i had poor results, for example applying the second method I obtain this images 1 2

this is my code

import cv2
import numpy as np

# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    # Grab the image size and initialize dimensions
    dim = None
    (h, w) = image.shape[:2]

    # Return original image if no need to resize
    if width is None and height is None:
        return image

    # We are resizing height if width is none
    if width is None:
        # Calculate the ratio of the height and construct the dimensions
        r = height / float(h)
        dim = (int(w * r), height)
    # We are resizing width if height is none
    else:
        # Calculate the ratio of the 0idth and construct the dimensions
        r = width / float(w)
        dim = (width, int(h * r))

    # Return the resized image
    return cv2.resize(image, dim, interpolation=inter)

# Load template, convert to grayscale, perform canny edge detection
template = cv2.imread('C:\\Users\Quirino\Desktop\Reti\Bounding_box\Checkboard.jpg')
template = cv2.resize(template, (640,480))
template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
template = cv2.Canny(template, 50, 200)
(tH, tW) = template.shape[:2]
# cv2.imshow("template", template)

# Load original image, convert to grayscale
original_image = cv2.imread('F:\\ARCHAIDE\Appearance\Data_Archaide_Complete\MTL_G6\MTL_G6_MMO090.jpg')
# original_image = cv2.resize(original_image, (640,480))
final = original_image.copy()
gray = cv2.cvtColor(original_image, cv2.COLOR_BGR2GRAY)
found = None

# Dynamically rescale image for better template matching
for scale in np.linspace(0.2, 1.0, 20)[::-1]:

    # Resize image to scale and keep track of ratio
    resized = maintain_aspect_ratio_resize(gray, width=int(gray.shape[1] * scale))
    r = gray.shape[1] / float(resized.shape[1])

    # Stop if template image size is larger than resized image
    if resized.shape[0] < tH or resized.shape[1] < tW:
        break

    # Detect edges in resized image and apply template matching
    canny = cv2.Canny(resized, 50, 200)
    detected = cv2.matchTemplate(canny, template, cv2.TM_CCOEFF)
    (_, max_val, _, max_loc) = cv2.minMaxLoc(detected)

    # Uncomment this section for visualization
    '''
    clone = np.dstack([canny, canny, canny])
    cv2.rectangle(clone, (max_loc[0], max_loc[1]), (max_loc[0] + tW, max_loc[1] + tH), (0,255,0), 2)
    cv2.imshow('visualize', clone)
    cv2.waitKey(0)
    '''
    # Keep track of correlation value
    # Higher correlation means better match
    if found is None or max_val > found[0]:
        found = (max_val, max_loc, r)

# Compute coordinates of bounding box
(_, max_loc, r) = found
(start_x, start_y) = (int(max_loc[0] * r), int(max_loc[1] * r))
(end_x, end_y) = (int((max_loc[0] + tW) * r), int((max_loc[1] + tH) * r))

original_image = cv2.resize(original_image, (640,480))
# Draw bounding box on ROI to remove
cv2.rectangle(original_image, (start_x, start_y), (end_x, end_y), (0,255,0), 2)
cv2.imshow('detected', original_image)

# Erase unwanted ROI (Fill ROI with white)
cv2.rectangle(final, (start_x, start_y), (end_x, end_y), (255,255,255), -1)
final = cv2.resize(final, (640,480))
cv2.imshow('final', final)
cv2.waitKey(0)

what could i try?

How to pass data among inter-dependent but different objects in C++? [closed]

I am facing design issues with my current task at hand.

I am implementing a service in C++ which has basically two main aims to acheive:

  1. Control LEDs and set a specific pattern based on incoming request to service
  2. Decide next state of system based on current state and incoming request to service

I have thought of Application, LEDController & State classes for the implementation. I am facing difficulty in communicating among different objects. I am unable to have seamless flow of data from one object to another.

Kindly refer to code snippet below:

/* Deals with the LED driver code */
class LEDController
{
    public:
        turnONLed(int pattern);
        turnOFFLed();
};

/* Base class for different states of the system */
class State
{
    protected:
        std::string stateName;
    public:
        void transitionTo(State* newState);
        virtual void HandleSystemOnEvent() = 0;
        virtual void HandleSystemOnEvent() = 0;
        virtual void HandleSetLEDPatternRequest() = 0;
        virtual void HandleCancelLEDPatternRequest() = 0;
};

/* Some derived states here and concrete implementations for their member functions */
class DefaultState: public State;
class SystemONState: public State;
class SystemServingLEDRequest : public State;

/* Service object implementation */
class Application
{
    LEDController* ledController;
    State* currentState;
public:
    Application();
    void waitForEvents();
    void serveEvent( EventData data);
};

Application::serveEvent(EventData data)
{
    switch( data.eventType)
    {
        case SystemON:
            currentState->HandleSystemOnEvent( ??? );  
            /*  Help needed here!
                Inside these polymorphic functions {HandleSystemOnEvent, HandleSystemOnEvent, ...} , I want to control the LEDs and make decision for new state.
                How to access Application::ledController from inside of State ?
                Also how to manipulate Application::currentState from these functions.
            */
            newState = new SystemOnState();
            currentState->transitionTo(newState);
            break;
        case SystemOFF:
            currentState->HandleSystemOffEvent();
            break;
        case SetPatternRequest:
            currentState->HandleSetLEDPatternRequest();
            break;
        case CancelPatternRequest:
            currentState->HandleCancelLEDPatternRequest();
            break;
    }
    
}

I want to achieve LED control and state related decisions inside the polymorphic functions of State object. Can you kindly suggest on how to achieve this or other design suggestions to fix this issue.

dimanche 29 janvier 2023

What is the best pattern to create structs and grant resources

I am curious about is the a good pattern to create golang structs with the ability to grant resources (db, client, etc)

In my case I have a struct called GetUser with the following fields

type GetUser struct {
  DB  *sql.Conn
  Req model.GetUserReq
}

where DB is the connection to postgres. Also I have a struct which have a grpc client to make a HTTP request.

type GetUserTweets struct {
  DB  *sql.Conn
  Client grpc.Client
  Req model.GetUserTweetsReq
}

The thing is the structure GetUserTweets will be created only once GetUser finished successfully, and I have a question is the a good pattern for that, because when GetUserTweets finishes I want to create another struct let's say with SQL connection, redis Connection but without grpc Client. Should I provide all my structures with all possible fields and create something like that and pass it to another my struts ?

type GetUser struct {
  DB  *sql.Conn
  Redis *redis.Conn
  TweeterClient grpc.Client
  InstagramClient grpc.Client
  Req model.GetUserReq
}

Lifetime of return value not directly related to parameter lifetime

I am new to rust, and having trouble figuring out the correct design pattern for what I am trying to do. In my program, there are Position structs, which reference a single coordinate system that they "belong" to. I have understood that rust must therefore be able to guarantee that coordinate_system reference outlives the Position. So far so good.

The issue is in a function such as transform_to_parent, where I want to create a new Position which is dependent on the lifetime of the exact coordinate_system that it later references, and not on the lifetime of the self parameter through which it accesses the coordinate system. This seems to be the only thing that lifetime specifiers would allow.

If I add a lifetime specifier to the following code, it compiles, but understandably complains when I let the old Position that I transformed from goes out of scope.

pub struct Position<'a> {
    // Position data omitted
    coordinate_system: &'a CoordinateSystem<'a>,
}

impl<'a> Position<'a> {
    fn transform_to_parent<'b>(self: &'b Self) -> Option<Position<'b>> {
        Some(Position {
            coordinate_system: self.coordinate_system.origin?.coordinate_system
        })
    }
}

pub struct CoordinateSystem<'a> {
    origin: Option<&'a Position<'a>>,
} 

// Test case
fn main() {
    // child_system is the child coordinate system of root_system, and has its origin at child_origin
    let root_system = CoordinateSystem { origin: None };
    let child_origin = Position { coordinate_system: &root_system };
    let child_system = CoordinateSystem { origin: Some(&child_origin) };

    let mut p2 = Position { coordinate_system: &child_system };
    {
        let p1 = Position { coordinate_system: &child_system };
        if let Some(x) = p1.transform_to_parent() { // Error: "borrowed value does not live long enough"
            p2 = x;
        }
    }
    // No-op, just pretend to use p2 again, after p1 has gone out of scope
    p2;
}

Is it possible for Rust to bind the lifetime of the function result to the lifetime of self.coordinate_system.get_origin()?.coordinate_system (i.e. the parent coordinate system), instead of the self? Is there a correct design pattern for something like this?

I assume that a ref-counting system would work, but I think that would be bad design, because there is clear ownership of the coordinate systems, and because the lifetime information should be deducible somehow.

Message broker/queue architecture design pattern

I'm designing the architecture of a platform to introduce a message broker in an existing data collection web application.

This web application is currently used to upload data from excel files that are then validated, processed and inserted into a database. Every time a new set of data is inserted we should run one or more scripts, depending on the nature of the data, to perform a deep analysis of the data.

These scripts are written by data scientists or other programmers, therefore are not in the same technology as the main application and some of them are also hosted on another machine. Some of this script could run for also 2~3 hrs to produce the results.

For the above reasons, I think that introducing a message broker, like RabbitMQ or SQS or Kafka, could be an added value to making these applications talks together and synchronize their running processes.

The messages should be two-way: The main application should notify the "scripts" that there is new data available to be processed, and the "scripts" should notify the main application when they have finished (so I can also run sequential operations...)

I foresee having around 200 messages exchanged per day with a max peek of 400msgs/day, splitter in ~10 different queues/topics.

The software architect is contesting me to have only one message broker he said that I need to make one broker for each way, so I need to set up one message broker for the messages produced by the main application and another one for the messages produced by the "scripts" and micro-services.

I think it's really a waste of resources considering the amount of data that I have to manage.

Am I wrong and there is something I'm missing in the design pattern?

my design with only one message broker to manage both consumers/producers

Can I use the Facade pattern for Admin/Front Interfaces [closed]

I'm new to Design Patterns and working on the improve the my skills about Design Patterns. I wanna learn to can we use the Facade pattern to seperate the Admin Panel and Front of Website interfaces?

And also can you give few examples about usage of the Facade patterns.

(I am using the PHP)

samedi 28 janvier 2023

Decorating with arguments a Class Declaration

I'm trying to create a Class representing a regex to execute for my application. For each regex I have a link to the regex101.com page where users can find unit tests. I wanna use this solution to have near the class declaration this link but without having them in the class code. The code I think about has to look like this:

class TestUrl(object):
    def __init__(self, url) -> None:
        self.url = url
        
    def __call__(self, cls) -> Any:
        functools.update_wrapper(self, cls)
        cls.url = self.url

        def wrapper(*args: Any, **kwds: Any):
            return cls(*args, **kwds)
        
        return wrapper

def test_url(url):
    def wrapper_class(cls):
        cls.test_url = url

        @functools.wraps(cls)
        def wrapper(*args, **kwargs):
            return cls(*args, **kwargs)

        return wrapper

    return wrapper_class

class Regex:
    def __init__(self, pattern, repl, flags) -> None:
        self.exp = re.compile(pattern, flags=flags)
        self.repl = repl
        self.flags = flags

    def sub(self, string: str):
        return self.exp.sub(self.repl, string)

@test_url("https://regex101.com/r/.../...")
class SubRegex(Regex):
    def __init__(self):
        super().__init__(r'...', r'...', re.MULTILINE | re.DOTALL)

But my problem is that when I wanns cycle on all classes in the module using this code:

def test_all_regexs(regex):
    module = importlib.import_module("...")
    print(f"Looking at {module}")
    for name, obj in inspect.getmembers(module):
        if inspect.isclass(obj):
            print(f"Class: {name}, {obj}")
        if inspect.isfunction(obj):
            print(f"Func: {name}, {obj}")

The output is always:

Func: SubRegex, <function SubRegex at ...>
Class: Regex, <class '....Regex'>
Class: TestUrl, <class '....TestUrl'>
Func: test_url, <function test_url at ...>

I can't figure out how obtain SubRegex as Class, not as Func. How can I get this?

P.S.: Do you have another way to don't mix application logic like regex patterns with the url I use only for documentation?

vendredi 27 janvier 2023

Two classes with exact same methods and field. Only 1 field has different value

Client needs me to provide two different classes Service1Transformer and Service2Transformer. Both classes need to implement the interface Transformer which only contains a transform() method. Now after writing all the logic for transformation, it is the exact same for Service1 and 2, with the difference being in a large list that carries specifications (hardcoded specs) and the output of transformation. So I created an abstract class with all the methods implemented, and just left the method that generates the specs/output abstract. The 2 classes extend that base class and only implement the specs/output generation method. Specs/output are just a nested list of lists and pairs.

Unfortunately the checkstyle validator setup for that code base refuses my spec/output generation method because it is more than 100 lines long (it’s quite a long list). So looks like I need to make these specs/output become a field rather than getting generated by a method. But I can’t do that because of field hiding.

Any thoughts on what a good approach to this design issue would be?

interface Transformer {
    public String transform();
}

abstract class ServiceTransformer implements Transformer {
    public String transform() {…}
    public abstract List<Pair<String,List<String>>> generateTransformationSpecsAndOutputContainer();

}

class Service1Transformer extends ServiceTransformer {
    public abstract List<Pair<String,List<String>>> generateTransformationSpecsAndOutputContainer() {…}
}

class Service2Transformer extends ServiceTransformer {
    public abstract List<Pair<String,List<String>>> generateTransformationSpecsAndOutputContainer() {…}
}

Multiple diffrent class to create instance of same class

I have 10 diffrent classes like a,b,c which have diffrent primary keys and structure but every class will b having a button which will be opening a same class like Charges if gets clicked. I want to save charges class information along with the primary Key of the relevant class(a,b,c) from which it gets called.What would be the best design pattern for it. Thanks

Please guide.

how do I get an input field in html to ensure the pattern contains a specific country code eg 1472 followed by 3 number and then 4 numbers

I have different sign up pages that load for different countries, and I need the telephone input to be for that specific country, such as on one page it needs to be the country code 1234 followed by any 3 numbers and then any 4 numbers. so I need the pattern for the input in the html form. I am dealing with it on the server side with PHP, but I want to handle it on the client side via the input restriction pattern, as to be more efficient. Im sure its really simple but I cant seem to find a simple solution. thanks for your help

i tried the pattern restriction, i casn get the any 4 number, space, any 3 number, space any 4 numbers. but i could not get the: '1234' specific number, space, any 3 number, space, any 4 numbers.

Rust equivalent of Java Consumer interface for Strategy pattern

I will provide a practical example.

I want to create an event logger. I define an event as an Interface:

import java.util.function.Consumer;

interface Event {}

class BuyEvent implements Event {}

class SellEvent implements Event {}

A logger is simply a Consumer of events:

public static void main(String[] args) {
        Consumer<Event> logger;

        // Logger with method reference
        logger = System.out::println;
        logger.accept(new BuyEvent());

        // Logger with lambda
        logger = (event) -> {
            // Do something else
            System.out.println(event);
        };
        logger.accept(new BuyEvent());

I can also create a logger with state. For example:

class StatefulLogger implements Consumer<Event> {
    public StatefulLogger() {
    }

    @Override
    public void accept(Event event) {
        // Change state, then print event
        System.out.println(event);
    }
}

I can use the stateful logger as follows:

public static void main(String[] args) {
        Consumer<Event> logger = new StatefulLogger("foo.txt");
        logger.accept(new BuyEvent());
}

I am trying to achieve the same in Rust.

I define an event as an enum:

#[derive(Debug)]
enum Event {
    BuyEvent,
    SellEvent,
}

I define a Logger trait and a struct with state that implements such trait:

trait Logger {
    fn accept(&mut self, ev: Event);
}

struct StatefulLogger {}

impl Logger for StatefulLogger {
    fn accept(&mut self, ev: Event) {
        // Change state, then print event
        println!("{:?}", ev);
    }
}

I can use the logger as follows:

fn main() {
    let logger: &dyn Logger = &ComplexLogger {};
}

I would like to be able to assign a closure to the logger, much in the same spirit of Java.

fn main() {
    let consumer: fn(Event) = |ev: Event| {
        println!("{:?}", ev);
    };
}

To recap:

In Java, I had implemented a logger using a Strategy design pattern using the Consumer interface. A logger could both be a complex stateful object but also a lightweight lambda.

I would like to achieve the same in Rust, but I don't know how to proceed. I was not able to find similar examples on the Internet. Also, does Rust provide an analogous to Java's Consumer interface?

Is observer pattern and React context the same?

Within the paradigm of React, what is the difference between an observer pattern and React context?

From what I understand, it looks like they're different methods to achieve the same result

How to print character in zig zag pattern

I want to print character in zig zag pattern well I already tried but I'm only able to print star in zig zag pattern

star pattern

**Code of star zig zag pattern **

#include <iostream>
using namespace std;

int main() 
{
    int n;
    cin >> n;
    for(int i = 1; i <= 3; i++)
    {
        for(int j = 1; j <= n; j++){
            if(((i + j) % 4 == 0) || (i == 2 && j % 4 == 0)){
                cout << "* ";
            }
            else{
                cout << "  ";
            }
        }
        cout << endl;
    }
    return 0;
}

I want to print character in zig zag pattern

String in zig zag pattern

Spring inject component into non-spring managed interface/abstract class and its subclasses

TLDR: I need an interface/abstract class and all classes implementing it to have access to a Spring managed bean. Can Spring inject a bean into an interface/abstract-class and its subclasses simply via @Autowired ?

I am working on an API built with Spring Webflux + Cloud Gateway that depending on the cookie JWT authorized party, identifies the User's policy group and assign an Attribute ENUM "InterfaceID" to the ServerWebExchange via exchange.getAttribute().put("InterfaceID",InterfaceID.A) after the JWT is validated, and currently uses "InterfaceID" to represent the different groups of users/different interface the user entered from.

JWTValidationFilter.java [Current]

switch(JWTValidator.validate(jwt).get("AZP")){
    //if user is from company A or its partners
    case "a":
    case "aa":
        exchange.getAttribute().put(InterfaceID.COMPANY_A_ACCESS);
        break;
    case "b":
        exchange.getAttribute().put(InterfaceID.NORMAL_ACCESS);
    ...
}

For certain API endpoints (say /api/getSessionDocument), different "InterfaceID" fetches data from different DB/apis, as well as have different permission checking on top of that.

RequestController.java [Current]

@Autowired
APICallerUtil apiCallerUtil;

switch(exchange.getAttribute.get(InterfaceID)){
    case "NORMAL_ACCESS":
        apiCallerUtil.getDataFromApiA();
        break;
    case "COMPANY_A_ACCESS":
        // call api B but check for permission from api D first
    ...
}

The endpoint's controller now has another switch statement, and to many code analyzers this have been a code smell. I have been trying to refactor this entire bit of code to use polymorphism to handle the different "getSessionDocument" flows, but i run into issues regarding the injection of util classes that calls specific APIs.

APICallerUtil.java class, exisiting class from the project, would prefer not to refactor this.

@Component
public class APICallerUtil{
    @Value("${some uri to some API}") //different by environment and therefore cant be static final
    private String uri1;

    @Value("${some auth to some API}") //confidential
    private String uri1AuthHeader;
    //...

    public JSONObject getDataFromApiA(String somekey){ //cant be static since uri1 is not static
        //Some code that uses uri1 and apache httpclient
        return data;
    }

    ...
}

IBaseAccess.java

interface IBaseAccess{
    default Mono<JSONObject> getSesssionDocument(ServerWebExchange e){return Mono.error("not implemented");}
}

RequestController.java [new]

@Autowired
APICallerUtil apiCallerUtil;

return exchange.getAttribute.get(InterfaceID).getSessionDocument(exchange);

NormalAccess.java

public class NormalAccess implements IBaseAccess{
    //can i autowire APICallerUtil here?
    //use constructor to pass the Util class reference here?

    Mono<JSONObject> getSesssionDocument(ServerWebExchange e){
        //need to call ApiA here
        //need to call ApiC here
    }
}

NormalAccess needs to call APICaller.getDataFromApiA(), but it needs a reference to the Spring managed instance of APICaller. What would be the "correct" way to pass the reference/autowire API caller into NormalAccess, or even better IBaseAccess (so that the implementing classes can use the Util bean)?

JWTValidationFilter.java [new]

switch(JWTValidator.validate(jwt).get("AZP")){
    //if user is from company A or its partners
    case "a":
    case "aa":
        exchange.getAttribute().put("InterfaceID",new CompanyAAccess(/*pass the util class here?*/));
        break;
    case "b":
        exchange.getAttribute().put("InterfaceID",new NormalAccess(/*pass the util class here?*/));
    ...
}

I have tried several methods, but either I lack the knowledge on the specific Spring feature, or that method is deeemed a bad design choice by some, including:

  1. Making the methods and fields in APICallerUtil static, via suggestions from Spring: How to inject a value to static field? and Assigning private static final field member using spring injection , then the Access classes can call the static methods.

  2. Creating a contructor for IBaseAccess that consumes the APICallerUtil reference and store it inside. The JWTfilter would hold an autowired APICallerUtil and pass it in when the attribute is assigned.

  3. Create a static class that provides the application context and Access classes use applicationContext.getBean("APICallerUtil"); to obtain the bean.

  4. Use the @Configurable annotation? I could not find much documentation on how this works for interfaces/abstract-class.

I understand that there might not exist an absolute answer for this question, but regardless I'd like suggestion/feedback on which of these approaches are viable/good. Especailly concerning whether the APIUtil class should be static or not.

jeudi 26 janvier 2023

How can I encapsulate a private mutable object of a class such that it can expose its attributes publicly through an inmutable object?

To be more specific I am designing a Downloader Class that has as member variable a reference to an array of DownloadItem objects which represents resources that the user wants to download over the network. The idea is that a Downloader object will handle the details regarding connecting to the server that hosts the resource, fetching the file data/metadata and writing to disk while also exposing the state of the DownloadItems when queried.

The DownloadItem stores information about the file such as filename, URL, file size, etc. plus other metadata such as the status, progress, when the download started, etc. Some of this information is not known before instantiation therefore the class itself should be mutable to allow for the Downloader object to modify it, but only the Downloader object that created it.

In short I want the properties of the DownloadItem to be accessible through the Downloader object like so:

> DownloaderObj = Downloader()
> unique_id = DownloaderObj.download(url='https://path/to/resource', start_inmediate=False)
> print(DownloaderObj._download_queue)
  [<Class: DownloadItem url: https://path/to/resource filesize: -1>]
> DownloaderObj.start_download(unique_id)  # Handler thread updates metadata on the background
> print(DownloaderObj.get_download_by_id(unique_id).filesize)
  1024
> DowloaderObj.get_download_by_id(unique_id).filesize = 1024 # Should raise NotAllowed exception

One could have a lot of boilerplate code in the Downloader class that exposes those attributes but that increases the coupling between the two classes and makes the class less maintainable if I want to later extend the DownloadItem class to support other fields. Any thoughts or ideas on how I can accomplish this?

Side note: This problem is mostly for my own learning of OOP patterns and design choices so feel free to critique and add as much context as possible.

I tried doing something like:

class InmutableWrapper:
    def __init__(self, obj):
        self._obj = obj

    def __getattr__(self, val):
        return self._obj.__getattr__(val)

then returning InmutableDownloadItemObj = InmutableWrapper(DownloadItemObj) on the call to Downloader.get_download_by_id() but I could still do assignments which would be reflected when the property was queried:

> print(Downloader.get_download_by_id(unique_id).filesize)
  1024
> Downloader.get_download_by_id(unique_id).filesize = 2    # Assigment goes through
> print(Downloader.get_download_by_id(unique_id)._obj.filesize) # Underlying object remains unchanged
  1024 
> print(Downloader.get_download_by_id(unique_id).filesize)
  2

Why does this code does not give result and keeps running?

->this code gonna work only when all characters in the pattern are distinct
->pattern matching question.

#include<iostream>
using namespace std;
void patSearching(string &text,string &pat)
{
    int n=text.length();
    int m=pat.length();
    for(int i=0;i<n-m;)
    {
        int j;
        for(j=0;j<m;j++)
        {
            if(pat[j]!=text[i+j])
              break;
              if(j==m)
              cout<<i<<" ";
              if(j==0)
              i++;
              else
              i=i+j;
        }
    }
}
int main()
{
    string text="ABCABCD";//it is the text against i try to match the pattern
    string pat="ABCD";//pattern
    patSearching(text,pat);
}

Even i tried to debug my code.But it doesn't work

Syntactically everything looks right compiler didn't give any error.

What can be the run time error here?

How to make a memory book for my batchmates of 100 members in college [closed]

I'm at the end of my college We all want to make a book , 1 page for each member Like a memory book, about themselves and their future plans , memories they made like that Help me with ideas as to what softwares should I use Design templates

Thank you

Expecting softwares that would help me to make a book Ideas Any guides Designs

mercredi 25 janvier 2023

what is the design pattern of inform

I'm studying design patterns. I wondered what the design pattern of the project was basically created when I created the WinFoam project in the Visual Studio. what is the design pattern of winform when I create new winform project in visual studio?

Is there a design-pattern that addresses creation of the same product in multiple different ways (requiring pipeline-like pre-creation steps)

I am currently working on a machine learning project and would like my Python program to be able to process/convert measurement data from various measurement data formats into a PyTorch compatible dataset class. This essentially means that I need to extract samples and labels from these measurements so that I can instantiate my dataset class.

Right now: I am mainly using a single libraryA which provides all functions I need to load and preprocess the data. To extract the samples and labels as needed I have to follow several processing steps which is why I decided to encapsulate that logic in a simple factory class.

My concern is: What if I need to handle a data format that is not supported by libraryA but by another libraryB. That libraryB, however, has a very different approach on how to extract the samples and labels and requires different processing steps.

My initial thought: Use an abstract factory or a factory method to create the dataset object and let the subclass decide how to do it. But, despite that I am not following the intent of abstract factories / factory method as stated by the GoF (I always want the same single product), the signatures of the abstract methods won't match because the libraries require very different inputs.

My question: Is there a suitable Design-Pattern that standardizes the creation of the same product with very different pre-creation steps?
Or should I stick to concrete simple factories that are tightly coupled to the library (e.g. LibADatasetFactory and LibBDatasetFactory)?

How to store/send linking events using event sourcing?

I have an endpoint which is linking entity1 to entity2 (many to many), so after they were linked I need to send an integration event. I am using event sourcing and outbox pattern. So what must be the aggregate of my event? entity1 or entity2 What must be the topic of my integration event? entity1 or entity2

Also in the event store(where I store domain events) I need to specify streamName, but as I understand it needs to be buisness valued entity name, so it cannot be like entity1_entity2 (the name of linking table)?

Trying to design a 8 bit down counter, which counts down from a number which we input and when it becomes 0, again it resets to the input number

Task: Designing a 8-bit downcounter which takes an initial input value and start the downcount, and when count becomes 8'b0000_0000, it should automatically set to input value.

Ex: If given input is 8'b10010100, counter should start counting down, when value reaches 8'00000000, it should automatically reset to 8'b10010100, and again start downcount repeatedly. For this had written a modified D flip flop using behavioral method, which works as follows: When ld=0, output of d-flip flop q=d1 and q_bar=~d1 and when ld=1, q=d2 and q_bar=~d2 Here d2 stores the initial input values, and ld is being used as switch, i.e. when q=8'b00000000, ld=1 and sets counter output q=d2 and next cycle, ld=0 and takes d1 value.

Modified D-flip flop

module modified_d_flip_flop(q,q_bar,d1,d2,clk,ld
    );
    input d1,d2,clk,ld;
    output q,q_bar;
    reg q,q_bar;
    always @(posedge clk)
        begin
                if(ld==0)
                begin
                q<=d1;
                q_bar<=~d1;
                end
            else if(ld==1)
                begin
                q<=d2;
                q_bar<=~d2;
                end
            else
                begin
                q<=q;
                q_bar<=q_bar;
                end
            end
    endmodule

Down Counter:

module down_counter(
    input [7:0] d,
    input clk,
    input ld,
    output [7:0] q,
    output [7:0] q_bar
    );      
    modified_d_flip_flop m_dff1 (.q(q[0]), .q_bar(q_bar[0]), .d1(q_bar[0]), .d2(d[0]), .clk(clk), .ld(ld));
    modified_d_flip_flop m_dff2 (.q(q[1]), .q_bar(q_bar[1]), .d1(q_bar[1]), .d2(d[1]), .clk(q[0]), .ld(ld));
    modified_d_flip_flop m_dff3 (.q(q[2]), .q_bar(q_bar[2]), .d1(q_bar[2]), .d2(d[2]), .clk(q[1]), .ld(ld));
    modified_d_flip_flop m_dff4 (.q(q[3]), .q_bar(q_bar[3]), .d1(q_bar[3]), .d2(d[3]), .clk(q[2]), .ld(ld));
    modified_d_flip_flop m_dff5 (.q(q[4]), .q_bar(q_bar[4]), .d1(q_bar[4]), .d2(d[4]), .clk(q[3]), .ld(ld));
    modified_d_flip_flop m_dff6 (.q(q[5]), .q_bar(q_bar[5]), .d1(q_bar[5]), .d2(d[5]), .clk(q[4]), .ld(ld));
    modified_d_flip_flop m_dff7 (.q(q[6]), .q_bar(q_bar[6]), .d1(q_bar[6]), .d2(d[6]), .clk(q[5]), .ld(ld));
     modified_d_flip_flop m_dff8 (.q(q[7]), .q_bar(q_bar[7]), .d1(q_bar[7]), .d2(d[7]), .clk(q[6]), .ld(ld));
    endmodule

Down counter Test Bench

 module down_counter_tb;

    reg [7:0] d;
    reg clk;
    reg ld;

    wire [7:0] q;
    wire [7:0] q_bar;

    down_counter uut (
        .d(d), 
        .clk(clk),
        .ld(ld),
        .q(q), 
        .q_bar(q_bar)
    );
        always #5 clk = ~clk;
    initial begin
        clk = 1;
        ld = 1;
        d = 8'b00000111;
        end
    initial begin
        #20 ld = 0;
        #20 ld = 1;
        #30 ld = 0;
     end
     endmodule

Issue: If initial input i.e. d2=8'b11111111, then i am getting the downcounter it works properly for the above code, But if i give some thing like d2=8'10010011, then counter starts from 011, 010, 001 and 111, 110, 101, ........ it counts only the number of high bits from lsb + 1, if 0 is encountered next values till msb becomes x.

enter image description here

enter image description here

enter image description here

ld function too is not working as expected, when ld=0 instead of reset counter to initial input, it stops counter and starts it once ld=0. Help is appreciated! Thanks!

mardi 24 janvier 2023

Positioning content components on a home page pattern

I want to find a way to be able to change my home page sections on my react-native mobile using a back-office/api.

My home page has several different sections: banner, carousel, products, users. And I want to be able to re-order then and change for example the banner.

My first guess is to store the placement in my database, fetch it and parse it to place the elements according what I set as data in my database.

But I wanted to know if someone knows a pattern to do it ?

lundi 23 janvier 2023

HTML input pattern doesn'n work correctly

I have a form

<form method="POST">
    <p><label for="id_product_phone">Phone number:</label>
        <input type="text" pattern="\+?[0-9\s\-\(\)]+" title="Invalid phone number" name="product_phone" maxlength="20" required="" id="id_product_phone"></p>
    <p><label for="id_product_productname">Product name:</label>
        <input type="text" pattern="[A-Za-z]" name="product_productname" maxlength="100" required="" id="id_product_productname"></p>
    <p><label for="id_product_description">Description:</label>
        <input type="text" name="product_description" maxlength="500" id="id_product_description"></p>
    <p><label for="id_product_media">Picture:</label>
        <input type="file" name="product_media" required="" id="id_product_media"></p>
    <button type="submit">Надіслати</button>
</form>

and when i try to submit it's all, second input say it's not correct data in this field, but i write only letters what i set. Why it doesn't work? Can someone check and they me, please

I use Firefox.

Java: How to add two generics of java.lang.Number in a function and design pattern of Matrix in Java?

I am implementing a Matrix class from scratch with Java language and I am quite new to java. Right now I have an interface of Matrix like this:

public interface Matrix <T extends Number & Comparable<? super T>,L extends List<T>,M extends Matrix>{
    // ... a bunch of methods ...
    public M add(M matrix) throws MatrixException;
    public M mul(M matrix) throws MatrixException;
}

The MatrixException here is an Exception defined by me and List here is also an List class implemented by myself. I also have a DenseMatrix class which extends interface Matrix:

public class DenseMatrix<T extends Number & Comparable<? super T>, L extends List<T>> implements Matrix<T, L, DenseMatrix<T, L>> {
    // ... a bunch of methods ...
    public DenseMatrix<T, L> add(DenseMatrix<T, L> matrix) throws DataStructureException {
    // add two matrix element-wisely
    }
}

But the fact I found is I can't just add two Number together and there's no overload of operator +.

So I have seen solutions like check if the class type of an element in matrix is an instanceof Integer or Double or Long or Float and I have also seen solutions like giving up on using generics but implement methods with respect to all types of Number. But from my perspective neither of these solutions are decent enough like what I can do in C++.

Thus my question is how can I resolve this issue decently? or maybe my design paradigm is completely wrong? If there's a better design, please tell me! Many thanks in advance!

Database write and read best practices ? (Java/Scala and Spanner DB)

Wondering if there's an industry standard/best practice for a situation like this - I have a method that takes in some information about a row (modeled as a case class) that has the same params as the database table. Basically, I have a method that creates an object of the class that has all the fields required to populate the db row and then once it's written to the db, I want to use the same row to do more operations. The flow looks like this:

val databaseRow = row // case class object with stuff to write to db

writeRowToDatabase(databaseRow).map {
  case Ok(_) =>
       // Row written to the database
       // Question - Should I refetch from db or safe to assume its writte to db and just use the databaseRow variable for further operations?
       // Log to different table - id of row
       logToDatabase(databaseRow.id) // can i use this `id` or should this be fetched from db?
       .
       .
       .

  case Err(err) =>
       sys.error("failed to write to db")
}

So, wondering if this is acceptable and fault tolerant? If not, what's the best practice? I could insert that row in the db and subsequently refecth it again OR just use the context object databaseRow and take the id from there to do further operations(assuming the write will succeed since I got Ok(_). This will save a call to the db. But would there be a case when I receive Ok(_) from writeToDatabase method but its not actually written to the db?? In that case, I'm logging something downstream that's not really inserted first in the db. How do folks deal with situations like this? Appreciate any pointers. Thanks

Control child's layout from parent in Vue

is there an idiom in Vue ( let's say Vue2) to control child's layout?

The child is supposed to provide a logically coupled 'template elements' (e.g. el-1, el-2) and I/parent consumer want to pick how to arrange layout. I may want them to be displayed in column or maybe the second one should be a tooltip for the first one on another occasion.

I know that I can use scoped slots to access child's information but el-1 and el2 are complex enough that I would prefer not to recreate them but do something along those lines:

// NOT a valid VUE syntax

// parent 
<template>
  [...]
  <TheChild>
    <div>
      <el-1-provided-by-the-child-somehow/>
      <q-tooltip> 
        <el-2-provided-by-the-child-somehow/>
      </q-tooltip>
    </div>
  </TheChild>
  [...]
</template>

// child
<template>
  <slot>
      // I know this is a place for a default content but just for illustration,
      // let's say this is a way to 'emit' two templates to the parent:
      <....> // here is a non trivial template for el-1
      <....> // here is a non trivial template for el-2
  </slot>
</template>

I failed to find a solution, maybe because of my inability to phrase the question precisely. What I currently do always contains code duplication to some extent and is not acceptable in general.

I saw e.g. https://stackoverflow.com/a/42701426/4251542 but I need to be a whole piece of template defined in a child. So having access to child's state is not enough.

Now that I wrote this I came with an ugly idea, TheChild logic can be packaged as a mixin that additionally provides everything needed by el-*s. Then el-1 and el-2 are defined as separate components but heavily depend on inject. With provide/inject the parent wouldn't have to care about passing relevant props to el-*s. But that's ugly because it is obscure, el-* should rather take props and be nice presentational components, mixin names can collide with the consumer logic.

Did I miss something basic, the really feels like something that should be easy to do. But maybe I approach it from a wrong angle.

dimanche 22 janvier 2023

Pyinstaller exe not working on target machine but works in source machine. ImportError of lazylinker(theano)

I am working on RHEL-9.1 with python version 3.7.9 installed. After converting my python source to exe using pyinstaller, My executable works fine in the same machine but it fails with the import error of lazylinker when executed the exe file in non-python installed RHEL-9.1 environment.

Versions :

Python-3.7.9 PyInstaller-3.6

Below is the Detailed Error:

You can find the C code in this temporary file:

`/tmp/theano_compilation_error_208c3d4e
library python3.7m is not found.
Check if package python-dev 3.7 or python-devel 3.7 is installed.
Stop Application Exception
Traceback (most recent call last):
  File "theano/gof/lazylinker_c.py", line 128, in <module>
ImportError: Version check of the existing lazylinker compiled file. Looking for version 0.211, but found None. Extra debug information: force_compile=False, _need_reload=True

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "theano/gof/lazylinker_c.py", line 182, in <module>
ImportError: Version check of the existing lazylinker compiled file. Looking for version 0.211, but found None. Extra debug information: force_compile=False, _need_reload=True

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "theano/gof/vm.py", line 674, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "/home/user/.local/lib/python3.7/site-packages/PyInstaller/loader/pyimod03_importers.py", line 623, in exec_module
  File "theano/gof/lazylinker_c.py", line 226, in <module>
  File "theano/gof/cmodule.py", line 2411, in compile_str
Exception: Compilation failed (return status=1): /usr/bin/ld: cannot find -lpython3.7m. collect2: error: ld returned 1 exit status.

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "Application.py", line 173, in stop_application
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "/home/user/.local/lib/python3.7/site-packages/PyInstaller/loader/pyimod03_importers.py", line 623, in exec_module
line 623, in exec_module
  File "keras/__init__.py", line 3, in <module>
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "/home/user/.local/lib/python3.7/site-packages/PyInstaller/loader/pyimod03_importers.py", line 623, 
  File "theano/gof/vm.py", line 683, in <module>
AttributeError: module 'theano' has no attribute 'gof'
`

Abstract Factory Mapping EF Core .NET 6

I have tremendous doubts.

I'm using Abstract Factory in my payment system:

public abstract class Payment : Entity

    {
        protected Payment(DateTime paidDate, DateTime expiredDate, decimal total, decimal totalPaid, string payer, Document document, Address address, Email email)
        {
            Number = Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10).ToUpper();
            PaidDate = paidDate;
            ExpiredDate = expiredDate;
            Total = total;
            TotalPaid = totalPaid;
            Payer = payer;
            Document = document;
            Address = address;
            Email = email;

            AddNotifications(new Contract<Payment>()
                .Requires()
                .IsLowerOrEqualsThan(0, Total, "Payment.Total", "O total não pode ser zero")
                .IsGreaterOrEqualsThan(Total, TotalPaid, "Payment.Total", "O Valor pago é menor que o valor do pagamento")
                );
        }

        public string Number { get; private set; }
        public DateTime PaidDate { get; private set; }
        public DateTime ExpiredDate { get; private set; }
        public decimal Total { get; private set; }
        public decimal TotalPaid { get; private set; }
        public string Payer { get; private set; }
        public Document Document { get; private set; }
        public Address Address { get; private set; }
        public Email Email { get; private set; }

    }
 public class CreditCardPayment : Payment
    {
        public CreditCardPayment(string cardHolderName, string cardNumber, string lastTransactionNumber, DateTime paidDate, DateTime expiredDate, decimal total, decimal totalPaid, string payer, Document document, Address address, Email email) : base(paidDate, expiredDate, total, totalPaid, payer, document, address, email)
        {
            CardHolderName = cardHolderName;
            CardNumber = cardNumber;
            LastTransactionNumber = lastTransactionNumber;
        }

        public string CardHolderName { get; private set; }
        public string CardNumber { get; private set; }
        public string LastTransactionNumber { get; private set; }
    }

My real doubt is how do I map this inside EF Core in the DbSet part

because when I try to map the class to be implemented by the abstract, it gives an error when I upload the dotnet ef migrations add

public DbSet<CreditCardPayment> creditCardPayment{ get; set; }
No suitable constructor was found for entity type 'CreditCardPayment'. The following constructors had parameters that could not be bound to properties of the entity type: cannot bind 'document', 'address', 'email' in 'CreditCardPayment(string cardHolderName, string cardNumber, string lastTransactionNumber, DateTime paidDate, DateTime expiredDate, decimal total, decimal totalPaid, string payer, Document document, Address address, Email email)'.

He brings me this would i have to do

public DbSet<Payment> Payments{ get; set; }

also?

in this case, what is the best way to implement the Abstract Factory pattern in the EF CORE

in this case, what is the best way to implement the Abstract Factory pattern in the EF CORE

JS function chaining/piping around non-objects - what is the most elegant pattern? [closed]

Let's imagine you have a number of separate functions that accept a string variable as an argument and return it with some modifications for further use. What is the most simple and elegant pattern to chain the function calls around a single variable in vanilla JavaScript you prefer and recommend to use in production?

  1. Function sandwich aka nested madness (straightforward, but not nice, poor readability):

    let str = 'random text';
    str = func4(func3(func2(func1(str))));
    
  2. Copy-paste method (simple, readable, but repetitive):

    let str = 'random text';
    str = func1(str);
    str = func2(str);
    str = func3(str);
    str = func4(str);
    
  3. Array juggling (feels goods and automated, but not super neat):

    let str = 'random text';
    [func1, func2, func3, func4].forEach((func) => {
      str = func(str);
    });
    
  4. Promisification (looks clean, but has async side-effects):

    let str = 'random text';
    str = await Promise.resolve(str)
      .then(func1)
      .then(func2)
      .then(func3)
      .then(func4);
    

Could you please suggest other fancy ways? I stick to #1, but not sure if it's good enough.

How to structure public and private methods in python

Suppose I have a class with several public methods and several _private or "helper" method.

There is the problem of how to sort them in the code. It could be 1. all public then all private or 2. the private functions after the calling public functions. (See Best practice: ordering of public/protected/private within the class definition?

An alternative approach is nesting private functions but that has a runtime overhead.

How could be the code structured in order to easily peek:

  • The interface of the class
  • The logic structure of the functions?

Decorator pattern limitations

I have a usecase where I am trying to use decorator pattern but not sure if it is the right way of using pattern. I have 2 message publisher class. First publisher takes json as input and publish message Second publisher takes bytes as input and publish message

Currently these 2 are separate classes

public class A {
    publish(Json input);
}

public class B {
    publish(byte[] input);
}

I want to decorate B with A instead of creating a separate class. Basically user would give input as Json and it would be converted to compressed bytes and published to a sink. But problem what i can think here is, while I can decorate B with A, I can't decorate A with B, reason being json can be converted to byte stream but all byte stream can't be converted to json format, and doing so would throw exception.

All decorator classes inherit same parent interface, so one can dcorate classes in any possible combination. So for decorator pattern to work properly, all of decorators must be compatible with each others irrespective of orders in which they are applied. Is this understanding correct or am I missing something in decorator pattern.

What design pattern to use for Notification Service?

I am designing a notification system for a e-commerce website. Here is the use-case:

The notification service receives a request to send notification to user and seller. The gateway queue request for notification and returns to caller to do other works. The Notification can be of two types,

  1. Email Notification
  2. Push Notification

Each of these two types have a field, Vendor(it can be Seller or User). Vendor type is used to set the priority of the notification.

The logic to consume from queue is quite clear to me. I have completed that part along with model classes for Email and Push notification.

The logic to create these notifications and pushing them to queue is confusing to me. Basically, at upper layer(Publisher), Notification can be of two types, either User or Seller. Both of these will have Email and Push notification. I can simply create two classes, one for seller and one for user and add two members, for Email and push.

Although this might work, the design seems pretty stiff to me. What if we have another requirement where we have to send both these notification to Project Manager too? What if We need to add some new Notification, like phone text. It will be hard to refactor.

Is there any way to make the publisher side flexible to changes like this? What design patterns should I use?

vendredi 20 janvier 2023

C program to create a square pattern with two triangles

So, the output should come out with a incrementing triangle of looped numbers (1,2,3,...) combined with a decrementing triangle of stars. Like this:

1********
12*******
123******
1234*****
12345****
123456***
1234567**
12345678*
123456789

So far I have this but just can't figure out how to decrement the stars.

#include <stdio.h>

int main()
{
    int i, j;
    for(i=1; i<=9; i++)
    {
        for (j=1; j<=i; j++)
        {
            printf ("%d",j);
        }

        int k;
        for(k=8; k>0; k--) {
            printf("*");
        }

        printf("\n");
    }
}

And it prints out this:

1*******
12*******
123*******
1234*******
12345*******
123456*******
1234567*******
12345678*******
123456789*******

What is this kind of interface hierarchy?

Context: The IVI Visa Specification defines a standardized interface for compliant instruments from various vendors. (oszilloscopes, multimeters,...)

From some VB code example I knew I had to do something like this in C#

var resManager = new VisaComLib.ResourceManager();
var io = new BASICFORMATTEDIOLib.FormattedIO488();

IVisaSession session = resManager.Open("some instrument id");
io.IO = (IMessage)session;
io.IO.WriteString("*IDN?");
string ident = io.IO.ReadString(100);

On the last page of the VISA specification I found this image:

enter image description here

Is this just weird design or is there something I'm missing. Is this something necessary for COM? Why would a message extend a session? Is it common practice to return some very basic interface and cast it to whatever extension you might need?

As a beginner I find it weird that a message class would also have to implement a session interface.

How do I validate a pattern set in an HTML tag thru JavaScript?

I'm very VERY new to JavaScript and I'm currently working on a challenge. I was given instructions to create a way to validate formats in a User ID field. I've tried about a thousand different methods using both Regular Expressions and functions in JS to have this User ID validation work, but nothing seems to function properly. I'm very lost and can't seem to make this work no matter the approach. I'd really appreciate if anyone could give me some advice or point out something I've been overlooking!

Here are the instructions (there are other parts to this challenge but I've chosen only the pieces of my code and instructions related to the User ID portion)

**Carefully follow the requirements below:

We prefer that you check the pattern match of the userid with javaScript rather than on the HTML input, but the HTML pattern match is ok if you can't figure out how to do it in javaScript.

Ask the user to input their first name, last name, a UserID, and a birthdate in type date format. The UserID must contain an uppercase, a lowercase, a number, and be 8 to 12 chars long.

Create a JS function to verify formats of the UserID field.

You will either need to use a For loop to iterate through your data fields character by character with JS functions like char.toUpperCase() and parsInt(char), or use Regular Expressions, to validate the UserID format.

Create an “Accept” button to execute your functions and create the following output:

If the UserID does not pass your verification, then print “Invalid UserID” to the Display window.

**And here is my code:

<!DOCTYPE html>
<html>
<body>

<h2>Type here</h2>

<div>

<label for="uid">User ID:</label><br>
<input type="text" id="uid" name="uid" pattern="(?=.*[A-Z])(?=.*[a-z])(?=.*[0-9]).{8,12}"><br>
<button type="button" onclick="validateUid()">Submit</button>

</div>

<p id="demo"></p>

<script>

function validateUid() {
let x = document.getElementById("uid").value;
if (x == "") {
    document.getElementById("demo").innerHTML = "Invalid UserID";
    return false;
}
}

</script>

</body>
</html>

This returns "Invalid UserID" when the field is left blank, but as per the instructions I need this to check the pattern I set in the HTML "uid" tag. I'm not sure how to get any kind of feedback. I've checked the Reg Ex and everything seems to be working like I want it to, but I don't know how to get a full check working. I'm sure it has something to do with the IF (x == "") portion but I genuinely have no idea what values to add. Again I'm sorry if this is a really stupid question but I'm very new and doing my best to learn on my own!

jeudi 19 janvier 2023

Can I save instance-specific functions as environment variables (and should I)?

Each instance of my app has a different policy for paying commission to sales reps. Currently I'm using environment variables such as:

// Client 1
SALES_COMMISSION_BASIS = "PERCENTAGE"
SALES_COMMISSION_PERCENT = 15%

// Client 2
SALES_COMMISSION_BASIS = "FLAT_RATE"
SALES_COMMISSION_AMOUNT = £42

I then have a function that returns the commission calculated according to the basis

const commission = (totalFee) => {
  switch (SALES_COMMISSION_BASIS) {

    case "PERCENTAGE":
      return (totalFee * SALES_COMMISSION_PERCENT)
      break;

    case "FLAT_RATE":
      return (SALES_COMMISSION_AMOUNT)
      break;

  }
} 

I could of course simplify this to always return (totalFee * SALES_COMMISSION_PERCENT + SALES_COMMISSION_AMOUNT) but this would still mean that I am including logic for percent-based commission in a flat-rate client and vice-versa, which is what I am seeking to avoid.

What I'd like to do instead is save the commission function into my environment variables.

// Client 1
SALES_COMMISSION_FUNCTION = "(totalFee) => totalFee * 0.15"

// Client 2
SALES_COMMISSION_FUNCTION = "() => 42"

While none of this is particularly language specific, it's worth noting that I'm working with an Express app in Node JS, and I'm currently using dotenv to store environment variables.

My questions are:

  1. Is saving the function to an environment the correct approach?
  2. How would I implement this in a NodeJS app?

How do you deal with a large number of EventListeners? [duplicate]

I am currently working on a comment feature. There can be many comments > 100. Each comment has several functions (Delete, Edit, Flag) that the user can click on. If I assume there are 100 comments with three 3 functions. There are 300 event listeners that I have initialised.

Problem Now I wonder if this has a negative impact on the performance of the browser? I suppose so.

Question Is there a more performance approach that can be used? A pattern that was designed for exactly such cases?

Empty upper part of the layout (near the toolbar and status bar)

I have a problem with the design layout in Android Studio, when designing the layout there, the layout looks acceptable and everything okay, but as soon as I run it forms a very nasty white area between the Status Bar and the Toolbar (although I do not use the Toolbar), and the theme which is applied (Theme.MaterialComponents.Light.NoActionBar), does not imply the presence of ActionBar. In any case, I must admit that my skills and experience in Android development is not enough to solve this problem, I would be glad for any help, thanks in advance.

I attach the code of the layout:

    <?xml version="1.0" encoding="utf-8"?>
     <androidx.constraintlayout.widget.ConstraintLayout    
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     xmlns:tools="http://schemas.android.com/tools"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     tools:context=".activities.WelcomeActivity">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/btnLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/background_intro" />

    <ImageView
        android:id="@+id/imageView2"
        android:layout_width="wrap_content"
        android:layout_height="0dp"
        android:scaleType="centerCrop"
        app:layout_constraintBottom_toBottomOf="@+id/imageView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:srcCompat="@drawable/white_line" />

    <ImageView
        android:id="@+id/imageView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintBottom_toTopOf="@+id/btnLogin"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView3"
        app:layout_constraintVertical_bias="0.285"
        app:srcCompat="@drawable/women" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="36dp"
        android:fontFamily="@font/ptsansbold"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:text="Welcome text"
        android:textAlignment="center"
        android:textColor="#FFFFFF"
        android:textSize="41sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="26dp"
        android:fontFamily="@font/ptsansregular"
        android:paddingLeft="10dp"
        android:paddingRight="10dp"
        android:text="Lorem Ipsum Text"
        android:textAlignment="center"
        android:textColor="#FFFFFF"
        android:textSize="20sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView2" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnLogin"
        style="@android:style/Widget.Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginTop="32dp"
        android:layout_marginEnd="32dp"
        android:background="@drawable/background_btn"
        android:text="Auth"
        android:textAlignment="center"
        android:textColor="#39632F"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/imageView" />

    <androidx.appcompat.widget.AppCompatButton
        android:id="@+id/btnRegister"
        style="@android:style/Widget.Button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="32dp"
        android:layout_marginTop="24dp"
        android:layout_marginEnd="32dp"
        android:background="@drawable/background_btn"
        android:text="Register"
        android:textAlignment="center"
        android:textColor="#39632F"
        android:textSize="18sp"
        android:textStyle="bold"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/btnLogin" />

</androidx.constraintlayout.widget.ConstraintLayout>

I tried to use android:fitsSystemWindows="true" but it had no effect, unfortunately I could not find any other cases with this problem, I also tried to activate Fullscreen mode.

But this also had no effect, which is needed.

mercredi 18 janvier 2023

Is it possible to implement “column based” multi-tenancy while avoiding to add the tenantId to all methods in a NestJS/TypeORM App?

Context

We are building our backend using NestJS and TypeORM (with PostgreSQL) and have determined that the optimal multi-tenant strategy for us is to utilize a shared database/shared schema with a column (companyId) identifying the "tenant" (company) on all our tables.

Current Solution

We have implemented this strategy successfully by retrieving the companyId from the request (currently from the query parameters but it will be in a JWT token once authentication is in place) and passing the companyId to all our method calls from the controller to the service and then to the repository.

For example :

The CatsController.create method takes companyId from the @Query('companyId') and passes it to our service:

@Controller('cats')
export class CatsController {
  constructor(private readonly catsService: CatsService) {}

  @Post()
  create(
    @Query('companyId') companyId: string,
    @Body() createCatDto: CreateCatDto,
  ) {
    return this.catsService.create(companyId, createCatDto);
  }
}

The CatsService.create method on our service also takes companyId as an argument to pass it to the repository :

@Injectable()
export class CatsService {
  constructor(
    @InjectRepository(Cat)
    private readonly catRepository: Repository<Cat>,
  ) {}

  create(companyId: string, createCatDto: CreateCatDto) {
    return this.catRepository.save({ ...createCatDto, companyId });
  }
}

I have created a sample project with a simplified version of our implementation to demonstrate how it can become complicated and lead to a significant amount of boilerplate code for managing companyId for all our class methods.

https://github.com/jmoyson/multi-tenant-example

Problem

While this is working, as we continue to develop more modules, it becomes apparent that this approach is not developer-friendly and it forces us to be extra cautious to ensure that every new module implements this strategy correctly to prevent any issues with data separation.

So my question is :
Is there a more efficient way to implement data separation without having to pass the companyId to all method calls, while still using the column-based tenant strategy we have decided to implement?

ps: If possible, we want to avoid the use of Request Scoped controllers/services as all our requests will need to implement the solution and we do not want to negatively impact performance.

Which Design Pattern suitable for a React Web App

Want to know how to architect a reactjs based web application solution. What patterns are popular in reactjs How to make estimation of workforce, hardware, time etc Is possible to get sample technical documentation and project roadmaps. Kindly, help me on the above issues.

Expecting some documents, links where I can get answer

Circular reference using dependency inversion issue

I have a circular reference issue using this pattern approach. TypeError: Class extends value undefined is not a constructor or null .

The strange thing is, if I move the field.type.ts in src/constants.ts, it doesn't throw an error and it works as expected, but crashes on the Unit Tests. If it leave the fied.type.ts contents in it's own file, it crashes.

Maybe I am not using/understanding this dependency inversion pattern the right way. I could probably fixed by passing the FieldTypeToClassMapping as a parameter in Field.create(options: FieldOptions, fieldTypeMapping: FieldTypeToClassMapping), but I want to understand why this is happening.

export const FieldTypeToClassMapping = {
  //Constructor of eg. StringField class so I can use `new FieldTypeToClassMapping[options.type](options)`;
  [FieldTypeEnum.STRING]: StringField,
  [FieldTypeEnum.INTEGER]: IntegerField,
};
//field/field.ts
export abstract class Field {
  value: any;
  type: string;

  errors: string[] = [];

  public constructor(options: FieldOptions) {
    this.value = options.value;
    this.type = options.type;
  }

  public static create(options: FieldOptions): any {
    try {
      return new FieldTypeToClassMapping[options.type](options);
    } catch (e) {
      throw new Error(`Invalid field type: ${options.type}`);
    }
  }
}
//field/integer.field.ts
export class IntegerField extends Field {
  constructor(options: FieldOptions) {
    super(options);
  }
  protected validateValueDataType() {
    this.validateDataType(this.value, "value");
  }

  protected validateDefaultDataType() {
    this.validateDataType(this.defaultValue, "defaultValue");
  }
}
//field/service.ts
payload const postFields = [
  {
    type: "string", //FieldTypeEnum.STRING,
    value: 'a name'
  },
];

const postFields = [
  {
    type: "string",
    value: "John",
  },
  {
    type: "integer",
    value: 32,
  },
];


const fieldsArray = [];
postFields.forEach((item) => {
    const field: Field = Field.create(item);
    fieldsArray.addField(field);
  });

return fieldsArray;

mardi 17 janvier 2023

Proper way to satisfy liskov substitution principle?

How should I properly satisfy the Liskov Substitution Principle in this sample?

class User(ABC):  # App core logic
    def add_photo(self, photo: bytes, ) -> None:
        ...


class FacebookUser(User):  # API interation logic
    def add_photo(self, photo: custom_type, ) -> None:
        ... # Set of Facebook specific actions.
        super().add_photo(photo=photo.bytes, )

I know 4 solutions:

  1. Name mangling. Flaws:
    Forcing me to rename all the existing code with Parent.add_photo and probably all the rest methods.
  2. Composition. Flaws:
    2.1. Can't reflect the logical relation between the classes.
    2.2 Forcing me to implement (proxy) methods for every Parent method.
  3. if checking for the self object type inside the method. Flaws:
    3.1. Additional complexity and clumsy branches.
  4. Implement convert_photo method from custom_type to bytes type inside the FacebookUser child class. Flaws:
    4.1 I still need to place a new convert_photo method inside some kinda "event" method (set of methods) and the best name for it is add_photo.

Write a Lua program that opens a text file which contains a series of numbers line by line in a rectangular pattern. Rows and columns represent stages

Write a Lua program that opens a text file which contains a series of numbers line by line in a rectangular pattern and reads it into an appropriate data structure of your choice. The rows and columns represent stages in a process (numbered from 0) with the value 1 representing it being possible to move from one stage to another. 0 represents the case where it is not possible to move from one stage to another.

I tried using arrays, functions and tables to solve my problem and come up with an answer but it was not working

lundi 16 janvier 2023

What are the potential drawbacks of using the Facade design pattern in C?

I've been writing a compiler for some time now as a passion project. As it stands, the compiler is written fully in C++. I employ the visitor pattern for things like type checking, code generation, debug printing, etc. I've realized over time, I don't need such a complex system to represent the various AST nodes. Whenever I want to add another AST node, it requires adding tons of boilerplate code and methods to "visit" this node.

I'm playing around with the idea of rewriting the front end of the compiler largely in C where I'll still use the C++ LLVM-IR API in the back end to simplify things. I think that OOP might add some unnecessary complexities to how I'm representing AST nodes, so I'm toying with the Facade pattern in C:

typedef enum {
  AST_NUM,
  AST_EXPR
} NodeType;

typedef struct AstNumNode AstNumNode;
typedef struct AstExprNode AstExprNode;

typedef struct AstNode {
  NodeType type;
  union {
    AstNumNode* num;
    AstExprNode* expr;
  } actual;
} AstNode;

struct AstExprNode {
  AstNode* left;
  AstNode* right;
};

struct AstNumNode {
  int value;
};

Of course, I'll still have to write methods such as:

void ast_node_print(AstNode* node, int depth); // switch on node->type and select one of the below methods based on that type
void ast_num_print(AstNumNode* node, int depth);
void ast_expr_print(AstExprNode* node, int depth);

which I view as much simpler than the visitor pattern.

However, when I'm creating these nodes, it can be a bit tedious to do the following:

AstNode* numNode = malloc(sizeof(AstNode));
numNode->type = AST_NUM;
numNode->actual.num = malloc(sizeof(AstNumNode));
numNode->actual.num->value = 10;

The last drawback I can see is space. Each AstNode will take up the same amount of space, regardless of what "sub-node" it wraps, because of the union. When compiling large programs, I can see this becoming a problem.

All in all, I'm having trouble weighing the advantages and drawbacks of doing it this way, so any help and guidance is much appreciated!

Multithreaded server - design approach

I have a systemd service which acts as a server for incoming requests (API endpoint). Additionally, this service should monitor the state of the system (cpu load, ram, etc.), this is done by reading in the appropriate files in the /proc filesystem. I plan to update these values each second by spawning a dedicated thread, which will continuously read in the new values.

To my understanding a thread pool would be the wrong pattern to apply here, since these threads (probably around 4 in total) are long running (start and termination depends on the lifetime of the service). What would be a proper approach to manage these threads?

In my current implementation I have a dedicated class for each thread with some helper functions:

class Example{
  public:
    Example() {
      t = std::thread{&Example::run, this};
    }

    ~Example() {
      t.join();
    }

    void read();  // read from /proc fs
    void set();   // update values
    void get();  // access to private data member
    void run();  // thread loop, will call read and set each second
    
    std::thread t;

  private:
    int data;  // type int to keep it simple
}

The server then manually starts each thread on startup:

// constructor snippet
// these are member variables
t1 = Example1();
t2 = Example2();
t3 = Example3();
t4 = Example4();

I'm not sure if this is a proper approach to handle multiple, long running threads. Would it be better to create a dedicated class which handles all threads, so that the server would just have to manage this one object? Are there any other patterns for this kind of work?

Also the thread should be the only one updating the corresponding value, but there could be multiple reads happen at the same time, should a mutex be used during the update process?

Designs Patterns?

I'm trying to write a generic code. Here is my scenario.

class AEvent {

  public void onAEventCreate( A event){
     //do something
  }

}

class BEvent {

   public void onBEventCreate (B event) {
   //do something
   }

}

I want to have some generic class which could do the operation of method onAEventCreate and onBEventCreate on one single method. Now the problem is I cannot change the classes AEvent and BEvent . Is there a way I can listen to the two methods? or is there some kind of design pattern maybe like observer which can help me achieve this.

dimanche 15 janvier 2023

Design pattern for multiple handlers handling an object

My need:

I have an object and its to be processed in 3 stages. Depending on the object's data the handlers differ for all the three stages. Like one possible scenario will be handlerAStage1, handlerAStage2, handlerAStage3 will be executed, on the other case handlerBStage1, handlerBStage2, handlerBStage3 will be executed.

Can you suggest some best ways to implement this? Any resource will be helpful.

Is there any tool to determine a pattern from several numbers and characters sequences ie ti find out what way they were calculated?

I have several alphanumeric sequences generated by some system and want to find the pattern so I could add new ones. They consist of 11 numbers and letters. Similarly I'd like to find out how to deconstruct only numerical data like that. Is there any tool, formula or algorithm for that online?

Can anyone provide solution for this?

Can someone please help on this? Python Question on Pattern Matching

I tried patterns like, import re

match1 = re.findall('[^rgb]$',i)
match2 = re.findall('file0[1]_?',i)
match3 = re.findall('file0[2]_?',i)
match4 = re.findall('file[1-9]',i)
match5 = re.findall('file[^0-9]',i)

It works, but I don't think it is dynamic. Can someone Provide the pattern?

samedi 14 janvier 2023

What is the purpose of this Promise wrapper in producer-consumer queue?

I am reading Node.js Design Patterns and am trying to understand the following example of a producer-consumer pattern in implementing limited parallel execution (my questions in comments):

export class TaskQueuePC extends EventEmitter {
  constructor(concurrency) {
    super();
    this.taskQueue = [];
    this.consumerQueue = [];

    for (let i = 0; i < concurrency; i++) {
      this.consumer();
    }
  }

  async consumer() {
    while (true) {
      try {
        const task = await this.getNextTask();
        await task();
      } catch (err) {
        console.error(err);
      }
    }
  }

  async getNextTask() {
    return new Promise((resolve) => {
      if (this.taskQueue.length !== 0) {
        return resolve(this.taskQueue.shift());
      }

      this.consumerQueue.push(resolve);
    });
  }

  runTask(task) {
    // why are we returning a promise here?
    return new Promise((resolve, reject) => {
      // why are we wrapping our task here?
      const taskWrapper = () => {
        const taskPromise = task();
        taskPromise.then(resolve, reject);
        return taskPromise;
      };

      if (this.consumerQueue.length !== 0) {
        const consumer = this.consumerQueue.shift();
        consumer(taskWrapper);
      } else {
        this.taskQueue.push(taskWrapper);
      }
    });
  }
}
  1. In the constructor, we create queues for both tasks and consumers, and then execute the consumer method up to the concurrency limit.
  2. This pauses each consumer on const task = await getNextTask() which returns a pending promise.
  3. Because there are no tasks yet in our task queue, the resolver for the promise is pushed to the consumer queue.
  4. When a task is added with runTask, the consumer (the pending promise's resolver) is plucked off the queue and called with the task. This returns execution to the consumer method, which will run the task(), eventually looping again to await another task or sit in the queue.

What I cannot grok is the purpose of the Promise and taskWrapper in the runTask method. It seems we would have the same behavior if both the Promise and taskWrapper were omitted:

  runTask(task) {
    if (this.consumerQueue.length !== 0) {
      const consumer = this.consumerQueue.shift();
      consumer(task);
    } else {
      this.taskQueue.push(task);
    }
  }

In fact, when I execute this version I get the same results. Am I missing something?

How to avoid duplicate code while using Strategy Design Pattern?

I am new to design patterns and thinking about using Strategy design pattern for implementing code in my backend service. However, the Strategies are having duplicate code. I have the following classes:-

class StrategyA implements Strategy {
  private Helperclass1 helperclass1;
  private Helperclass2 helperclass2;
  private Daoclass dao;

  public void execute(Object obj) {
    updatedObj = helperclass1.method(obj);
    updatedObj = helperclass2.method2(updatedObj);
    updatedObj = updateObj(updatedObj);
    dao.update(updatedObj);
  }

  private Object updateObj(Object obj) {
    //update obj & return;
  }
}

class StrategyB implements Strategy {
  private Helperclass1 helperclass1;
  private Helperclass2 helperclass2;
  private Daoclass dao;

  public void execute(Object obj) {
    updatedObj = helperclass1.method(obj);
    updatedObj = helperclass2.method2(updatedObj);
    dao.update(updatedObj);
  }
}

class StrategyC implements Strategy {
  private Helperclass1 helperclass1;
  private Daoclass dao;

  public void execute(Object obj) {
    updatedObj = helperclass1.method(obj);
    dao.update(updatedObj);
  }
}

What should I do to remove duplicate code from Strategy pattern? I am considering not using the design pattern to avoid code duplication. Can anyone suggest a better design pattern for this usecase? I read about some similar situations and found that Command or Template patterns may be considered as an alternative (link:What pattern to use with a Strategy Pattern to avoid duplicate code inside Concrete Strategies?). However I am not sure how I can effectively use these patterns for my use-case.

How to split complicated ViewModel into reusable parts? Using MVVM, android jetpack compose

I have an application with MVVM pattern with jetpack compose, the code style is similar with NowInAndroid app structure. Now I faced the issue, please help with examples, that I can investigate and move further. I have complicated screen, for example this is the entity (it came from room as flow) and I should provide editing feature for the user. The entity contain data including some list. For editing this list I open a dialog above the screen, each item is a Card with text fields, etc. Also, I need this dialog to be opened from other screens of this application with the same goal to edit the same type of list.

Now, each change of each field triggers action in viewmodel like other actions that comes from other screen components.

All I did : I separated dialog Composable and each Card and use them. I united all dialog actions in one interface that my viewmodel implemented. So, now for reuse this dialog I should other viewmodel implement this actions interface, but the implementation will be almost the same! it is 12 actions now.

Now I cannot understand how to separate this implementation of actions from viewmodel.

The same question I have not only about dialog, but about any part of the screen (composable) that have complicated logic with actions and should be reusable.

Structure of code for example that I have now.

@Composable
 fun ScreenRoute(
  viewModel: ExampleEntityEditViewModel = hiltViewModel(),){
//...
val exampleDialogUIStateby viewModel.exampleDialogUIState.collectAsStateWithLifecycle()
val exampleActions: ExampleDialogActions = viewModel

if (exampleDialogUIState.visible) {
        ExampleDialog(
            uiState = exampleDialogUIState,
            actions = exampleActions,
//...
        )
    }
}

@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
@Composable
fun ExampleDialog(
    uiState: ExampleDialogUIState,
    actions: ExampleDialogActions,
    currencies: List<Currency>,
    //...
    showInfoDialog: Boolean,
    onDismiss: () -> Unit,
    modifier: Modifier = Modifier,
    messages: List<Message>,
) {
    if (uiState.visible) {
        ModalBottomSheetLayout(){
            Scaffold(
                modifier = modifier,
                topBar = {
                    CustomTopAppBar(
                        titleRes = R.string.title,
                        navigationIcon = CustomIcons.Close,
                        onNavigationClick = onDismiss,
                        actionIcon = CustomIcons.Info,
                        //...
                        onActionClick = actions::onInfoClicked,
                    )
                },
                floatingActionButton = {
                    FloatingActionButton(
                        onClick = actions::onExampleAddClicked,
                        //...
                    )
                },
            ) { innerPadding ->
                if (uiState.items.isEmpty()) {
                    EmptyScreen(
                        modifier = Modifier.padding(innerPadding),
                        messageHeader = //..,
                        messageText = //..,
                    )
                } else {
                    ExampleDialogEditContent(
                        modifier = Modifier.padding(innerPadding),
                        uiState = uiState,
                        actions = actions,
                        //...
                    )
                }
            }
            if (showInfoDialog) {
                MessageDialog(
                    //...
                )
            }
        }
    }
}

interface ExampleDialogActions {
    fun onExampleAmountChanged(exampleItem: ExampleItem, value: String)
    fun onExamplePeriodCountChanged(exampleItem: ExampleItem, value: String)
    fun onExampleTypeSelected(exampleItem: ExampleItem, value: String)
    fun onExampleSelectedClicked(id: Long)
    fun onExampleDeleteClicked(exampleItem: ExampleItem)
    fun onExampleAddClicked()
    fun onDismissExampleDialog()
    //...
    fun onInfoClicked()
    fun onDismissInfoDialog()
    fun onExampleMessageShown(errorId: Long)
    fun onCurrencySelected(currency: Currency)
}

data class ExampleDialogUIState(
    val visible: Boolean,
    val showInfoDialog: Boolean,
    val exampleItems: List<ExampleDialogUIState>,
    val currency: Currency,
) {
    companion object {
        val initialState = ExampleDialogUIState(
            visible = false,
            exampleItems = listOf(),
            showInfoDialog = false,
            currency = DefaultCurrency
        )
    }
}

@HiltViewModel
class ExampleViewModel @Inject constructor(
    private val exampleRepository: ExampleRepository,
    private val currencyRepository: CurrencyRepository,
    private val preferencesManager: DefaultPreferencesManager,
    savedStateHandle: SavedStateHandle,
) : ViewModel(), ExampleDialogActions {
    //...
    private val _exampleDialogUIState: MutableStateFlow<ExampleDialogUIState> =
        MutableStateFlow(ExampleDialogUIState.initialState)
    val exampleDialogUIState: StateFlow<ExampleDialogUIState> get() = _exampleDialogUIState
    //...
    override fun onShowExampleDialog() {
        _exampleDialogUIState.update {
            _exampleDialogUIState.value.copy(
                visible = true,
                exampleItems = _mainEntity.value.someList.map { item ->
                    ExampleItem(
                        item = item,
                        amount = item.amount.toString(),
                        amountInputIsError = false,
                        title = "",
                        //...
                    )
                },
                currency = _mainEntity.value.currency
            )
        }
    }
//...
override fun onExampleAmountChanged(exampleItem: ExampleItem, value: String) {
    _exampleDialogUIState.update {
        val exampleItems = _exampleDialogUIState.value.exampleItems
        val itemToChange = exampleItems.indexOfFirst {
            it.id == exampleItem.id
        }
        _exampleDialogUIState.value.copy(
            exampleItems = exampleItems.copy {
                this[itemToChange] = this[itemToChange].copy(
                    amount = value,
                    amountInputIsError = !validateExampleAmount(value).status,
                )
            }
        )
    }
}
}

Command design pattern when invoker and client may be on different machines

I read about the Command design pattern on Head First Design Patterns. Note that they use a remote control and household appliance as an example.

I noticed that their client and invoker code both reside on the same machine, but in their example, the remote control and various household appliances are clearly different machines.

If we want to make this example a reality, how must we implement the design pattern? Let's say: given the 2 machines are in the same local network and use the same programming language

I tried sending the inputs and the receivers as pure strings and the invoker will decide which receiver to use, but at times I have thought about pickling. Sometimes I might wanna send pure string commands from the invoker to another microcontroller, via MQTT, running C++ code.

Any advice is appreciated. This is a personal project.

vendredi 13 janvier 2023

JavaScript: Command Patterns [duplicate]

I have trouble in understanding a specific line of the command design pattern, the code goes here:

const carManager = {
  // request information
  requestInfo(model, id) {
    console.log(`The information for ${model} with ID ${id} is hahahaha`);
  },
  // purchase the car
  buyVehicle(model, id) {
    console.log(`You have successfully purchased Item ${id}, a ${model}`);
  },
  // arrange a viewing
  arrangeViewing(model, id) {
    console.log(
      `You have successfully booked a viewing of ${model} ( ${id} ) `
    );
  },
};

carManager.execute = function (name) {
  return (
    carManager[name] &&
    carManager[name].apply(carManager, [].slice.call(arguments, 1))
  );
};

carManager.execute("arrangeViewing", "Ferrari", "14523");
carManager.execute("requestInfo", "Ford Mondeo", "54323");
carManager.execute("requestInfo", "Ford Escort", "34232");
carManager.execute("buyVehicle", "Ford Escort", "34232");

What is the carManager[name] && carManager[name].apply(carManager, [].slice.call(arguments, 1)) doing exactly? Also I have understanding of call, bind and apply methods separately and I understand that a command pattern takes away the responsibility of issuing commands from anything that's executing commands, delegating the responsibilities to different objects. Thus car manager and execute are separate, I just don't get the dry run of that complex line.

What's the best practices in C# for public members that must be used for internal use only?

In a scenario similar to the one described here, I have 2 different assemblies and I need to declare some members in classes of assembly A that must be used only by my classes in assembly B (I mean, who uses a class of the assembly A must be discouraged to call/use those methods/properties/fields).

What is the best practice to declare them?

  1. Creating an interface for them (so you need to explicitly cast the class of assembly A to the interface to see them)
  2. Naming them with a particular prefix (so I can "train my user" to avoid calling/using them)
  3. Naming them with the first letter lowercase (so Intellisense will put them at the end and they will be "more hidden")

Notes:

  • Assembly A is built against .net6 (cross-platform) and assembly B is built against net6-windows (O.S. Windows specific)
  • I can't use InternalsVisibleTo because Assembly A must be obfuscated and this prevents obfuscation for internal members.

Listed below is the code for a better explanation of those cases.


assembly A

case 1

public class Workspace : IWorkspaceInternal
{
   /// <summary>
   /// Does stuff.
   /// </summary>
   public void MyRealPublicMethod() { //do something }

   /// <summary>
   /// For internal use only.
   /// </summary>
   void IWorkspaceInternal.MyMethod1() { //do something }
}

/// <summary>
/// Interfaces with methods/properties/classes for internal use only.
/// </summary>
public interface IWorkspaceInternal
{       
   /// <summary>
   /// Does stuff.
   /// </summary>
   public void MyMethod1() { //do something }
}

case 2

public class Workspace
{
   /// <summary>
   /// Does stuff.
   /// </summary>
   public void MyRealPublicMethod() { //do something }

   /// <summary>
   /// For internal use only.
   /// </summary>
   public void Foo_Method1() { //do something }
}

case 3

public class Workspace
{
   /// <summary>
   /// Does stuff.
   /// </summary>
   public void MyRealPublicMethod() { //do something }

   /// <summary>
   /// For internal use only.
   /// </summary>
   public void myInternalMethod1() { //do something }
}

Other ideas?