jeudi 30 septembre 2021

C++ : Observer Pattern

How efficiently can I write setScore() without adding it to IObserver ? Is there any better to add such method ? or any better implementation than this ? PLEASE HELP.

ObserverPattern.cpp:88:7: error: ‘class IObservable’ has no member named ‘setScore’

//interface
class IObserver
{
public:
    virtual void update(int) = 0;   
};

//interface
class IObservable
{
public:
    virtual void subscribe(IObserver *) = 0;
    virtual void unsubscribe(IObserver *) = 0;
    virtual void notifyAll() = 0;   
};


class CricketMatchScore : public IObservable
{
    
public:

    CricketMatchScore()
    :   mScore (0)
    {

    }

    void subscribe(IObserver * obj)
    {
        mObservers.push_back(obj);
    }   

    virtual void unsubscribe(IObserver * obj)
    {
        auto iter = std::find(mObservers.begin(), mObservers.end(), obj);
        if (iter != mObservers.end())
        {
            mObservers.erase(iter);
        }
    }

    void notifyAll()
    {
        for (auto & item : mObservers)
        {
            item->update(mScore);
        }
    }

    void virtual setScore(int score)
    {
        if (mScore != score)
        {
            mScore = score;
            notifyAll();
        }
    }

private:
    std::vector<IObserver*> mObservers;
    int mScore;

};


class CricInfo : public IObserver
{
public:
    void update(int score)
    {
        std::cout<<score<<std::endl;
    }
};

int main()
{
    IObserver * ob1 = new CricInfo;
    IObserver * ob2 = new CricInfo;

    IObservable * obl = new CricketMatchScore;

    obl->subscribe(ob1);
    obl->subscribe(ob2);

    obl->setScore(20);

    return 0;

}

How do I get rid of a ever growing switch-statement?

The Problem

switch (choice) {
    case 0:
        return new Class0();
    case 1:
        return new Class1();
    case 2:
        return new Class2();
    case <n - 1>:
        return new Class<n - 1>();
    default
        return new Class<n>();
}

What I Tried

Chain of responsibility design pattern. A great and amazing solution for distributing complex tasks. However, I don't want a class that checks if it can do 1 method.


Motivation

I'm tired of updating the code every time I add something. Bad design.

How to call member functions of an IMPL from an injected strategy pattern

So I have been tasked with implementing a strategy pattern on an existing code base. The code below is a very simplified version of the code that I am using for demonstration purposes. I don't have a lot of leeway to re-architect the WorldTraversal class. So the issue I am having is that I am not that familiar with the PIMPL idiom, and it adds a layer of doubt into my mind as to how to approach this.

The apply method in the strategy will need to execute two methods that are defined in the impl. But I am unsure how to gain access to them without exposing them to the public interface. I have tried using std::function, and passing the method as a parameter, but I am unsure of the syntax for binding a method on an impl (and even if this should be attempted).

Any assistance would be appreciated.

// The main class/object that will need to execute different strategies based on the situation
class WorldTraversal
{
public:
    void setStrategy(ITraversalStrategy&& strategy) { m_impl->strategy = std::move(strategy); }
    void execute()
    {
        // Apply needs access to methods in the impl but they are not static
        m_impl->traversalStrategy->apply(std::bind(&m_impl->processPath, *m_impl), std::bind(&m_impl->executePath, *m_impl)); // Can I even do this given the impl is a unique_ptr??
    }

private:
    struct Impl;
    std::unique_ptr<Impl> m_impl;
}

// The IMPL which contains (at least) two methods I would need to call
struct WorldTraversal::Impl
{
    Impl() {}

    void processPath();
    void executePath();

    std::unique_ptr<ITraversalStrategy> traversalStrategy;
}

WorldTraversal::Impl::processPath() {}
WorldTraversal::Impl::executePath() {}

// The strategy (I left the interface out for brevity)
class GroundTraversal : public ITraversalStrategy
{
public:
    using ProcessPath = std::function<void()>;
    using ExecutePath = std::function<void()>;

    virtual void apply(ProcessPath processPath, ExecutePath executePath) override
    {
        // Implementation of the actual strategy goes here
        // I need to be able to call processPath and executePath in here
        // Different strategies may need to call these differently etc.
        processPath();
        executePath();
    }
}

int main()
{
    WorldTraversal worldTraversal;

    // Could be ground, air, water etc.
    worldTraversal.setStrategy(std::make_unique<GroundTraversal>());
    worldTraversal.execute();

    return 0;
}

Clean Design | Quiz Responses Validation

Please suggest a clean design to validate a quizAttempt done on a quiz. There are multiple level of validations to be done

At Quiz Level:

  • TimeLimit Validation
  • Duplicate response validation

At Section Level:

  • TimeLimit Validation

At Question Level:

  • A non optional question not answered

  • A Prequisite question not answered

  • Invalid optionId

  • TimeLimit Validation

    QuizModel {    
        private List<QuizSection> sections;
        private Short marks;
        private Short seconds;
    }
    
     QuizSection{
         private Short marks;
         private Short seconds;
         List<Question> questions;
     }
    
     abstract Question{
         String question;
         private Short marks;
         private Short seconds;
         boolean optional;
         Question[] prerequisites;
     }
    
     MCQ extends Question{
        Options[] options
        Options[] correctAnswers
     }
    
     QuizAttempt{
         private String quizId;
         private String questionId;
         private long startTime;
         private long endTime;
         private long timeTaken;
         private List<QuestionAttempt> questionResponses;
         private UserIdentifier userIdentifiers;
         private Map<String,Object> quizForm;
     }
    

Is there a software engineering concept/pattern for "service injection"?

I'm implementing a service that needs to call another service that calculates a result in a way I cannot know.

Let's say I have the following scenario: I have some place in my code, calling a HTTP request to a defined endpoint another service returning a defined result. Now, I mustn't dictate how the result will be calculated, however I can define the result output data type I'm expecting. I want to put emphasis on this, since otherwise I would just implement the calculation logic in my service.

I would then describe it to the user:

You need to provide an HTTP service, with this exact endpoint, receiving these exact parameters, delivering this exact result type, but how you calculate the result is your job. I just need the URL of your service.

Afterwards the user of my service would configure the URL to their HTTP service into my service, so that I can make a HTTP request to {url}/defined-endpoint.

I couldn't think of another name but "service-injection" to describe this concept, since it has a resemblance to dependency injection, just that in code you don't provide an object instance, but a service that is called via http.

My question is: Is there a pattern for this concept or an alternative that more elegantly solves the general problem of outsourcing a calculation to another service?

Dependency injection pattern how to initialize variables of static class at beginning

I've been using dependency injection for about 6 months now and sometimes there is a situation I don't know how to handle in an elegant way.

Say I want a class for storing all my app settings in. This class is only initialized at beginning.

Please let me know how idea 1 can be executed (as I think this is the classic way) and if idea 2 is a valid pattern or if there is a better alternative.

Idea 1:

make this class static as its variables are only initialized and after that everything stays read-only. The problem with this is that I do not know where to initialize variables of this class. To initialize one of the variables a password needs to be decrypted which requires the use of IEncryption interface.

I would like to initialize these static variables before the main program actually start (so preferably in Startup.cs). I can't do that because I can't get the implementation of IEncryption in the DI container class, or at least I don't know an elegant way to get it. How should this be done with a static class? should I make another "middleware" between Startup and actual program logic where I can initialize static variables?

If I'm not mistaken simple data only classes that are application wide are ok to be static object even when using DI pattern

Idea 2:

Now I don't know if this has a name or if it's ever used. It's just something I came up with and it seems like a good solution for me but there might be an alternative I don't know of that makes it useless.

What if I instead of making this class static I make it as a normal class and initialize all static variables inside class constructor.

So something like this:

public ClientData(IConfiguration configuration, IEncryption encryption)
{
    var section = configuration.GetSection(nameof(ClientData));
    EdgeUrl = section.GetValue<string>(nameof(EdgeUrl));
    EdgeAuthUrl = section.GetValue<string>(nameof(EdgeAuthUrl));
    Username = section.GetValue<string>(nameof(Username));
    Password = encryption.Decrypt(section.GetValue<string>(nameof(Password)));
    OrganizationKey = section.GetValue<string>(nameof(OrganizationKey));
}

public string EdgeUrl { get; }

public string EdgeAuthUrl { get; }

public string Username { get; }

public string Password { get; }

public string OrganizationKey { get; }

I then inject IEncryption through the constructor.

mercredi 29 septembre 2021

Templated object generation in python

