jeudi 6 juillet 2023

Implementing a Generic Singleton Factory in C#?

Hello fellow developers,

I am currently working on a project where I have to create several singleton instances of different types. I know that creating singletons for each type can be a bit tedious and error-prone, so I wanted to implement a generic singleton factory in C#. However, I am a bit unsure about the best way to accomplish this task.

The objective is to have a method which can create a singleton instance of any given type. Here is a simple code that I have so far:

public class SingletonFactory
{
    private static readonly Dictionary<Type, object> instances = new Dictionary<Type, object>();

    public static T GetInstance<T>() where T : class, new()
    {
        if (!instances.ContainsKey(typeof(T)))
        {
            instances[typeof(T)] = new T();
        }
        return (T)instances[typeof(T)];
    }
}

This is a minimalist version, and I understand that it does not take into account things like thread safety and disposing.

So, my questions are:

  1. How can I enhance the above code to make it thread-safe?
  2. Is there any better approach to implement this pattern which would also take into account the disposal of instances when they are no longer needed?
  3. Is there a way to make this pattern work if the class that needs to be instantiated has some parameters in its constructor?

I appreciate any help or advice that you can provide. Thanks!

mercredi 5 juillet 2023

What pattern to use to make a IO-bound NodeJS process work at maximum efficiency (saturate CPU)?

I need to perform a process which (in an abstract way) goes roughly like this:

while (true) {
    try {
        const item = await getItemFromQueue();
        const request = transformItemToRequest(item);
        await callExternalService(request);
        await logItemComplete(item);
    } catch ( e ) {
        log(e);
        await returnItemToQueue(item);
    }
}

As you can see, this is a mainly IO-bound process. Getting the item from queue and logging completion are expected to be fast operations, since they only involve a local DB with a permanently open connection. The external service request however can be lengthy process. Some external services might even time out if there's a problem on the other end. We currently set a 10s timeout which is very generous, but we really need to get the data out there so we try to give it some time.

Items get added to the queue fairly rapidly, although it really varies depending on the time. At peak we currently have a little over 4000 items per hour. As the business grows, this number is expected to go up even more.

Obviously I'd like to make my process as efficient as possible. If an external service is being slow, I want to use the async nature of NodeJS to fire off more requests in parallel (either to the same or other external services). If for some reason our DB is bogged down and getting an item takes ages, the running requests can still be serviced. Etc. Idle CPU is a sin and should only be allowed when there really is no more work to do.

I also want to be able to run several instances of this program, in case a single CPU core is not enough to handle a burst of items.

But how to structure my code so that this would be the case? Plugging in awaits serializes the whole thing and I'm just doing a single item at a time. I could just start a new fetch-send-log iteration on every event loop tick (setImmediate() or process.nextTick()), but I'm afraid that the process might bite off more than it can chew. Memory is not an issue, but what if it spends most time fetching and preparing new items, while the stack of replies from external services that needs to be processed will continues to grow? It should fetch a new item only if there is nothing else to do, I think. But how to detect this?

What is the best design pattern when creating an interface for functions that can return a variety of responses?

I am writing parsers for GNU/Linux commands. For example:

from pydantic import BaseModel

from mmiac.core.system import run_cmd
from mmiac.core.parsing import create_key


class HostnamectlResponse(BaseModel):
    static_hostname: str
    transient_hostname: str | None
    pretty_hostname: str | None
    icon_name: str | None
    chassis: str | None
    deployment: str | None
    location: str | None
    virtualization: str | None
    cpe_os_name: str | None
    operating_system: str | None
    os_support_end: str | None
    os_support_expired: str | None
    os_support_remaining: str | None
    kernel: str | None
    machine_id: str | None
    boot_id: str | None
    kernel: str | None
    hardware_vendor: str | None
    hardware_model: str | None
    firmware_version: str | None
    firmware_date: str | None
    

def parse() -> dict:
    """Parses output from hostnamectl command.
    
    The only required field is static hostname. Output fields from hostnamectl can be found below:
    https://github.com/systemd/systemd/blob/main/src/hostname/hostnamectl.c
    """
    content = run_cmd("hostnamectl").split("\n")
    data = {}
    for line in content:
        try:
            k, v = line.strip().split(":", 1)
        except ValueError:
            continue
        k = create_key(k)
        data[k] = v.strip()
    return HostnamectlResponse(**data)

I was thinking about making each command parser a class, but at the moment I feel like a function suffices. I imagine I'll create some sort of dispatch table that dynamically loads modules in that have a parse() method defined then call the functions using that.

But anyway, my question is related to the response. I'd love to make it such that the response is generic, but unfortunately, ps output is much different than lspci (and so on). I'm curious if there is a design pattern that I can reference, or anything really, when the functions you create have a common interface (parse()) but lack a common response.

Beyond the question itself, I appreciate any input here with regards to the design of this. My goal here is to make using the library as intuitive as possible without having to constantly reference docs.

mardi 4 juillet 2023

How to create a pie chart circle designs with matplotlib?

Here is the problem,How to create this design Here is an example

Tried experimenting with changing colors,radius still didnt get the design right, and to get the design i tried all sorts of things to get it perfect but it still always end up getting a wrong design

lundi 3 juillet 2023

How do I implement business rules within a Swift/iOS class so that rules&decisions can be made based on a core data table and not hardcoded in code?

I have the following types of variables within swift code and would like to take specific action based on a rules based table. For example:

Class Variables

joints.shoulder.left.y
joints.arm.wrist.left.y

Typical swift/pseudo code:

if (joints.arm.wrist.left.y > joints.shoulder.left.y){
   print("warning")
   self.elevated = true }

Problem: Instead of coding if/then statements, I'd like to maintain this logic in a table which contains the following columns

  1. Left expression (e.g. joints.arm.wrist.left.y)
  2. Condition (e.g. > )
  3. Right expression (e.g. joints.shoulder.left.y)
  4. Results (e.g. self.elevated = true)

I'd like to know what is the best way to be able to evaluate the expressions held in the table, but then to set the actual variable within the class to be self.elevated = true. Basically I need to figure out a way in Swift/iOS to not only to evaluate the expressions, but also to take the string "self.elevated" and to use that string literally as it refers to the variable within the class itself.

Thank you.

Why do we need a 'Builder class' in Builder design pattern?

In Builder design pattern a 'Builder' inner class is used through which we set the values for the fields of that class. What is the purpose of defining this class?

One of the main reasons cited for using a builder pattern is that it solves the Telescoping Constructor Problem

If so, why can't we just go ahead with setter methods?

(Note: Although there are some questions that had already discussed this topic (link) those questions and answers were not very straight forward. Hence, I had to draft this question)

For e.g., Why do this?

public class Employee {
  private int id;
  private String name;

  public Employee (Builder builder) {
    this.id = builder.id;
    this.name = builder.name;
  }

  public static class Builder {
    private int id;
    private String name;

    public Builder id(int id) {
      this.id = id;
      return this;
    }

    public Builder name(String name) {
      this.name = name;
      return this;
    }

    public Employee build() {
      return new Employee(this);
    }
  }
}

// Employee emp = new Employee.Builder().id(1).name("Abc").build();

instead of this?

public class Employee {
  private int id;
  private String name;

  public Employee id(int id) {
    this.id = id;
    return this;
  }

  public Employee name(String name) {
    this.name = name;
    return this;
  }
}

// Employee emp = new Employee().id(1).name("Abc");

Is it always bad practice to check if an object's type is a particular subclass in C?

I'm writing a BitTorrent client as a personal project, and the client includes a parser for the Bencode encoding format. The parser stores different types of encoded values (ints, strings, lists, dictionaries) as subclasses of a Bencode abstract class so that I can nest values cleanly (e.g. list is a vector<Bencode *>).

According to the BitTorrent specification, all the data in the ".torrent" file is in a Bencoded dictionary, meaning if the file I got is parseable, I want my Bencode * object to have a subclass dictionary, if not I would like to reject it.

I can do this easily enough with a dynamic_cast as I read in this question: How do I check if an object's type is a particular subclass in C++?

However, one of the answerers to this question suggested that if you have to check the type of a subclass, it probably means there's a design flaw. I can't figure out a clean way to do this otherwise though. Is checking the type bad in this case, and if so why and what are the alternatives?