What is a good design pattern to implement templated object generation (not sure that's the name) in python?

By that, I mean having a function such as:

from typing import TypeVar

T = TypeVar('T')

def mk_templated_obj_factory(template: T) -> Callable[..., T]:
    """Returns a f(**kwargs) function that returns an object of type T created by a template of the same type."""

Python has templated strings. Something like `"this {is} a {template}".format' would be how one could achieve the above. If we want to get a "proper" function that has a signature (useful for a user so they know what arguments they need to provide!), we could do this:

from inspect import signature, Signature, Parameter
from operator import itemgetter
from typing import Callable

f = "hello {name} how are you {verb}?".format

def templated_string_func(template: str) -> Callable:
    """A function making templated strings. Like template.format, but with a signature"""
    f = partial(str.format, template)
    names = filter(None, map(itemgetter(1), string.Formatter().parse(template)))
    params = [Parameter(name=name, kind=Parameter.KEYWORD_ONLY) for name in names]
    f.__signature__ = Signature(params)

    return f

f = templated_string_func("hello {name} how are you {verb}?")
assert f(name='Christian', verb='doing') == 'hello Christian how are you doing?'
assert str(signature(f)) == '(*, name, verb)'

But would if we want to make dict factories? Something having this behavior:

g = templated_dict_func(template={'hello': '$name', 'how are you': {'$verb'}})
assert g(name='Christian', verb='doing') == {'hello': '$name', 'how are you': {'$verb'}

What about other types of objects?

It seems like something that would have a solid design pattern...

Architecture of subscription system?

How does work the system with user subscription. For example real estate app when user log in and creates a filter by interest. When the relative data is appeared users gets corresponding notification about it.

For example user subscribe to filter: Houses -> 100m -> 2 flats -> price less 400 000. Then user gets notification in matching case.

I wonder about this architecture approach, how does it work?

Managing sync and async functions in an algorithm call stack

TLDR: must I use async and await through a complicated call stack if most functions are not actually async? Are there alternative programming patterns?

Context

This question is probably more about design patterns and overall software architecture than a specific syntax issue. I am writing an algorithm in node.js that is fairly involved. The program flow involves an initial async call to fetch some data, and then moves on to a series of synchronous calculation steps based on the data. The calculation steps are iterative, and as they iterate, they generate results. But occasionally, if certain conditions are met by the calculations, more data will need to be fetched. Here is a simplified version in diagram form:

enter image description here

The calcStep loop runs thousands of times sychronously, pushing to the results. But occasionally it kicks back to getData, and the program must wait for more data to come in before continuing on again to the calcStep loop.

In code

A boiled-down version of the above might look like this in JS code:

let data;

async function init() {
  data = await getData();
  processData();
  calcStep1();
}

function calcStep1() {
  // do some calculations
  calcStep2();
}

function calcStep2() {
  // do more calculations
  calcStep3();
}

function calcStep3() {
  // do more calculations
  pushToResults();

  if (some_condition) {
    getData(); // <------ question is here
  }

  if (stop_condition) {
    finish();
  } else {
    calcStep1();
  }
}

Where pushToResults and finish are also simple synchronous functions. I write the calcStep functions here are separate because in the real code, they are actually class methods from classes defined based on separation of concerns.

The problem

The obvious problem arises that if some_condition is met, and I need to wait to get more data before continuing the calcStep loop, I need to use the await keyword before calling getData in calcStep3, which means calcStep3 must be called async, and we must await that as well in calcStep2, and all the way up the chain, even synchronous functions must be labeled async and awaited.

In this simplified example, it would not be so offensive to do that. But in reality, my algorithm is far more complicated, with a much deeper call stack involving many class methods, iterations, etc. Is there a better way to manage awaiting functions in this type of scenario? Other tools I can use, like generators, or event emitters? I'm open to simple solutions or paradigm shifts.

Lombok @Builder for a class in multiple level of inheritance with mandatory fields

I'd like to implement Builder pattern for a class in deeper level of inheritance where some fields are mandatory (message, cause) and some optional (myOptField1, myOptField2...) by using Lombok @Builder and assuming that the parent class cannot be changed. So I've implemented my own builder() like this:

@Builder(toBuilder = true)
@Getter
public class MyException extends Exception {

    private int    myOptField1;
    private String myOptField2;

    public static MyExceptionBuilder builder(String message, Throwable cause) {
        return new MyException(message, cause).toBuilder();
    }

    public MyException(String message, Throwable cause) {
        super(message, cause);
    }
}

Then using of this class can be this way:

MyException
    .builder("Mandatory message", new SpecificException("specificCause"))
    .myOptField2("value")
    .build();

In IntelliJ Idea, everything seems to be fine but I get compilation error:

java: constructor MyException in class com.myproject.MyException cannot be applied to given types;
required: java.lang.String,java.lang.Throwable
found: int,java.lang.String
reason: actual and formal argument lists differ in length

So compiler can see only constructor generated by Lombok @Builder (=@AllArgsConstructor) and cannot see my constructor with parameters java.lang.String,java.lang.Throwable. Is there any better way how to solve this?

Scala Case Class Inheritance for common vals

I am having case class that has few vals which are used only for 1 conditions.

case class ExampleCase(name:String, age:Int , abc:Int , abc1:Int )

Here abc is used or assigned only for 1 scenario and for other scenario we use only abc1

Wanted to create a trait so that we have mandatory vals in trait and then extend that trait with 2 case class and 1 having abc and one more having abc1.

Please suggest me best approach for this.

Spring Interface Driven Controllers best practices

I used to write @RestControllers without interface, but suddenly saw article https://www.baeldung.com/spring-interface-driven-controllers, describing such pattern Interface Driven Controllers. So the question is: is there best practice to create controllers without implementing interface or with special interface per controller with annotated methods, for example @GetMapping, @RequestBody, @PathVariable etc. and implement it?

mardi 28 septembre 2021

Is local secret store best practice for sensitive data?

I am using Azure App Configuration on a team project and am wondering what would be the best way to store the connection string, so that it is protected, yet not every developer would have to install it to his local secret store?

For production I am thinking of storing it in an env variable which the application will be getting (it's an Azure Web App).

What would be the best practice to store the conn string for development and is storing it in an env var in prod good practice?

Do I need to return an object of all the concrete classes implementing an interface if I am using Factory Pattern in Java

While reviewing the code for one of my colleagues, I pointed out some code structuring improvements and how we should use Factory Design Pattern for our use-case but I have not been able to convince him so I am seeking help from the almighty community here whose opinion no developer would neglect :)

The code is structured similar to the below -

abstract class X {
    abstract y();
}

class a extends X {
    y();
}

class b extends X {
    y(){
       factory().y();
    }
}

class factory(){
    determineClass(input){
        if(input == 'a')
           return new a();
        else return null;
    }

}

I have two questions -

  1. Given that both class a, b extend class x and we are using factory class to determine which object to create, should it not ideally have an extra condition for when input == 'b' and we return new b() ?
  2. I don't think class b should extend x because it seems as if we are using this to determine which object to create and call method y() on that class. I think this should be a high level class which calls factory and not an extension of X

Best way to execute instruction and set variables before any method call in Python class

I need to set a number of environment variables and class properties before any other command is executed like for example:

def __init__(self):
  os.environ["HOST"] = os.uname()[1]
  self._home = os.environ["HOME"]
  self._storage = f'{self._home}/my-storage'
  self._service_names = None
  self._requirements_file = None

I also need to read some files and set some more variables.

I thought to include them in the "init" function but I am thinking that this might make the class initialization step too slow.

Is this recommended doing file reads and other potentially time consuming operations in init? What other mechanism does Python offer to ensure that as set of instruction is executed before a class method is executed? I could put these operations in a decorator function maybe?

SwiftUI MVVM approach with vars in View

I'm building an app in SwiftUI, based on the MVVM design pattern. What I'm doing is this:

struct AddInvestment: View {
    
    @ObservedObject private var model = AddInvestmentVM()
    @State private var action: AssetAction?
    @State private var description: String = ""
    @State private var amount: String = ""
    @State private var costPerShare: String = ""
    @State private var searchText: String = ""
    @State var asset: Asset?
    
    var body: some View {
        NavigationView {
            VStack {
                Form {
                    Section("Asset") {
                        NavigationLink(model.chosenAsset?.completeName ?? "Scegli asset") {
                            AssetsSearchView()
                        }
                    }
                    Section {
                        Picker(action?.name ?? "", selection: $action) {
                            ForEach(model.assetsActions) { action in
                                Text(action.name).tag(action as? AssetAction)
                            }
                        }
                        .pickerStyle(.segmented)
                        .listRowBackground(Color.clear)
                    }
                    Section {
                        TextField("", text: $amount, prompt: Text("Unità"))
                            .keyboardType(UIKit.UIKeyboardType.decimalPad)
                        TextField("", text: $costPerShare, prompt: Text("Prezzo per unità"))
                            .keyboardType(UIKit.UIKeyboardType.decimalPad)
                    }
                }
            }
            .navigationTitle("Aggiungi Investimento")
        }
        .environmentObject(model)
        .onAppear {
            model.fetchBaseData()
        }
    }
}

Then I have my ViewModel, this:

class AddInvestmentVM: ObservableObject {
    
    private let airtableApiKey = "..."
    private let airtableBaseID = "..."
    
    private let assetsTableName = "..."
    private let assetsActionsTableName = "..."
    
    private let airtable = Airtable.init("...")
    
    private var tasks = [AnyCancellable]()
    
    @Published var chosenAsset: Asset?
    @Published var assets = [Asset]()
    @Published var assetsActions = [AssetAction]()
    
    init() { }
    
    func fetchBaseData() {
        
        print("Fetching data...")
        
        let assetActionsRequest = AirtableRequest.init(baseID: airtableBaseID, tableName: assetsActionsTableName, view: nil)
        let assetsActionsPublisher: AnyPublisher<[AssetAction], AirtableError> = airtable.fetchRecords(request: assetActionsRequest)
        
        assetsActionsPublisher
            .eraseToAnyPublisher()
            .sink { completion in
                print("** **")
                print(completion)
            } receiveValue: { assetsActions in
                print("** **")
                print(assetsActions)
                self.assetsActions = assetsActions
            }
            .store(in: &tasks)
    }
}

Now, as you can see I have some properties on the view that are binded to some text fields. Let's take these in consideration:

@State private var description: String = ""
@State private var amount: String = ""
@State private var costPerShare: String = ""
@State private var searchText: String = ""

Keeping in mind the MVVM pattern, should these properties be declared in the ViewModel and binded from there? Or is this a right approach?

Use := and = for assignment

I want to know why some programming languages use := and some use = for assignment? What are some of the logical difference between them?

lundi 27 septembre 2021

Can .NET Core Identity work with a Unit of Work Pattern?

I'm developing a .NET Core Web application (Razor Pages) with Entity Framework Core. I am implementing a Unit of Work (and generic repository) Design Pattern as I've had success with this in the past.

I would also like to use .NET Core Identity (Individual User Accounts) for authorisation/ authentication etc., but I'm wondering if .NET Core Identity might not integrate well with a Unit of Work Pattern.

Previously when using a Unit of Work and Generic Repository Pattern, I've only ever had one DbContext (Entity Framework) and this has been shared among multiple repositories within the same HTTP request.

If I retrofit .NET Core Identity into my Web Application an IdentityDbContext is created. This means I have 2 DbContexts in my application. The IdentityDbContext inherits from DbContext, so I could still use the IdentityDbContext, put my domain DbSet entities into it and then my UoW implementation would only have one DbContext. However, I would prefer to separate my domain entities from user authorisation/ authentication entities - it seems cleaner that way.

Another concern is that I think the ASP.NET Identity methods call SaveChanges() internally and when using a UoW pattern I usually only want that to happen once all the CRUD work is done.

I've researched this topic quite a bit on Stackoverflow and I feel like I am going around in circles!

Would really appreciate any guidance on whether this approach is advisable or best to avoid!

Thanks.

How can I avoid a warning in a child class due to attribute covariance?

I am trying to avoid the linter warning that is shown as a comment in the last line of the code sample.

I understand why it happens, and I know I could very well ignore because this is Python. But as a sort of self-exercise, I've been trying to think of a properly typed way to avoid it, and haven't been able to find a solution.

Here's a code sample:

class Content(ABC):
    def __init__(self, data: Dict):
        self._data: Dict = data


class AlertContent(Content):
    def __init__(self, alert: Alert):
        data: Dict = get_data_from_alert(alert)
        super().__init__(data)
        self.alert_priority: str = alert.priority


class Envelope(ABC):
    def __init__(self, content: Content):
        self._content: Content = content
    
    @property
    @abstractmethod
    def priority(self) -> str:
        raise NotImplementedError


class AlertEnvelope(Envelope):
    def __init__(self, content: AlertContent):
        super().__init__(content)

    @property
    @abstractmethod
    def priority(self) -> str:
        return self._content.alert_priority  # Warning: Unresolved attribute reference 'alert_priority' for class 'Content'

Do you have any ideas?

Brute Force Pattern Algorithm in Python

Using Python, how would you implement a brute-force string matching algorithm. The algorithm would solve the string matching problem. The string matching problem is to find a pattern (string of m characters) inside a text (a string of n characters). Verify your code with outputs from the following test cases:

Test case#1: Text: 10110100110010111 Pattern: 001011

Test case#2: Text: It is never too late to have a happy childhood Pattern: happier

Test case#3: Text: NOBODY_NOTICED_HIM

PostgresSQL updates into MongoDB

Can someone tell me if there is a better way of doing this? Currently, I have a script that is running every minute to check the Postgres database of any changes, and if there are any then we insert them into the MongoDB database. Now if this script dies then the whole setup would stop so is there a better way of doing this?

Which design pattern to use for "Changes in parent object should also change child objects"

Suppose, I have an enterprise object. User and Organization are the child objects of enterprise object (or you can say dependent on enterprise object). If the enterprise object state is changed to 'Cancelled', I want to set all dependent objects state to 'Cancelled' For this scenario, which design pattern do I have to use in JAVA

dimanche 26 septembre 2021

calling *.feature file across the karate repositories/projects [duplicate]

can we call the *.feature file from one karate project/repository into another karate project/repository? because in my organization, they want to separate out common karate things in one karate repo and use that repo in other karate projects to reduce boilerplate code.

Binary number pattern matching

/*

  • patternMatching - return the number of found 4-bit pattern p in the given 16-bit number x.
  • Examples:
  •         patternMatching(11, 11) = 1, patternMatching(245, 13) = 1,
    
  •         patternMatching(170, 15) = 0, patternMatching(23397, 11) = 3
    
  • Legal ops: ! ~ & ^ | + << >>
  • Max ops: 75
  • Rating: 4 */ How to solve this question...? Should I just iterate each bit one by one?

Is right to call Microservice a project that is just an adapter?

Let's think I have a project that manage games. In this project, I use request X for example.

But I had to create a new project to use request Y. We can think that is to be conformed with some standards of API for games manager. In this new project, I only have mapping being done. The project that uses request Y change the request to X and call the API. There is no business logic, only mapping logic. So, we can see that new project is a kind of adapter. In this new project I have a different development, deployment and team managing.

My question is: is right to call the new project of microservice? The new one is highly coupled of the core (the one that manage games) and doesn't work without it.

InvocationHandler in Kotlin

I'm reading Head First: Design Patterns (2nd ed) and I followed the code sample but instead of using Java, I used Kotlin. Currently, I'm in a chapter tackling about proxy protection pattern and having difficulty to run it with Kotlin. Please see the code and exceptions below.

Sample code

interface Person {
    fun getName(): String
    fun setName(name: String)
}

class PersonImpl : Person {
    private var _name: String = ""
    override fun getName(): String = _name
    override fun setName(name: String) {
        _name = name
    }
}
class OwnerInvocationHandler(private val person: Person) : InvocationHandler {
    override fun invoke(proxy: Any?, method: Method, args: Array<Any>?): Any? {
        try {
            val methodName = method.name
            if (methodName.isNullOrEmpty())
                return null

            if (methodName.startsWith("get")) {
//              return method.invoke(proxy, *(args ?: arrayOfNulls<Any>(0))) // << Encountered "EXCEPTION B" below
//              return method.invoke(proxy, *(args ?: emptyArray()))         // << Encountered "EXCEPTION B" below
//              return method.invoke(proxy, *args.orEmpty())                 // << Encountered "EXCEPTION B" below
                return method.invoke(proxy, args)                            // << From the code sample, encountered "EXCEPTION A" below
            } else if (methodName.startsWith("set")) {
                return method.invoke(person, args)
            }
        } catch (e: InvocationTargetException) {
            e.printStackTrace()
        }
        return null
    }
}
// main.kt
val listOfPeople = arrayListOf<Person>()

fun main(array: Array<String>) {
    initializeDatabase()

    val joe = getPersonFromDatabase("Joe Javabean") ?: return
    val ownerProxy = getOwnerProxy(joe)
    println("Name is ${ownerProxy.getName()}")

}

fun initializeDatabase() {
    val p1 = PersonImpl()
    p1.setName("Joe Javabean")
    listOfPeople.add(p1)
}

fun getOwnerProxy(person: Person): Person {
    return Proxy.newProxyInstance(
            person.javaClass.classLoader,
            person.javaClass.interfaces,
            OwnerInvocationHandler(person)
    ) as Person
}

fun getPersonFromDatabase(name: String): Person? {
    return listOfPeople.firstOrNull { p -> name.contentEquals(p.getName()) }
}

Exception

Exception A

/Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x10a5ef4e0). One of the two will be used. Which one is undefined.
Exception in thread "main" java.lang.IllegalArgumentException: wrong number of arguments
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.helloworld.app.OwnerInvocationHandler.invoke(OwnerInvocationHandler.kt:17)
    at com.sun.proxy.$Proxy0.getName(Unknown Source)
    at com.helloworld.app.MainKt.main(main.kt:12)

Exception B

objc[64094]: Class JavaLaunchHelper is implemented in both /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/bin/java (0x109e744c0) and /Library/Java/JavaVirtualMachines/jdk1.8.0_131.jdk/Contents/Home/jre/lib/libinstrument.dylib (0x109eee4e0). One of the two will be used. Which one is undefined.
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at JPLISAgent.c line: 844
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at JPLISAgent.c line: 844
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at JPLISAgent.c line: 844
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at JPLISAgent.c line: 844
java.lang.reflect.InvocationTargetExceptionjava.lang.reflect.InvocationTargetException
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.helloworld.app.OwnerInvocationHandler.invoke(OwnerInvocationHandler.kt:17)
    at com.sun.proxy.$Proxy0.getName(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.helloworld.app.OwnerInvocationHandler.invoke(OwnerInvocationHandler.kt:17)
    at com.sun.proxy.$Proxy0.getName(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.helloworld.app.OwnerInvocationHandler.invoke(OwnerInvocationHandler.kt:17)
    at com.sun.proxy.$Proxy0.getName(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.helloworld.app.OwnerInvocationHandler.invoke(OwnerInvocationHandler.kt:17)
    at com.sun.proxy.$Proxy0.getName(Unknown Source)
    at sun.reflect.GeneratedMethodAccessor1.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    ...

I found the link below but didn't solve my issue.

Kotlin: Argument Type Mismatch when passing Array as vararg parameter

Showing progress of Downloads inside Tkinter Tree View

I have created a UI which have a tree view and the neccesary components for a downloader. The UI related code is shown below.

from tkinter import Button, Label, LabelFrame, W, E, Entry, Scrollbar
from tkinter import ttk
from tkinter.ttk import Progressbar


def create_label_frame(self):
    labelframe = LabelFrame(self.root, text='SAN G DOWNLOADER', fg='white', bg="#253f59", font=("Monotype Sorts", 15))
    labelframe.grid(row=0, column=1, padx=8, pady=8, sticky='e')
    Label(labelframe, text='Download Type   :', bg="#040d57", fg="white").grid(row=1, column=1, sticky=W, pady=2,
                                                                               padx=15)
    self.download_type_field = Entry(labelframe)
    self.download_type_field.grid(row=1, column=2, sticky=W, padx=5, pady=2)
    Label(labelframe, text='ShutDown yes/no:', bg="#040d57", fg="white").grid(row=2, column=1, sticky=W, pady=2,
                                                                              padx=15)
    self.shutdown_field = Entry(labelframe)
    self.shutdown_field.grid(row=2, column=2, sticky=W, padx=5, pady=2)
    Label(labelframe, text='Download Limit  :', bg="#040d57", fg="white").grid(row=3, column=1, sticky=W, pady=2,
                                                                               padx=15)
    self.limit_field = Entry(labelframe)
    self.limit_field.grid(row=3, column=2, sticky=W, padx=5, pady=2)
    Button(labelframe, text='Add Links', command=self.on_add_links_button_clicked, bg="blue", fg="white").grid(
        row=4, column=2, sticky=E, padx=5, pady=5)
    Button(labelframe, text='   clear   ', command=self.on_clear_links_button_clicked, bg="blue", fg="white").grid(
        row=4, column=1, sticky='e', padx=15, pady=5)


def create_tree_view(self):
    self.tree = ttk.Treeview(height=10, columns=("link", "status"), style='Custom.Treeview')
    self.tree.grid(row=6, column=0, columnspan=3, ipadx=15, ipady=25, sticky='e')
    self.tree.heading('#0', text='Count', anchor='center')
    self.tree.heading("link", text='Download Link', anchor='center')
    self.tree.heading("status", text='Download status', anchor='center')
    self.tree.grid_columnconfigure(1, weight=1)
    self.tree.grid_columnconfigure(2, weight=1)
    style = ttk.Style()
    style.element_create("Custom.Treeheading.border", "from", "default")
    style.layout("Custom.Treeview.Heading", [
        ("Custom.Treeheading.cell", {'sticky': 'nswe'}),
        ("Custom.Treeheading.border", {'sticky': 'nswe', 'children': [
            ("Custom.Treeheading.padding", {'sticky': 'nswe', 'children': [
                ("Custom.Treeheading.image", {'side': 'right', 'sticky': ''}),
                ("Custom.Treeheading.text", {'sticky': 'we'})
            ]})
        ]}),
    ])
    style.configure("Custom.Treeview.Heading",
                    background="blue", foreground="white", relief="flat")
    style.map("Custom.Treeview.Heading",
              relief=[('active', 'groove'), ('pressed', 'sunken')])


def create_scrollbar(self):
    self.scrollbar = Scrollbar(orient='vertical', command=self.tree.yview, bg='blue')
    self.scrollbar.grid(row=6, column=3, rowspan=10, sticky='sn')


def create_progress_bar(self):
    self.progress_bar = Progressbar(orient='horizontal')
    self.progress_bar.grid(row=6, column=3, rowspan=10, sticky='ew')

I have a downloader which follows strategy design pattern for downloading from various media. The code corresponding to the entry point of application is shown below.

from os import path
import sys

sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))
from tkinter import Tk

from Downloader.Cateogory.torrent import *
from Downloader.Cateogory.youtube import *
from Downloader.Cateogory.fb import download_fb_videos
from Downloader.Cateogory.insta import download_insta_images
from Downloader.UI.Widgets.widget import *
from Downloader.Utils.regex import torrent_regex, youtube_regex, fb_regex, instagram_regex
from Downloader.Utils.tasks import links_copied_to_clipboard

if os.environ.get('DISPLAY', '') == '':
    print('no display found. Using :0.0')
    os.environ.__setitem__('DISPLAY', ':0.0')


class Downloader:

    def __init__(self, app_root):
        self.root = app_root
        self.create_gui()
        ttk.style = ttk.Style()
        ttk.style.configure("Treeview", font=('helvetica', 10))
        ttk.style.configure("Treeview.Heading", font=('helvetica', 12, 'bold'))
        self.show_links([], '')

    def create_gui(self):
        create_label_frame(self)
        create_tree_view(self)
        create_scrollbar(self)
        # create_progress_bar(self)

    def on_add_links_button_clicked(self):
        stream_type = self.download_type_field.get().lower()
        stream_limit = int(self.limit_field.get())
        shut = self.shutdown_field.get()
        if stream_type in ['youtube', 'utube']:
            self.download_strategy(stream_limit, shut, youtube_regex, download_youtube_videos)
        elif stream_type == 'torrent':
            self.download_strategy(stream_limit, shut, torrent_regex, download_torrents)
        elif stream_type in ['fb', 'facebook']:
            self.download_strategy(stream_limit, shut, fb_regex, download_fb_videos)
        elif stream_type in ['insta', 'instagram']:
            self.download_strategy(stream_limit, shut, instagram_regex, download_insta_images)

    def on_clear_links_button_clicked(self):
        self.show_links([], '')
        self.download_type_field.delete(0, 'end')
        self.limit_field.delete(0, 'end')
        self.shutdown_field.delete(0, 'end')

    def show_links(self, _links, status):
        items = self.tree.get_children()
        count = 0
        for item in items:
            self.tree.delete(item)
        for link in _links:
            count += 1
            self.tree.insert('', 0, text=count, values=(link, status))

    def download_strategy(self, stream_limit, shut, regex_type, download_fn):
        _links = links_copied_to_clipboard(stream_limit, regex_type)
        self.show_links(_links, 'Started')
        self.tree.update_idletasks()
        download_fn(_links, shut)
        self.show_links(_links, 'Finished')
        self.tree.update_idletasks()


if __name__ == '__main__':
    root = Tk()
    root.protocol("WM_DELETE_WINDOW", root.quit)
    root.title('Downloader')
    root.config(bg='sky blue')
    root.geometry("650x450")
    root.resizable(width=False, height=False)
    application = Downloader(root)
    root.mainloop()

PROBLEM

I have defined a progress function for each strategies and the progress I was able to display in the terminal. But the Approach corresponding to updating the progress in the tree view currently was to show the download status after the process finished only. The dynamic update of tree view for the download progress is seemingly impossible.

QUESTION?

Is this design pattern proper to display download progress inside Tree View for a tkinter based application?

Catch text using a regex with specific rules

Ok, I'm trying to catch text using a regex with the following rules:

  • Each new line starts with the word type or tag, and : comes after that. | type or tag should be the capture group 1
  • A varchar might come after : | That varchar should be the capture group 2
  • \\ comes after that
  • A number comes after \\ | That number should be the capture group 3
  • ? might come after the number
  • If we have ?, a varchar might come after ? | That varchar should be the capture group 4
  • If we have ? + a varchar, then : might come after that
  • If we have ?+ a varchar + :, then a varchar might come after that | That varchar should be the capture group 5

Examples:

type:test\\1?value12:value9        // Should get: Group 1 = type, Group 2 = test, Group 3 = 1, Group 4 = value12, Group 5 = value9

type:\\22?value62:value3        // Should get: Group 1 = type, Group 2 = NULL, Group 3 = 22, Group 4 = value62, Group 5 = value3

My regex is:

/(type|tag):([^\\]+)?\\\\([0-9]{1,3})?\??([^\:]+):([^\:]+)?/i

I believe that it's not accurate. It can be written to be better and more strict, for example:

type:\\1p?hello:iii

The current regex matches p?hello as Group 4, however, it should capture group 4 as hello

Anyone can help please? Thanks!

What design pattern does tailwind use?

I have little experience of programming and just want to find out which design patterns are based on the frameworks I use. For one thing, I use Vue.js, I know that Vue uses the "Model View ViewModel" design pattern, but I don't know which design pattern Tailwind uses. Is there a design pattern for Tailwind at all? If so, which? And if not, why not?

Thank you :)

Public static readonly vs passing a reference

For a school project I have to design a system using UML, only I have ran into a problem.

Let's say that I have to design a (somewhat overcomplicated) vending machine. It has a class with the Creator pattern that makes controllers: VendingMachine. This class makes a SaleController object for every sale. The machine supports different kinds of payments, so the SaleController creates a Payment object. The job of this class is to request a payment with the CoinMachine or CardReader classes, based on a user input. However, it obviously needs a reference to the CardReader and CoinMachine objects, which are created by the the VendingMachine class.

Would it be better to create a public static readonly object reference in the VendingMachine? Or to pass an object reference to SaleController and then pass it on to Payment?

Thanks!

samedi 25 septembre 2021

When using the CQRS pattern, should the Handler class be responsible for calling the DTO-to-Domain mapper?

I have DTO called FooDTO that is sent to or from the FooController. I also have a mapper class that maps FooDTO to my domain entity Foo. To keep my controllers slim, I am using the Mediatr to implement CQRS. Should the Handler for Foo be responsible for calling the mapping function? Or should this happen elsewhere such as a layer in the pipeline before it?

How to unselect a components of same type in a parent component when other component is clicked - Vue. options api PATTERN?

Bassicaly, I would like to know your way, how would you approach unselecting all previously selected components(bind css selectedClass to class element property ).

My solution: childComponent aka product-tab deals with changing its own class @clik binding data and passing event to parent with clicked tab.

          ParentComponent - $refs all child components, than foreach loop , than change data like this ..this.$refs.tab1.selectedClass = "";

I am a begginer in Vue so please any help wit many possible solutions to this and similar problems.

How to fix the error with FormGridControl?

I got this error, but I have already added all the necessary fields and datasources to them. I have no idea why it says that GridControl is empty.

Severity Code Description Project File Line Suppression State Error Path: [AxForm/JournProductUpdate/Design/Controls/MainTab/HeaderTableFields/FormGridControl1/DefaultAction]:Property 'DefaultAction' on control AxForm/JournProductUpdate/Design/Controls/MainTab/HeaderTableFields/FormGridControl1 cannot be empty per pattern 'Details Transaction'.

Pattern guidance serialised DTO and Generics

I am looking for some pointer into best pattern regarding the following objective.

I have multiple services that I would like to send Jobs but will contain meta data that will form separate object DataObject. I am thinking the following

public enum JobType
{
    Job1 = 0,
    Job2 = 1,
    Job3 = 2
}

public class BaseJob
{
    /// <summary>
    /// Unique id maybe a guid
    /// </summary>
    public string Id { get; set; }
}


public interface IJob<T>
{
    /// <summary>
    /// Enumeration of a type of job 
    /// </summary>
    JobType Job { get; set; }

    /// <summary>
    /// Serialized object JsonConvert.SerializeObject(data);
    /// </summary>
    string DataObject { get; set; }
    
    /// <summary>
    /// DeSerialized object of Type T;
    /// </summary>
    T Object { get; }

    /// <summary>
    /// Unique id maybe a guid
    /// </summary>
    string Id { get; set; }

    /// <summary>
    /// Create the job object natively
    /// </summary>
    /// <param name="data"></param>
    void SetJobInfo(T data);
}

public class Job<T>: BaseJob, IJob<T>
{
    /// <inheritdoc/>
    public JobType Job { get; set; }

    /// <inheritdoc/>
    public string DataObject { get; set; }

    [JsonIgnore]
    public T Object => JsonConvert.DeserializeObject<T>(DataObject);

    /// <inheritdoc/>
    public void SetJobInfo(T data)
    {
        DataObject = JsonConvert.SerializeObject(data);
    }
}

I can use Factory method to create relevant Jobs from one micro-service, but how would I check what the type is from another service. I am trying to not have logic in multiple places if possible.

What is the best way to define T in the Job type for when I deserialise the DataObject from the Job DTO?

public void GetJob(IJob<dynamic> job)
{
    switch (job.Job)
    {
       case JobType.Job1:
           // How do I get the T of the object
           var object1 = job.Object;

           // I would like to use T to do something..

           break;
        case JobType.Job2:
           break;
       case JobType.Job3:
           break;
       default:
           throw new ArgumentOutOfRangeException(nameof(job), job, null);
     }
}

Thanks

vendredi 24 septembre 2021

Concrete example of RAML 1.0 Example DataType

I didn't found any suitable example where Example is being used as DataType properly inside main RAML file. Mostly it's being used as .json/.xml file. Is there any proper detail or reference where I could find that. Using AnyPoint Platform design center to build RAML.

Is it okay to throw different exceptions for the exact same problem if it occurs in a different context?

I have a simple problem in my project (C# based Windows Service) which I just cannot wrap my head around.

In several classes of my application I need to load an interval (time span), from the application configuration. In the configuration file this timespan is stored as a string, such as "1d8h". Obviously, the application needs to parse this string before it can use the time span. In one case, I am passing this string as an argument to a constructor while initializing several objects which all have their own time span. In the constructor I am then parsing this string and throwing an ArgumentException if the parsing fails for whatever reason.

Somewhere else in my application I need to do the exact same thing, but this time in a static constructor which is not allowed to have any arguments. In this case, I am throwing a System.Configuration.ConfigurationErrorsException because I am not working with any arguments so throwing an ArgumentException would not be correct in this case.

Is it perfectly fine to throw different exceptions in both cases, despite them being caused by the exact same operation? If not, what should I do instead?

Multi-select pill overflow according to width instead of count

We're trying to implement pills into our multi-select box and once it overflows the box, have it show '...X more'.

Currently we're looking to use Ant Design's multi-selection box.

Sandbox here

What Ant Design's multi-selection does is allow you to determine the count before it shows the '...X more' text. However this requires huge flexibility on design and coding because we would have to set a value for each instance depending on space available.

So to combat this, we're looking to implement one that shows '...X more' if the next pill will overflow the container.

Thoughts on if this is even possible?

Best practices for passing 'this' to class with smart pointers [closed]

I have a file in a certain format, which represents a file system. In addition, I have a class called 'FS', which parsing the above file, and builds an array of files. It looks like this:

class File
{
    friend FS;

private:
    FS * fs;

public:
    File(FS *fs) : fs(fs) {
        ...
    }
    
    void readFile() {
        fs->readSector(...);
    }
}

class FS
{
    private:
        std::vector<File> files;
    
        int readSector(...) {
            ...
        }
    
        void parse() {
            for (...) {
                readSector(...);
            }
        }
        
    public:
        File getFileByName(...) {
            return File(this);
        }
}
  1. What's the best way to pass 'this' to the 'File' class?
  2. Should I use smart pointers? If so, how should I use them in this case? If I did use them, what would happen if I make an instance of 'FS' with a 'new' operator but inside I would use with smart pointers for 'this'?
  3. Is the use of 'friend' right here?

Best Library or Object Oriented Design Pattern to Describe Dataflow Dependency in Python

Writing codes on python3. Basically, the project involves generating some json files based on some input json files and taking them through multiple processing steps (which I have implemented as separate functions). Algorithmically speaking, nothing complicated.

For example, there will be one module to load input in the form of pandas dataframes and some nested dictionaries. Then some function will do stage1 processing based on the loaded input. Another function will do stage2 processing based on stage1 output. Then stage3 processing will use the output of stage2 as well as the loaded inputs.

Essentially, the computation diagram will look like a directed acyclic graph where each node is a function (which I already wrote), having one starting point and one endpoint.

My question is what kind of object oriented design pattern or readymade libraries best capture this kind of flow pattern? Without such a design, I have to code the whole thing as

processed_input=input_reader(source_json)
intermediate_op1=stage1(processed_input)
intermediate_op2=stage2(intermediate_op1)
intermediate_op3=stage3(intermediate_op2, processed_input)
...
# and so on

My intention is to describe the graph as an object and the raw input. Then the object will execute to calculate the final output from the input source file names. Probably I can code a class which will execute the functions in sequence, but to initiate the class, I would have to supply the above code nonetheless.

Kindly let me know if the question and my intention is not too clear, I will try to rephrase it.

jeudi 23 septembre 2021

Adding a new implementation without having to touch an existing code - how?

There're 2 entities in a Go program: country states and years. A program calculates some data by receiving input from a user. The list of country states is constant, whereas years, as the time goes on, of course not.

I want to structure my program in such a way that it'll be flexible from the point of view of adding new year without changing the existing code. How would I do it? I need an architecture pattern for such a case, that is.

I want to avoid something like this:

func CalculateData(cs, year) -> ReturnDataStructure {
    if year == 2000 {
        return calculateDataFor2000(cs)
    } else if year == 2001 {
        return calculateDataFor2001(cs)
    } else if year == 2002 {
        return calculateDataFor2002(cs)
    } else //and so on


    // as years go by, add a new year...
    } else if year == 2052 {
        return calculateDataFor2052(cs)
    }

    //....
}

Instead I want to be able to add only: I'd add an implementation, perhaps in a separate file, without having to touch the existing code, as the years go by. That is, the function CalculateData(...) should become this flexible for it work properly and it shouldn't know how many years there are. The years must not be hard-coded.

How would one do it?

What is a good approach to identifying a pattern and a way to solve it?

(Without machine learning)

So I have a game that I am creating a bot for. It is essentially a matching-tile game, but much simpler. There are several different colors you can score with, each with their own score values (e.g. orange=1, pink=2, etc) You can score a specific color if it meets 2 conditions: 1. it has to have at least 4 of the same color adjacent to it. & 2. It has to lie within a "score" slot, of which there are 6 on the left and right of the "board" respectively. Every time you score, it removes those slots and a few new, randomly selected slots are added to the board. You can either score, or swap slots. Swapping two slots adds a few new colors to the board as well.

So basically I'm trying to design an algorithm that plays this game very well, but I'm not sure how to approach it. My initial thought is to have a model that analyzes the existing board's state and ranks it. Then consider every available option, and rank its potential result, and then choose the option with the highest rank. In practice though, this doesn't hold up very well. I am not sure how to determine an appropriate rank for an existing board. What should be prioritized the most?

Anyway, this might be a rather broad question, but I was wondering if anyone had any design ideas for the concept.

What to do when all methods start with the same condition

In a class, all my methods start with the same if

if (locked)
    return;

Is there a design pattern to use in these situations? There has to be a better way than write the same 2 lines in like 8 methods.

Why aren't my grid items aligned to the center?

I created this navbar and aligned it using the grid system. But the contents of the navigation grid overflow out side the navbar for some reason and below and towards the right of where they should be. I removed any margin and padding I could find but to no awail. The position of the navbar is fixed and the inside contents are not but that should not have been an issue considering that they are items within the same grid. Below is the code:

:root{
    --main-color:#ffc40c;
    --secondary-color:lightyellow;
    --main-red:#d9001d;
    --secondary-red:#ff033e;
    --dark-color:#444;
    --light-color:#fafafa
}
body{
    font-family:"Source Code Pro",monospace;
    background-color:var(--light-color);
    color:var(--dark-color);
    margin-top:50px;
    margin-left:0;
    margin-right:0;
    margin-bottom:0;
    text-shadow:1px 1px 5px var(--light-color)
}
form{
    width:100vw;
    padding:1em
}
a{
    text-decoration:none
}
input{
    border:1px solid var(--main-color);
    margin:.75em;
    border-radius:.75em;
    padding:.75em 1em
}
.navbar{
    background-color:var(--main-color);
    position:fixed;
    display:grid;
    align-items:center;
    grid-template-areas:"searchbar close-button";
    top:0;
    left:0;
    height:30px;
    width:100%
}
.searchbar{
    background-color:var(--secondary-color);
    opacity:50%;
    width:calc(100vw - 80px);
    border-radius:1em;
    padding:1em
}
.close-button{
    display:grid;
    place-items:center;
    height:30px;
    width:30px;
    background-color:var(--light-color);
    color:var(--main-red);
    border:2px solid var(--main-red);
    border-radius:50%;
    font-weight:700
}
.close-button:hover{
    background-color:var(--main-red);
    color:var(--light-color);
    border:2px solid var(--light-color);
    transition-duration:.4s
}
.close-button:active{
    rotate:360deg;
    transition-duration:.5s
}
<form class="navbar">
      <input
        class="searchbar"
        type="search"
        id="name"
        name="searchbar"
        placeholder="Search here..."
      />
      <a href="#!" class="close-button">
        X
      </a>
    </form>

How do I bring it to the top?

Best practices on reusing test inputs in JavaScript

I've written a fixed-point math library, which comes in two flavors: the signed and the unsigned flavor.

The tests across the two flavors have lots of inputs in common. E.g. for the avg function:

// Signed tests inputs
context("when one operand is zero and the other is not zero", function () {
  const testSets = [
    [fp("-4"), fp("0")],
    [fp("0"), fp("-4")],
    [fp("0"), fp("4")],
    [fp("4"), fp("0")],
  ];
  // ...
});


// Unsigned tests inputs
context("when one operand is zero and the other is not zero", function () {
  const testSets = [
    [fp("0"), fp("4")],
    [fp("4"), fp("0")],
  ];
  // ...
});

The values in the testSets arrays are duplicated. Links to GitHub:

The question is, how to refactor my code base such that I don't repeat myself? Is there a "best practice" for this scenario? I read about snapshot testing, though that doesn't tackle test inputs. I said that maybe I should fake the data. But I'm not sure that makes sense in my case, because the inputs for my mathematical functions are bound by a domain.

Note: I am running my tests with Mocha.

How to call in function from a dictionary while accessing those through a loop

I want to make a program which allows users to input their name and the program will print the name in bigger font or like you know the way we print patterns . So I made functions of all the alphabets which contains the codes to print those alphabets in bigger font with '*' and I stored those functions in a dictionary . So may plan is that as a user input his/her name I will access each letter by putting a for loop or a while loop and then use those letters to access the functions in the dictionary enter image description here i don't know why but this code is showing weird output like it is printing 1st letter and then showing none and then printing 2nd letter and again showing none . So what should I do to avoid this

Why can't I center my "a" element which I'm using to close a modal component?

I created an "a" element that closes a modal when clicked on by taking you to the home page. I made it look like a close button. However, I can't seem to vertically center the "X" in it. I tried enclosing it inside a "button" element but that caused other problems. Below is the code:

:root {
  --main-color: #ffc40c;
  --secondary-color: lightyellow;
  --main-red: #d9001d;
  --secondary-red: #ff033e;
  --dark-color: #444;
  --light-color: #fafafa;
}
body {
  font-family: "Source Code Pro", monospace;
  background-color: var(--light-color);
  color: var(--dark-color);
  margin-top: 50px;
  margin-left: 0;
  margin-right: 0;
  margin-bottom: 0;
  text-shadow: 1px 1px 5px var(--light-color);
}
a {
  text-decoration: none;
}
.close-button {
  height: 30px;
  width: 30px;
  background-color: var(--light-color);
  color: var(--main-red);
  margin-left: 0.5em;
  border: 2px solid var(--main-red);
  border-radius: 50%;
  font-weight: 700;
  text-align: center;
}
.close-modal {
  position: fixed;
  top: 2.8em;
  right: 1.7em;
}
<a class="close-button close-modal" href="#!"> X </a>

How do I vertically center it?

Java abstract Step Builder pattern

I am designing a java system where users can define some rules in a fluent style.

Rules have many properties, which are partly mutually exclusive. We use a builder pattern with validation for this.

To make the system easier to use, we want to introduce a StepBuilder, to guide the user to all necessary steps.

There are different types of rules, but all share some common properties.

Current System:

abstract BaseBuilder<T extends BaseBuilder<T>> {

   protected String property1;
   protected String property2;
   protected String property3;

   abstract Rule build();

   public T withProperty1(String data) { 
      this.property1 = data; 
      return this; 
   }

   public T withProperty2(String data) { 
       this.property2 = data; 
       return this; 
   }

   public T withProperty3(String data) { 
       //this should only be possible if property2 is not set or similar logic
       this.property3 = data; 
       return this; 
   }
}

//there are a few others like this e.g. SpecialBuilder1-10
class SpecialRuleBuilder extends BaseBuilder<SpecialBuilder> {

       protected String special1;
       protected String special2;

       public T withSpecial1(String data) { 
          this.special1 = data; 
          return this; 
       }

       public T withSpecial2(String data) { 
           this.special2 = data; 
           return this; 
       }

     @Override
     Rule builder() {
        return new SpecialRule(property1, property3, special1, special2, ....);
     }

     static SpecialRuleBuilder builder() {
        return new SpecialRuleBuilder();
     }
    
}

class BuilderTest() {
   
   //User can set anything, no steps are enforced at compile time
   Result result = SpecialBuilder.builder()
                        .property1("some")
                        .special2("thing")
                        .build(); 

}

How can we use a StepBuilder including a hierarchy (parent class), so the user cannot get to the same step twice. Ideally the user should not be aware of all the special builders and have the same entry point and guided steps. For example:

Result result = GeneralBuilder.builder()
                              .withBaseProperty1("asdas") <-- Step 1
                              .withBaseProperty2("asd")  <-- Step 2, Step 3 is now not visible, continue with all possible special options
                              .withSpecial1("asd") <-- no we are in the step of one concrete builder, and should not get "out" again, not even to the base methods

I know how to define the interface steps, I just dont know how to include all possible starting steps of the special builders at the end of the base steps, since the higher interface/class should probably not rely on the lower parts of the hierarchy.

Is this somehow possible?

How to get this type of design?

I am learning to make apps using flutter. I recently happen to see this design somewhere and really liked it, but I couldn't reproduce it no matter how hard I tried.

That's the design:

App bar: enter image description here

text field: enter image description here

thanks in advance!

change the value inside the address using a patern?

I am a modder and I need to change the value of the object position. I inject into the game using my dll file. I have a pattern like this 9F4FF 0 C4 A8 70 39 41 and an address like this 0x7FF6CC7DCCD. I found this address & pattern using cheat engine and x64 Debug. I need to change the value at this address using this address or pattern, how can I do this in C++?

mercredi 22 septembre 2021

java callable with multiple methods

I`m trying to implement a java callable with multiple methods and my situation is like this:

interface FsHandler {

  boolean existDirectory();
  boolean existFile(File);
  ...
}
interface FileHandler {

  void write(byte[]);
  void read(byte[]);
  ...
}

All these methods are implemented by different storage backends like local file system, aws s3, etc

While search for a way to parallelise this code, I tried to use callable but if I understood correctly, I would need to to break my interface in many small abstract classes that implements callable - one for each method and then use callable, not to mention that I would still need to find a way to add the call to the blocking queue (which is using an executor)

So, my doubts are:

  • is it possible to wrap callable on already existing/implemented methods?
  • another idea is to create an abstract class for each method that needs to implement callable and then use the strategy pattern to decide which implementation to use

e.g.:

interface WriteStrategy implements Callable<Void> {

  Void call();
  void write(byte[]);
  static WriteStrategy localFSStrategy(){...}
  static WriteStrategy S3Strategy() {...}

class FileHandler {
  private WriteStrategy strategy;

  public FileHandler(WriteStrategy strategy) {...}
  public void write(byte[]) { strategy.call(); }
}

I`m still not sure how to approach it :'(

code refactoring for data aggregation service in java

I have the following situation in my application:

  • I have a service class with 700+ lines
  • The class is responsible for data aggregation from different sources.
  • There is no real signature in the inputs, as I mentioned in the code example.
  • The service will collect the data sequentially and sometimes we should ignore some method based on specific condition.
  • Currently the code become unmaintainable since the logic is growing and become more and more complex.
  • I already have looked into pipeline and Chain of Responsibility design pattern
    • pipeline: I think it will not resolve my issue, since the output from step1 is not necessary to be an input for step2
    • Chain of Responsibility: also this pattern will not fix the issue since the input signature is different.

Could you please suggest away to refactor the code in order to make things clear and maintainable.

public class DataCollector{

    public Report collect(input1){
        Report report = new Report();
        report.setFirstPart(getFirstPart(input1));
        report.setSecondPart(getSecondPart(report.getFirstPart().getInput2()));
        report.setThirdPart(getThirdPart(input1, report.getSecondPart().getInput3()));
        report.setFourthPart(input1, report.getFirstPart().getInput2());
        if( input1 > report.getSecondPart().getInput3()){
            report.setFifthPart(report.getFirstPart().getInput2());
        }
        else{
            report.setSixthPart(input1, report.getSecondPart().getInput3(), report.getThirdPart().getInput4());
        }
        return report;
    }


    public FirstPart getFirstPart(input1){
        ...method logic(reterive from DB or call service either rest or soap)
    }

    public SecondPart getSecondPart(input2){
        ...method logic(reterive from DB or call service either rest or soap)
    }

    public ThirdPart getThirdPart(input1, input3){
        ...method logic(reterive from DB or call service either rest or soap)
    }

    public FourthPart getFourthPart(input1, input2){
        ...method logic(reterive from DB or call service either rest or soap)
    }

    public FifthPart getFifthPart(input2){
        ...method logic(reterive from DB or call service either rest or soap)
    }

    public sixthPart getSixthPart(input1, input3, input4){
        ...method logic(reterive from DB or call service either rest or soap)
    }

}

What is the best practice for ASP.NET Core MVC dependency injection?

Here's my dilemma: every controller in my ASP.NET Core MVC project "automatically" gets the IConfiguration, which can be used to get any value from my appsettings.json including my connection strings. Note that I would love to get values from my appsettings.json in almost every class.

So, I have repository classes (or DAO, whatever) that do the respective queries to the database(s), the problem is, that in order to get the connection string in this classes I need to check the IConfiguration object that the controller has, so far I've found two options:

  1. Pass the configuration as a parameter, or
  2. Put it in a static class so that every class can access it (my preferred solution)

My dilemma is this: imagine that from the controller to the repository class I need to pass through 6 more classes, so if I implement solution (1) DO I need to pass the configuration as a parameter to each class or is there another solution?

Decorator design pattern with Composite Design pattern

I understand the composite design pattern and the decorator design pattern and their uses. Can we have a case where we have to use them together? How would the class diagram for such a scenario look like?

Will we have the decorator(from Decorator design pattern), leaf nodes, and composite(from Composite design pattern) inherited from the Component? Here is what I am referring to for the decorator pattern:wiki link for decorator pattern and for composite pattern: composite wiki link

Filter columns by specific name and save as fasta.file

I have a question and I hope I can formulate it in an understandable way. I am working with R and I am trying to write a script in which I am able to filter and extract specific names together with their sequences from a DNA dataset based on the first 4 characters or their specific name and save it as a new fasta.file.

The dataset I am working with contains 7754 obs with 2 variables (name & seq).

For better understanding, here is a created smaller dataset in which I can explain each step I doing now

name <- c("B*07:02:01:01","B*07:02:01:02", "B*07:02:01:03","B*07:98", "B*07:99","B*08:01:01:01","B*08:01:01:02","B*08:01:01:03","B*15:27:01",
      "B*15:27:02","B*15:27:03")
seq <- c("AAAA","TTTT","GGGG","ATCG","AATG","ATTC","GTCT","TCTT","TAGTC","CATG","TGCA")

df3 <- data.frame(name,seq)


df4 <- separate(data = df3,col = name,into = c("name","protein","mutation_coding","mutation_noncoding"),sep = ":")

common_identifier = unique(str_sub(df4$name,0,4))

out = list()
for(element in common_identifier) {
  
  out[[element]] = df4 %>% 
    filter(grepl(element, name)) %>% 
    mutate(name=element) %>% 
    select(name,protein,mutation_coding,mutation_noncoding, seq) %>%
    write.csv(paste0("../saving path",gsub("\\*","",element),"_list.csv"), row.names = FALSE)
  
}

First of all, I am saving as csv.file which is annoying because then I have to transform the created files by hand into a fasta.file. Do you know a way to save it directly as fasta.file?

Second, in this script I`m basically splitting the name in parts to look for specific pattern (first four characters) and later I put the name back together to have the actual name back. Do you know an easier way to do this? Or is there a more elegant way of looking for the pattern "B07","B08"and "B*15" without splitting the name first?

Thank you in advance, I hope that was kind of a clear question :)

Cheers...

Saga pattern for multiple ViewModels in SwiftUI

Have you heard of the Saga pattern used in microservices? In the event that one view has several view models, as I understand, it would be possible to control the display of the view. That is, if some view model has not loaded yet, then we expect it. And Saga can help us in controlling this case.

Have you met something like this, does it make sense? Maybe someone has an example implementation. Thanks in advance!

python children to parent class communication

i have been learning javascript so far but i'm new to python, and i want to do this:

def Node():
    def __init__(self):
        pass
    def callbacks(self):
        # i want this to change the value of the Tree property a to 2, how?:w
        self.self.a = 2
class Tree():
    def __init__(self):
        self.a = 1
    def printt(self):
        b = Node()
        b.callbacks()
        print(self.a)

a = Tree()
a.printt()

could anyone help or propose a better way to do this or even explain if it's a design pattern ?

How to handle an increasing number of operations in a python class

I'm trying to improve my code design skills but not sure what to do. Currently I have a class that needs to set certain keys on init and it looks something like this:

class A:
  def __init__(self):
    try:
      key1 = some_key_finder("key1")
      key2 = some_key_finder("key2")
      key3 = some_key_finder("key3")
    except KeyError as err:
      raise SecretNotFoundError(f"...{err}")

Initially it only set one key but as the reqs changed I had to set two more keys. My question is: how to make the above code more scalable and handle an (hypothetically) increasing number of keys?

Multi state model in MVI pattern

I understand that the advantage of the MVI pattern is that it is a single-state flow. So is it really necessary to have only one state model in MVI?

My app has several activities, and the subject of data obtained for each activity is completely different. For example, activity A gets the dog's information, and activity B gets the information of a Github user. In this case, if MVI-pattern should be only one state model, the mvi state model contains all the data information of activities A and B?

mardi 21 septembre 2021

understanding python inner function .how does this works?

def prefix_factory(prefix):
    def prefix_printer(text):
        print(f"{prefix}: {text}")
    return prefix_printer

Now lets execute the below line.

# First time we are executing this
debug = prefix_factory('DEBUG') 

# Second time we are executing as
debug('Hello world')

First time we are executing this

1st execution or assignment of function to the variable debug is assigned the value "DEBUG". My understanding is this is how it has to be executed.

ideally inner function prefix_printer(text) - gets defined inside prefix_factory() 'return prefix_printer' should get an error, stating that text is not available or text is missing.

Second time we are executing as

debug('hello world ') - 2nd execution of the function reference. The question for the second execution is, I am assuming 'hello world' should be considered as a value for the prefix. and text should be blank as we don't call prefix_printer in the return statement with any value. Hence it has to be '' empty string. I am coming from c, C++ background.

My question is, it's the same piece of code 1st-time prefix is assigned, but during the 2nd execution debug('Hello world') it behaves differently. How is it possible, please clarify in detail how this works?

Need help on bask awk to update Yaml file by finding the pattern in the file

CONTEXT: I am very new to UNIX scripting and bash.

I have a .bash script that takes a .yaml and an array of VMs passed as arguments.

(e.g.)

myscript.sh my.yaml neo1 neo2 neo3 alice1 alice2 alice3

How to find the monitor_vm key pattern and file the last lime of the that monitor section and add at the last lines of that section?

Have got one sample function which identifies some pattern to give line number of that inserting line ....but it requires some changes. Please advise example

getline() {
  awk '
    BEGIN { monitor_vms="'${}'"; ln=1; fnd=0; }
      (fnd==1 && $0 ~ /^  [a-z]/) { exit }
      ($0~/^monitor_vms:/) { fnd = 1 }
      ($0 ~ /./ && $0 !~ /^#/) { ln = NR }
    END { print ln }' ${1}
}


for name in $VM_LIST; do
  line=`getline my.yaml monitor_vms`
  sed -i -e ${line}"a\- name: \"${vmname}\"\n my.yaml
done

The file my.yaml looks like the following:

----
- someotherkey: hello
  value: some_value
- someotherkey1: hello1
  value1: some_value1
- monitor_vms:
  - name:  sujana
    cnt: 5
  - name: vijaya
    cnt: 5
- static_configs:
  - location:
    datacenter: 

I would expect to produce the required my.yaml, after update:

---
- someotherkey: hello
  value: some_value
- someotherkey1: hello1
  value1: some_value1
- monitor_vms:
  - name:  sujana
    cnt: 5
  - name: vijaya
    cnt: 5
  - name: neo1
  - name: neo2
  - name: neo3
  - name: alice1
  - name: alice2
  - name: alice3
- static_configs:
  - location:
    datacenter: 

Trying to get rid of many if else with factory method

    if (ftpType == "YouTube")
    {
        var digitalServiceResponse = JsonConvert.DeserializeObject<YoutubeMetadataResponse>(metadataJson);

        var fileRequest = new AddDeliveryFileRequest
        {
            //some code
        };

        ftpDeliveryQueue.AddFile(fileRequest);
    }
    else if (ftpType == "Flashtalking")
    {
        var metadata = JsonConvert.DeserializeObject<FlashtalkingMetadataResponse>(metadataJson);

        foreach (var file in metadata.FileList)
        {
            var fileRequest = new AddDeliveryFileRequest
            {
                //some code
            };

            ftpDeliveryQueue.AddFile(fileRequest);
        }
    }
    else if (ftpType == "Innovid")
    {
        var metadata = JsonConvert.DeserializeObject<InnovidMetadataResponse>(metadataJson);

        foreach (var file in metadata.FileList)
        {
            var fileRequest = new AddDeliveryFileRequest
            {
                //some code
            };

            ftpDeliveryQueue.AddFile(fileRequest);
        }
    }
    else
    {
        var digitalServiceResponse = JsonConvert.DeserializeObject<SizmekMetadataResponse>(metadataJson);

        foreach (var file in digitalServiceResponse.Metadata.FileList)
        {
            var fileRequest = new AddDeliveryFileRequest
            {
                //some code
            };
            ftpDeliveryQueue.AddFile(fileRequest);
        }
    }

How do I get rid of these if and else if block with the help of factory method?

lundi 20 septembre 2021

Converting between classes representing the same thing in different libraries

I’m working on a project which uses many independent libraries, so they are not somehow connected at all. For example imagine having a simple physics library, and a 2D renderer. Both of those use their own implementation of a Vector2D class. I would like to use instances of the Vector2D class generated by the physics library to work with the renderer. The problem is the classes, despite representing the same thing, are incompactible, in fact they are 2 different classes not knowing anything about each other. I do know how to convert a Vector2D produced by the physics system to a Vector2D class which the renderer uses - you just need to get the values (X, Y) and create a new instance of the other class. What I’m looking for is a more sophisticated solution, ideally a design pattern which solves this while keeping the code clean. I have seen the adapter design pattern, but it’s unnecesarily too complicated and it should be a one-time conversion.

Design pattern to get rid of switch/case from enum property

I'm currently trying to refactor a method that receives a property name and set it's value:

private async Task < Enrichment > ParseEnrichmentNewDataAsync(int leadId, string property, string newValue) {
  var enrichment = await _context.EnrichmentRepository.GetByLeadIdAsync(leadId);
  if (enrichment == null) {
    enrichment = new Enrichment() {
      LeadId = leadId
    };
  }

  Enum.TryParse < PropertyType > (property, out
    var enumProperty);
  switch (enumProperty) {
  case PropertyType.Color:
    enrichment.Color = newValue;
    break;
  case PropertyType.UsedVehicleModel:
    enrichment.UsedModel = newValue;
    break;
  case PropertyType.UsedVehicleYear:
    enrichment.UsedYear = newValue;
    break;
  case PropertyType.UsedVehicleKm:
    enrichment.UsedKm = newValue;
    break;
  case PropertyType.Payment:
    enrichment.Payment = Convert.ToInt32(EnumExtension.GetEnumValueFromDescription < PaymentType > (newValue));
    break;
  case PropertyType.ScheduleDate:
    enrichment.ScheduleDate = DateTime.ParseExact(newValue, "dd/MM/yyyy", CultureInfo.InvariantCulture);
    break;
  case PropertyType.SchedulePeriod:
    enrichment.SchedulePeriod = newValue;
    break;
  case PropertyType.SchedulePhone:
    enrichment.SchedulePhone = newValue;
    break;
  case PropertyType.PurchaseType:
    enrichment.PurchaseType = newValue;
    break;
  case PropertyType.HasOptInNextJeep:
    enrichment.HasOptInNextJeep = Convert.ToBoolean(newValue);
    break;
  }

  return enrichment;
}

Using reflection would work for most of the fields, but some values need to be converted before being assigned. Is there a design pattern or a better way to improve this code?

Is There a De Facto List of Names of Software Patterns?

Is there somewhere that would count as the source of truth for agreeing on names for software design patterns?

In the print word this would have been the Gang of Four "Design Patterns" book. Things have moved on since that was written.

I'm looking for the reference that answers the question "what is the name of this pattern in code"?

What would you call this? [closed]

I'm a journalist, designer, and web developer. I read dozens (if not hundreds) of news articles a day, and in terms of UI and layout most of them with a pretty standard template: big headline at the top, a photo, followed by uniform-sized blocks of text. Maybe another photo dropped in somewhere for good measure.

But every now and then I'm treated to a fascinating experience — a full-screen experience that reacts to my touch, animated elements fly into view as I scroll down the page, images move past my eyeballs in 2D, 3D, or maybe even AR.

The result is an impactful, almost cinematic experience — something that transcends simply browing and consuming content on the internet, that harnesses the power of technology to communicate a story that makes a person feel something.

That is my drug, and I want more of it. The problem: I can't figure what to call it.

I've seen many terms being thrown around: "multimedia journalism" — "visual journalism" — "interactive storytelling" — "web interactive" — "multimedia interactive" — "web documentary" - "visual investigations" … Maybe one single term doesn't exist.

I'm interested in this niche at the intersection of technology and storytelling, and would really like to figure out wht is the most common industry term for it. So this is an informal poll of what people refer to this as, so that I can better find and engage with the conversation around it. What would you call custom-coded experience immersive used for the purpose of storytelling? Examples would include the famous "Snowfall" — or more examples like this and this and this?

–— Please comment with terms you have seen / would use yourself.

Build unify/normalize data structure from third party API

its more of design question , im reciving json data structure ( big one ) from thired party API
now i don't want to take this structure as is and popolate it to the diferent services as is becouse the thired party API may change the strucure ( but keep the data)
i want to recive it in one place in my app and build 1 data structure that my services will undestand .
what design patern should i use to this central place which recive the hired party API?
proxy ? delegator?

Seperate Database for Users

In my postgreSQL I currently have one database with user and business relevant tables. Our company is planing in future to add more categories, therefor I would like to seperate the categories into individual databases, as most of the data is quiet static once initialized. Below I am a showing an example with cars, please keep in mind that our company services differ much more as Pkw and LorryTruck and need much more extra tables within their scope.

Current State:

  • PostgreSQL:
    • CompanyDB
      • UserTable
      • PkwTable
      • ServiceTable
      • BookingTable

Future State

  • PostgreSQL:
    • UserDB
      • UserTable
    • PkwDB
      • PkwTable
      • ServiceTable
      • BookingTable
    • LorryTruckDB
      • LorryTruckTable
      • ServiceTable
      • BookingTable

My concern is if and how I could connect user relevant Data to the desired databases. In example a user can register for Pkw services and might be later on interested in LorryTruck services. The main goal is also that a user should only register once on our system.

Is this possible or could I design this better?

Please provide your opinion or experiences.

Thank you!

How to embed auxiliary Snakemake workflows into main workflow structure

The Snakemake documentation defines how to setup the directory structure of a workflow. This is useful for easier understanding and deployment using snakedeploy.

My question is how to embed auxiliary workflows, which are functionally tightly connected to the main workflow but fulfill a different goal, with this approach. We would, for example, want to do this with V-pipe, where the main workflow processes sequencing data, and auxiliary workflows would download sequencing data or run a tool benchmark.

The following approaches come to mind:

  • store all auxiliary workflows in external git repositories. This would be a clean solution (and snakedeploy could readily be used) but adds the overhead of having to maintain multiple code sources.
  • integrate the auxiliary workflows into the main workflow. This would make the main workflow more complex and is not always feasible.
  • put all auxiliary workflows into 'resources/auxiliary_workflows/'. This would allow all workflows to live in a single codebase while not unnecessarily increasing complexity of the main workflow. However, deploying the auxiliary workflows would be slightly more complicated.

Do you have a suggestion which of these approaches would be best suited for our needs, or have an entirely different approach in mind?

dimanche 19 septembre 2021

Refractor redundant code through structural design pattern

I have the following snippet of a code that checks the type compatibility between a variable assignment and the expression of a statement that emulates for-in behavior from some ANTLR grammars.

// LoopAnalyzer.java

@Override
public void exitForInLoop(ForInLoopContext ctx) {
    final String rightHandSideType = this.determineExpressionReturnType(ctx.statementExpression());
    this.verifyTypeCompatibility(ctx.start, ctx.solType().getText(), rightHandSideType);
}

This code will read and determine the statement expression return type as denoted by the determineExpressionReturnType method, then verify the type compatibility by comparing the variable declaration type with the array's primitive form on the right-hand side. More specifically, given a snippet of an example for-in statement:

for (string item in items) {
    // do something with the item
}

In that example, the type of item should match with the primitive form of items, and that items itself should be an array. Otherwise, an incompatibility error message is raised, impeding the for-in statement to enumerate over object items. The logic of the type compatibility checking that resembles such behavior is coded at the verifyTypeCompatibility method shown below:

// LoopAnalyzer.java

private void verifyTypeCompatibility(Token token, String leftHandSideType, String rightHandSideType) {
    if (rightHandSideType == null || leftHandSideType == null) {
        return;
    }

    if (!TypeUtils.isArrayType(leftHandSideType, rightHandSideType)) {
        this.addError(token, String.format("Types are not compatible, cannot check containment of %s in %s.", leftHandSideType, rightHandSideType));
    }
}

The code looks good until I realize that the type checking of the for-in statement and the type checking of a variable declaration are very much alike with only small differences. Unlike for-in statements, a variable declaration statement requires only the statement expression type equals the type assigned to the variable name.

For simplicity, the snippet of the code that checks the variable declaration statement is shown as below:

// ExpressionStatementAnalyzer.java

@Override
public void exitVariableDeclarationStatement(VariableDeclarationStatementContext ctx) {
    final String rightHandSideType = this.determineExpressionReturnType(ctx.statementExpression());
    this.verifyTypeCompatibility(ctx.start, ctx.solType().getText(), rightHandSideType);
}

private void verifyTypeCompatibility(Token token, String leftHandSideType, String rightHandSideType) {
    if (rightHandSideType == null || leftHandSideType == null) {
        return;
    }

    if (!TypeUtils.areCompatible(leftHandSideType, rightHandSideType)) {
        this.addError(token, String.format("Cannot assign a %s value to a %s variable.", rightHandSideType, leftHandSideType));
    }
}

With these small differences, how can we extract similar components to be reusable within the two classes?

Currently, I can only think of structural design patterns where we keep the determineExpressionReturnType and verifyTypeCompatibility in the ExpressionStatementAnalyzer class and let the LoopAnalyzer extends the class so that it can override the currently available implementation for both methods. However, this approach is unlikely to be the solution since analyzing loop statements has nothing to do with analyzing the statement expression (i.e., they supposedly do not inherit each other). Thus I asked the question.

Design pattern for Photoshop analog

I am designing the Photoshop analog using ImGui. I update state of application every frame, even if there is no changes. But there are some computationally expensive operations and I want to update state of application only when something is changed. However when you have several control panels and trying to check their state you get ugly code which is difficult to support. I am aware of signal-slot paradigm in Qt, but I want to implement it myself. What design patterns or approaches should I use in this situation? May be there are some examples which I can not find.

samedi 18 septembre 2021

Why someone would use a hexadecimal approach in javascript?

I apologize cause this may be a bizarre question but I'm pretty confused. Would anyone know why someone would use what I believe to be "a hexadecimal approach" to javascript? i.e.) I see someone naming variables like

_0x2f8b, _0xcb6545,_0x893751, _0x1d2177, etc

Why would anyone ever do this? Also, I see code like

'to\x20bypass\x20this\x20link' 

as well as hexadecimals for numbers such as 725392

0xb1190

So, how would anyone even get this kind of naming convention and why would they ever want to use this?

C++ program to print hollow rectangle star pattern

I would like to know where I am going wrong. I know the logic is correct. Output of code

for (i = 1; i <= rows; i++) {
    for (j = 1; j <= columns; j++) {
        if (i == 1 || i == rows || j == 1 || j == columns) {
            cout << "*";
        }
        else {
            cout << "";
        }
        
        }
        cout << endl;
    }
    

OOP: How to "know" the object's type in this game design

Let's image for a game, I have this scheme

Item is what all the game's Item based off

Some Item like Sword implements IEquipable

Some Item like Potion implements IConsumable

When I am giving out a quest reward, I add an Item to the character. When I am listing out the character's inventory, I go through their List of Item. At this time, I only know I have some Item but no longer know that the Item is Equipable or Consumable . Basically, the Interface is no longer known to me. What design can I do in this circumstance?

Kotlin idiomatic interface method cache WITHOUT spring's cache?

Is there any way to intercept method from interface and cache result “WITHOUT” spring’s method cache ? Take a simple calculator for example :

interface ICalculate {

  fun multiply(a: Int, b: Int): Int
}

It just multiplies a and b , and return the result . Suppose it is a heavy computation work . And there are two implementations :

class CalculatorDumb : ICalculate {
  override fun multiply(a: Int, b: Int): Int {
    var sum = 0
    (1..a).forEach {
      (1..b).forEach {
        sum++
      }
    }
    return sum
  }
}

The dumb implementation just add one by one .

And there is a smart implementation :

class CalculatorSmart : ICalculate {

  override fun multiply(a: Int, b: Int): Int {
    return a * b
  }
}

This smart implementation just returns a * b .

OK , here is the point . I hope client can initialize no matter dumb or smart implementation , and can get result if the parameter is identical.

There is a Memoize pattern , described here : https://jorgecastillo.dev/kotlin-purity-and-function-memoization :

class Memoize<in T, out R>(val f: (T) -> R) : (T) -> R {
  private val values = mutableMapOf<T, R>()
  override fun invoke(x: T): R {
    return values.getOrPut(x) { f(x) }
  }
}

fun <T, R> ((T) -> R).memoize(): (T) -> R = Memoize(this)

I can use it in the implementation class , like this :

class CalculatorSmart : ICalculate {

  data class CacheKey(val a: Int, val b: Int)

  private val innerCalculate: (CacheKey) -> Int = { key: CacheKey ->
    println("cache miss")
    key.a * key.b
  }.memoize()

  override fun multiply(a: Int, b: Int): Int {
    return innerCalculate(CacheKey(a, b))
  }
}

But it seems it’s hard to apply it in the interface layer.

I wonder if there are any patterns to achieve :

  1. Each implementation class ( dumb or smart in this example) doesn’t need to implement its own cache .
  2. There are NO two public versions of method defined in interface ( for example : actual multiply() and cachedMultiply() while cachedMultiply checks cache and redirect to multiply if necessary )
  3. Client only knows one method of the interface , No matter the client initialize smart or dumb class , the result of the same parameter will be cached and returned.

For example : such scenario is OK

val calSmart: ICalculate = CalculatorSmart()
println(calSmart.multiply(3, 7)) // cache miss
println(calSmart.multiply(3, 7)) // cache hit

val calDumb: ICalculate = CalculatorDumb()
println(calDumb.multiply(3, 7)) // cache miss
println(calDumb.multiply(3, 7)) // cache hit

It will work like Spring’s method cache . but I hope there will be a kotlin-idiomatic style , maybe more functional , just like the memoization pattern above . Is there any idea ?

Thanks.