lundi 30 novembre 2020

Unable to call matrix matrix from main function in c++? [duplicate]

Don't know how to declare matrix using pointers and passing into the function and also not getting any useful resource from internet.

void wavePrint (int* arr[],int m)
{

    for (int i = 0; i < m; ++i){

        if(i%2==0) for(int j = 0; j < m; ++j)cout<<*(arr[j])<<" ";
        
        else for (int j = m-1; j >= 0; --j)cout<<*(arr[j])<<" ";
    }
}    

int main(int argc, char const *argv[])
{

    int* arr[5]={
        {1, 2, 3, 4, 5},
        {6, 7, 8, 9, 10},
        {11, 12, 13, 14, 15 },
        {16, 17, 18, 19, 20 },
        {21, 22, 23, 24, 25 }
    };

    wavePrint(*arr,5);
}

How to construct a configuration data class with no logic?

Within our project, we need to describe the properties of the HW we are working with. This information is then used within the program to make some decisions on how the program should execute.

I'm trying to find the optimal data structure for the job and I've been wondering what would be the pythonic approach in this case?

  • These properties do not change at runtime and should not be changed by accident.

  • Additionally, some of the HW is very similar, so it probably makes sense to use an inheritance mechanism to only specify the difference between two pieces of HW, instead of re-typing all the properties.

  • A lot of properties come from lists of possible values (enums).

  • It should be easy to add new properties or to rename existing ones. E.g. if another HW property becomes relevant for the execution of the program, we can easily add a new property (at coding time). If the naming of an existing property is too similar to the new one, we might need to rename it to make it clearer how they differ.

  • Last requirement (and this is the problematic one, I think) is that we want these properties to not depend on any logic (e.g. they should be direct assignments). Here is a clarification on the last requirement:

    name = "Joe" #OK
    
    if gender == Gender.male: #not OK
       name = "Joe"
    else:
       name = "Jane"
    

The reason for the last limitation is that we want to be able to have an overview of the values without executing the code (e.g. by glancing over it). While the above example is quite readable, it gets complicated quickly when a series of functions from imported modules is called to obtain the values. We'd like to avoid the need to run the code to see what the property values are.

At the moment we're using JSON file format, which doesn't allow any code by default, just contains pure values. But this brings other problems, e.g. no integrated support for inheritance, more difficult refactoring, dependency on 3rd party modules (pydantic)...

  • I've looked into dataclass, but this doesn't limit the assignment logic.
  • I've checked the @property decorator, but this doesn't limit the assignment logic either.
  • I've checked NamedTuple, but this creates issues with inheritance (and still allows logic to be added).
  • I've seen some posts that use source-code awareness with the ast.parse, but this seems hacky.

The closest I came was with the use of a dataclass (my apologies if the car example isn't very realistic):

from dataclasses import dataclass, field
from enum import Enum

class TransmissionType(Enum):
    MANUAL = "Manual"
    AUTOMATIC = "Automatic"
    
class BodyType(Enum):
    COUPE = "Coupe"
    WAGON = "Wagon"
    
@dataclass (frozen=True)
class Car:
    transmissionType: TransmissionType = field(init=False)
    bodyType: BodyType = field(init=False)
    numberOfDoors: int = field(init=False)
    consumptionPer100km: int = field(init=False)
    
@dataclass (frozen=True)
class FancyModel2019(Car):
    transmissionType = TransmissionType.MANUAL
    bodyType = BodyType.COUPE
    consumptionPer100km = 5
    if bodyType == BodyType.COUPE: #This should not be possible
        numberOfDoors = 3
    else:
        numberOfDoors = 5
    
@dataclass (frozen=True)
class FancyModel2020(FancyModel2019):
    consumptionPer100km = 4
    
myCar = FancyModel2020()
print(myCar.numberOfDoors)

However, this still allows the programmer to add logic, that calculates the values of the properties (numberOfDoors in the example above) instead of doing pure assignments only. I'm looking for a way to discourage / prevent this at coding time.

Is there a better-suited construct for this job?

How to find in a folder the newest file following a pattern but also excluding some files

I know that this code works for finding the newest file

var directory = new DirectoryInfo(tbxDir.Text);
if (Directory.Exists(tbxDir.Text))
{
    var NewestFile = (from f in directory.GetFiles() orderby f.LastWriteTime descending select f).First();
    ...
}

What I can't imagine is how to extend it to:

  1. Use a pattern: e.g. a*c.txt
  2. Exclude a list of files (e.g. lst = { "log.txt", "ccc.txt", ...}

Can that be done with a Linq expression? Thanks for helping Patrick

How can I build a nested list using builder pattern?

I am trying to make a query builder for GraphQL syntax, by using a builder pattern. I already did it for the filtering part:

Example where I would get the title for all the events from "somewhere" with a price lower than 100.:

val query = Query.Builder()
                  .filter(PLACE,"Somewhere")
                  .filter(PRICELT, 100)
                  .build()

So for that part ^ it was easy, because it was not nested. and I just used a MutableMap<ENUM, Any> in kotlin so that I can pass strings and ints and longs and so on, and then I have a method that collects everything to a string.

{events(place:"Somewhere", priceLT:100){title}}

But now I want to programatically make a way to say what data I want to get back from the query. (NOTE: before the title part of the query was hardcoded into the QueryBuilder.

So for that I made another class called Entity which has a list of itself as an attribute.

class Entity(
        private val entity: EntityType,
        private val entities: MutableList<Entity> = mutableListOf()
) {
    override fun toString(): String {
        return if (this.entities.isEmpty()) {
            entity.str
        } else {
            this.entity.str + "{" + this.entities.onEach {
                it.toString()
            }.joinToString(" ") + "}"
        }
    }
}

And I got it to work. But to build the structure. then I have to append to the list and "visit" the list of the entity to visit the entities in that list.

For example if I want to build this query:

{
    events{
        title
        location {
            coordinates {
                longitude
                latiitude
            }
        }
    }
}

Then I need to go 2 levels down in the layers of the Entity, And the way I am doing it now, then my code is getting very wide.

fun main() {
    val e1 = Entity(
            EntityType.EVENTS,
            mutableListOf(
                    Entity(EntityType.TITLE),
                    Entity(EntityType.LOCATION,
                            mutableListOf(
                                    Entity(EntityType.COORDINATES,
                                            mutableListOf(
                                                    Entity(EntityType.LONGITUDE),
                                                    Entity(EntityType.LATITUDE)
                                            )
                                    )
                            )
                    ),

            )
    )
}

So I was thinking to use builder pattern. Or something else which will be smarter.

Thank you in advance for your help, and have a nice day.

BTW: I am using following enums:

enum class EntityType(val str: String) {
    EVENTS("events"),
    TITLE("title"),
    GENRE("genre"),
    IMAGE("image"),
    LINK("link"),
    OTHER("other"),
    PRICE("price"),
    TEXT("text"),
    TICKETS("tickets"),
    TIME("time"),
    LOCATION("location"),
    AREA("area"),
    PLACE("place"),
    ADDRESS("address"),
    CITY("city"),
    STREET("street"),
    NO("no"),
    STATE("state"),
    ZIP("zip"),
    COORDINATES("coordinates"),
    LONGITUDE("longitude"),
    LATITUDE("latitude"),
}

enum class Filter(val str: String) {
    PLACE("place"),
    PRICELT("priceLT"),
    PRICEGT("priceGT"),
    TIMELT("timestampLT"),
    TIMEGT("timestampGT"),
    AREA("area"),
    TITLE("title"),
    GENRE("genre")
}

And the rest of my code looks like this:

I share it for transparency, even though its not that relevant to my question. Later I will implement the Entities in the code where i have written the comments.

class Query private constructor(val query: String) {
    class Builder {
        private var query = ""
        private var filters = mutableMapOf<Filter, Any>()
        private var entities = Entity(EntityType.EVENTS) // I started merging the entities into the query

        fun filter(key: Filter, value: Any) = apply {
            this.filters[key] = value
        }

        fun build(): Query {
            this.query = "{events{" // Here the first part of the event string should come.
            if (filters.isNotEmpty()) {
                this.query += "("
                filters.forEach {
                    this.query += if (it.value is Int || it.value is Long) it.key.str + ":" + it.value + "," else {
                        it.key.str + ":\"" + it.value + "\","
                    }
                }
                this.query = this.query.dropLast(1) + ")"
            }
            this.query += "title}}" // Here the Entities.toString will be called
            return Query(this.query)
        }
    }

}

How design models and database with animals example use case?

I have a project that is becoming more complex by the time and I am feeling that I have to reorganize the way the Models was designed, but I am stuck in decision which direction to go.

To make the long story short...

Let's suppose that I have Animals: Parrot and Toucan (They are Birds) and Iguanas (Is a Reptilian). Deep inside theses three types of class are all Animals...

They have/do some aspects in common like eat(); sleep(); poop(); and have nickname and status, but Reptilians and Birds is for different purpose and do different things too...

In my application I will never deal with Animals directly, only Iguanas, Toucan or Parrot.

I kindly ask for some suggests of what Design Pattern should I use in this case. I have doubts on how to organize it into the database too (which class will be tables)...

Here what I am thinking about:

I am planing to implement Composite Design Pattern... am I right?

Declaring Animal as Abstract Class holding the common fields (nickname,status) and declaring the required methods (eat(); sleep(); poop();) as abstract too... so Parrot, Toucan and Iguanas can implement your own way to do this stuffs. Is it right?

Things become more unclear when deal with database, in my vision will be three tables, one for each type of Animal (Parrot, Toucan and Iguanas) with your own fields (Toucan may have one or two fields that Parrot haven't). Is this ok?

Specific Design pattern JAVA

I'm trying to implement some get/post operations on different APIs (3-4) and I really don't know which design pattern to use to improve my code readability.

For the moment I have a custom visitor pattern implemented, with the get/post methods inside my API classes instead of visitor class because it seems cleaner. Every time I want to use a new API i just make the API class, add the following methods and call them in Visitor, but this is not how to use visitor pattern.

Example how this should look like:

1 job -> getAllPictures() -> getAllPicturesFromGoogle()
                          -> getAllPicturesFromFacebook()
                          -> getAllPicturesFromTwitter()
      -> postPicture()    -> postPictureOnGoogle()
                          -> postPictureOnFacebook()
                          -> postPictureOnTwitter()

Using one class to return different objects based on __init__() in Python?

I have to deal with two formats, say A and B. I want to build a class that handles these two formats in the best way possible in Python.

My idea was to have a class that based on what is passed on init() returns a different object responsible for handling that format. This way, my user has to deal with only one class.

class AnnotationHelper:
    
    def __init__(self, format):
        if format == "A":
           #return object AnnotationHelperA
        elif format == "B":
           #return object AnnotationHelperB 
        else raise ValueError("Invalid format")
    
   def get_x():
        raise NotImplementedError() //AnnotationHelperA and AnnotationHelperB should implement this

What would a "design pattern" like this be called? Is this a valid approach for my problem or is there another standard way of doing things like this? I just want my code to be as clean and re-usable as possible.

Creational adapter

I have a lot of code like this

additional_params = {
  date_issued: pending.present? ? pending.date_issued : Time.current,
  gift_status: status,
  date_played: status == "Opened" ? Chronic.parse("now") : (opened.present? ? opened.date_played : nil),
  email_template: service&.email_template,
  email_text: service&.email_text,
  email_subject: service&.email_subject,
  label: service&.label,
  vendor_confirmation_code: service&.vendor_confirmation_code
}
SomeService.new(reward, employee: employee, **additional_params).create

The same pattern applies to many models and services.

What is the name of this pattern?

How to refactor the current solution?

Is there a gem to solve this kind of solution? Like draper or something else

Talk about the software development framework from a design perspective? [closed]

Please talk about your understanding of software development framework (e.g., architecture design, design pattern, etc.) from the perspective of design (e.g., design ideas contained in it) and your design appeal to the existing development framework (e.g., new requirements for the framework, problems to be solved).

dimanche 29 novembre 2020

samedi 28 novembre 2020

When to use factory pattern

I know this question has been asked many times, but I still have a very simple question, what is the purpose of using a factory pattern if the initiation of an object is simple.

Interface Animal{
    eat();
}

class Dog implements Animal{

     public void eat(){System.out.println("dog eat");}
}

Assume I have a concrete Cat class and fish class implement the Animal interface.

So in this case, is it necessary to make 3 Factory to create the animals? I think we only use the factory method when the initialization is difficult.

Structure to define two class in PHP

I want to define two class and I am a little confused to choose the right structure. Among these two suggestion which one do you prefer ? and why?

Suggestion 1

<?php
    
    interface AbleToFly
    {
        public function fly();
    }
    
    abstract class Airplane implements AbleToFly
    {
    }
    
    abstract class Bird implements AbleToFly
    {
    }

Suggestion 2

<?php
    
    abstract class Airplain
    {
        public abstract function fly();
    }
    
    abstract class Bird extends Airplane
    {
    }

Thank you

How to intercept a function call in JavaScript to grab the function call name

I wasn't sure how to word the title so I will go into more detail.

What I want to do is have some object called car.

The object car contains two objects called tire and engine.

What I want to happen is be able to say,

car.start();

Then I want the car object to be able to check both tire and engine to see if it contains a function with that name then call it.

So in summary

I want to be able to call an object and have that object called pass it onto whoever implemented that function call.

I looked at the proxy pattern but I don't see how I can dynamically have function calls passed on from an object to a nested object.

Any ideas would be appreciated. Thanks!

Example Code

function engine() {
    return {
        start: () => console.log('start')
    }
}

function tire() {
    return {
        getWidth: () => console.log('get width')
    }
}

function car() {
    this.tire = new tire();
    this.engine = new engine();

    // Pass on function calls made to car over to tire or engine depending on who implemented that function call.
}

// This should print start.
car.start();

**PS. ** I know I can hard code the function calls and have it pass through but I am trying to do this dynamically so I don't have to declare every single function that can be called. So I want to do this dynamically.

Flow through interface in SysML

I was wondering how it would be possible to relate, within a SySML block diagram, the data flowing through two components with the interfaces that they expose.

As an example, assume that you have a supervisor component setting a reference for a lower level controller. The controller exposes an interface Operations which features the operation set_reference() and this latter specifies a float parameter reference. The supervisor will use the interface to effectively set the reference for the lower level controller. This operation tells that there exists a data flow between the two components (e.g. each component also has a flow port) and the exchanged data is the reference. How would you model this scenario in SySML? Does it exist a way to specify both the interface and the dataflow and say "look, this dataflow is realised through this interface".

Thanks a lot for your help

I can't maintain state of a base class amongst subclasses

Summary

My goal is to write a rendering engine using DirectX 11. I plan to write it in an OOP fashion. The plan is to write separate classes. Specifically one class for shader where I can load, compile, bind and set it for usage. Second class for creating vertex buffer, where I can load vertices, bind buffers and set it for rendering.



My Attempts

I wrote one base class `A` for initializing DirectX and maintain 2 objects, `m_device` and `m_device_context`. Then as I wrote `2` subclasses `B` and `C`.

At class B I create and bind vertex buffers and At C I compile and bind vertex shaders. Both B and C uses m_device object to create objects and m_device_context to bind/set them.

In subclass B, I use subclass C to compile and bind shaders. Using subclass B I initialize Base class. but at C subclass I get memory Access violation on m_device. this is probably because I have to reinitialize base class but I can't have different instances of DirectX objects.


Question

I have read that global variable or objects are not recommended but How do I solve this problem, How do I maintain global objects that I will need thought the project?



(My question is specifically about C++ implementation, not games)

Same specialization on multiple different derived classes

I have a concrete class A like

class A{
  doStuff() {
    // do some stuff
  }      
}

and a derived class B that extends it

class B extends A {
  doStuff(){
    super.doStuff();
    // do some other stuff proper to B
  }
}

Up until here I'm satisfied with inheritance, but now I'm in need to extend both A and B with some extra functionality, that (if I still use inheritance) will end up looking sort of like

class APlus extends A {
  doStuff(){
    super.doStuff();
    // do Plus-stuffs
  }
}

class BPlus extends B {
  doStuff(){
    super.doStuff();
    // do Plus-stuffs
  }
}

which is essentially duplicating code, so a no-go.

The first way that comes to mind to solve this is to use composition, like

class Plus {

  private A memberOfTypeAorB;

  doStuff(){
    memberOfTypeAorB.doStuff();
    // do Plus-stuffs
  }
}

but this is sort of weird because I'd need a lot or changes to accomodate the initialization of memberOfTypeAorB and in terms of domain/businees APlus and BPlus ARE a subtype of A and I have scattered around a lot of functions like

compute(A)

that we'd need to modify now to accept also Pluses ...

The other way is of course also possible, using composition to add the Plus functionality to both A and B, like a strategy-pattern of sort, but I find it awkward since the default strategy in the majority of the cases is "don't do Plus stuffs" ... but maybe it's not awkward, actually now that I've written this down I find this solution more appealing!

I have about zero knowledge about design-patterns but hopefully this is not a new problem so ... Does anyone have a better idea?

vendredi 27 novembre 2020

Designing endpoints for multiple filters

I am curious if there is a better way to handle an advanced filter design. I have an API for a music catalog that allows users to search for tracks based on the following criteria (if nothing is provided then it just returns a paginated result of all tracks ordered by added date)

that means a base endpoint of something like http://www.myapi.com/api/tracks Then I offer the following parameters to allow for advanced filtering based on multiple things if they choose to do so. If a parameter is not provided then it is not included in the query at all.

Artist Name / Song Title

Genre(s)

Key(s)

BPM Range

Version Type(s)

For example, you could search for Rock songs that are in key 2A, and all songs that meet that criteria would be returned. The endpoint would then look something like this:

http://www.myapi.com/api/tracks?genres=ROCK&keys=2A

My question is that in designing something like this is there any other approach than setting up your endpoint to basically brute force through all of the possible request param combinations and having a separate query for basically each combo?

When I think of this I think of something like Linkedin's advanced filter ... surely they can't brute force that kind of thing, it would be terrible to maintain and scale. How is that kind of functionality usually implemented in production systems?

Message-based machine control pattern similar to ROS

If I have a single application running on a single computer but want to have multiple asynchronous threads running and communicating with each-other in order to control the complex behavior of machinery or robots what software design pattern would that be?

I'm specifically looking for something similar to Robot Operating System (ROS) but more in the context of a single library for c# where it handles the messages or the "message bus". There seems to be a lot of overlapping terminology for these things.

I'm essentially looking for a software implementation of a local, distributed node architecture that communicate with each-other much in the same way that nodes on the CAN bus of a car do to perform complex behavior in a distributed way.

Thanks

Should I use observables or have all logic in parent?

I have following code:

Container is an object that holds set of Parts. Some of parts are able to tell to container that they changed (ObservablePart notifies Container via someObservableMarketChanged method), and some just update their state (NonObservablePart). In case that ObservablePart changes, I need to do recalculation, and update all parts again (but this change is only applicable to NonObservableParts, ObservableParts have their values remain the same). The output of this program is:

Changing NONobservable id 4 from 1 -> 235
Changing NONobservable id 3 from 1 -> 235
Changing observable id 1 from 1 -> 235
Changing NONobservable id 4 from 235 -> 236
Changing NONobservable id 3 from 235 -> 236
Changing NONobservable id 4 from 236 -> 236
Changing NONobservable id 3 from 236 -> 236
Changing observable id 2 from 1 -> 235
Changing NONobservable id 4 from 236 -> 470
Changing NONobservable id 3 from 236 -> 470
Changing NONobservable id 4 from 470 -> 470
Changing NONobservable id 3 from 470 -> 470

and as you can see there is too much unneeded calls. What I wanted to have is this:

Changing observable id 1 from 1 -> 235
Changing observable id 2 from 1 -> 235
Changing NONobservable id 4 from 1 -> 470
Changing NONobservable id 3 from 1 -> 470

It is possible to have this case implemented as easy as:

void doit(){
        allParts.stream()
                .filter(x -> x instanceof ObservablePart)
                .forEach(x -> x.updateMe(235));
        Map<Integer, Part> changed = onlyNonObservableMarketsChange();
        for(Part m : allParts){
            m.updateMe(changed.get(m.getId()).getVal());
        }
    }

So, basically, instead of ObservablePart notifying Container that it's state changed, I have to put all the logic inside Container, and Container is not more dumb container that just forwards responsibility to Part objects. Now, it has to know which parts are observable and which are not, and that it first needs to update all observable parts, and only then it can do some calculations and update non-observable parts.

Is this use of observer pattern an overkill in this case? Should I just put this logic inside Container, since code and reasoning is much more straightforward?

import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

public class Differ {
    public static void main(String[] args) {
        Container m = new Container();
        m.allParts = Set.of(
                new ObservablePart(1,m),
                new ObservablePart(2,m),
                new NonObservablePart(3),
                new NonObservablePart(4)
        );
        m.doit();
    }
}

class Container {
    public Set<Part> allParts = new HashSet<>();

    void doit(){
        for(Part m : allParts){
            m.updateMe(235);
        }
    }

    //this would not be in Container, just needed for example
    int getSumOfObservableMarkets(){
        return allParts.stream()
                .filter(x -> x instanceof ObservablePart)
                .mapToInt(x -> ((ObservablePart) x).val)
                .sum();
    }

    //this would not be in container, but something else would calc. changes
    Map<Integer, Part> onlyNonObservableMarketsChange(){
        int obsSum = getSumOfObservableMarkets();
        return allParts.stream()
                .collect(Collectors.toMap(k -> k.getId(), m -> {
                    if(m.getId()==1 || m.getId()==2){
                        return m;
                    }
                    m.updateMe(obsSum);
                    return m;
                }));
    }

    void someObservableMarketChanged(){
        Map<Integer, Part> changed = onlyNonObservableMarketsChange();
        for(Part m : allParts){
            m.updateMe(changed.get(m.getId()).getVal());
        }
    }
}

interface Part {
    int getId();
    int getVal();
    void updateMe(int val);
}
class ObservablePart implements Part {
    Container container;
    ObservablePart(int id, Container m){this.id=id;
        container =m;}
    public int id;
    int val = 1;
    public int getId() {return id;}
    public int getVal() {return val;}
    public void updateMe(int val) {
        if(this.val != val) {
            System.out.printf("Changing observable id %s from %s -> %s%n", id, this.val, val);
            this.val = val;
            container.someObservableMarketChanged();
        }
    }
}
class NonObservablePart implements Part {
    public int id;
    int val = 1;
    public NonObservablePart(int id) {this.id = id;}
    public int getId() {return id;}
    public int getVal() {return val;}
    public void updateMe(int val) {
        System.out.printf("Changing NONobservable id %s from %s -> %s%n", id, this.val, val);
        this.val = val;
    }
}

avoiding duplicate service calls java

I have got the below services:

AccountService class:

public class AccountService {
    public createAccount(argumentsList1);
    public closeAccount(argumentsList2);
    //many other methods
}

ServiceHandler class:

public class ServiceHandler {//ServiceHandler is singleton

    SavingsAccountService savingsAccountService;//SavingsAccountService implements AccountService

    LoanAccountService loanAccountService;//LoanAccountService implements AccountService

    public AccountService getService(boolean isSavings) {
        if(isSavings) {
            return savingsAccountService;
        } else {
            return loanAccountService;
        }
    }
}

Also, I have got many different types of services like ABCService, XYZService, etc.. which invoke ServiceHandler first to get the runtime object of AccountService and then invoke the respective method as shown in the below example:

ABCService class:

public class ABCService {
    public void process1(boolean isSavingsAccount, a, b, c, arguments..) {
        AccountService accountService = ServiceHandler.getService(isSavingsAccount);
        accountService.createAccount(argumentsList1);
    }
}

XYZService class:

public class XYZService {
    public void process2(boolean isSavingsAccount, d, e, f, argumemts...) {
        AccountService accountService = ServiceHandler.getService(isSavingsAccount);
        accountService.closeAccount(argumentsList2);
    }
}

There are many other services like PQRService (similar to ABCService, XYZService), etc.. Here, I did not like duplicating the call to the ServiceHandler.getService(isSavingsAccount) in all other services (like ABCService, etc..) first to get the handle and then further invoking the required methods createAccount(), closeAccount(), etc.. How can I expose the methods of AccountService through ServiceHandler itself (so that I can call createAccount() with a single line of code)? Note that ServiceHandler is a singleton class and should be threadsafe. Is there any specific design pattern that I can use to eliminate the above duplication?

Maximum Size of Status in the Kubernetes CRD?

Is there a limit on the size of Kubernetes spec and status size in Kubernetes?

I have a use case in which the operator spec is a regular expression and regex gets expanded to a lot of actual items whose status I have to store.

Example:

type RedshiftSinkSpec struct {
    TopicRegexes string `json:"topicRegexes"`
}

type Topic string

type RedshiftSinkStatus struct {
    // +optional
    CurrentMaskStatus map[Topic]MaskStatus `json:"currentMaskStatus,omitempty"`

    // +optional
    DesiredMaskStatus map[Topic]MaskStatus `json:"desiredMaskStatus,omitempty"`
}

Since the number of topics is being computed from the regular expression. I have no idea how big the data structure can grow for someone else. So would want to cap it at some level. Hence need help with the max limit Kubernetes allows.

Also, it is necessary to have it like this to save on the number of Redshift connections. Cannot really break the problem into one more crd with one topic.

Please suggest.

Not able to Print the Pattern in c++ [closed]

After executing the code the first half is not getting instead receiving this output: Expecting:

         1
        232
       34543
      4567654

//Above output is not getting

Getting: 1 230 34500 4567000

//Problem in printing the above pattern

void p8(int n){
    int star=1;
    int space=n-1;
    int number;
   
    for (int i = 1; i <= n; i++)
    {
        number=i;

        for (int j = 1; j <= space; j++)
        {
            cout<<" ";   
        }
        for (int j = 0; j < 2*number-1; j++)
        {
           
            if(j<=number/2){

                cout<<i+j;
            }
            else{

                cout<<number-i;
            }

        }

        number+=2;
        space--;

        cout<<endl;
        
    }
}

Designing a network client library

I'm looking for guidance and/or best practices for designing a Network Client Library.

This library will be used by a client application to:

  • authenticate to an HTTP service (most likely RESTful)
  • submit some arbitrary data
  • poll for processing state
  • return the result

The most important design consideration is that the library should be very testable.

At this point I'm thinking:

  • Use something like command pattern to encapsulate requests/responses. This way I'll be able to mock requests/responses easily.
  • In the client application, separate network concerns from the business logic layer. This will ensure end to end testability.

The eventual implementation will be in Python, so if there are specific libraries you can recommend, I'd appreciate it.

What else am I missing? I bet this has been done before, I'm looking for some tribal knowledge, I guess.

what are the three "dimensions of Combinations" of Design Patterns

what are the three "dimensions of Combinations" of Design Patterns Explain for each dimension how it improved Software quality

How to efficiently make a single instance for attaching events and share between two classes in .Net Standard

I'm working on a .Net Standard project and implementing some events from a third-party SDK.
As comments in the SDK, only one single instance of event args can be sent back.
Well, when all events are attached in one class, works fine.

Now I need to separate the class into two pages (classes).
Those events will be triggered on either of the pages.
But I cannot guarantee the initial order of those two pages, or one page might never be initialized.

So what I've done here (which works fine for now) is to share the properties in a global class and attach the events based on a boolean flag:

public class MainClass()
{
    public bool AttachFlag { get; set; } = false;
    public List<Obj> ObjList { get; set; } 
}
public class Page1() 
{
    private IProgress<ObjEventArgs> localChanged;

    public Page1()
    {
        if (!AttachFlag)
        {
            localChanged = new Progress<ObjEventArgs>(this.ObjUpdated);
            this.objManager.ObjChanged += (sender, e) => localChanged.Report(e.Object);

            AttachFlag = true;
        }
    }

    private void ObjUpdated(ObjEventArgs e)
    {
        //Update ObjList from e
    }
}
public class Page2()    //same logic as Page1 class
{
    private IProgress<ObjEventArgs> localChanged;

    public Page2()
    {
        if (!AttachFlag)
        {
            localChanged = new Progress<ObjEventArgs>(this.ObjUpdated);
            this.objManager.ObjChanged += (sender, e) => localChanged.Report(e.Object);

            AttachFlag = true;
        }
    }

    private void ObjUpdated(ObjEventArgs e)
    {
        //Update ObjList from e
    }
}

I wonder if any suggestion to make this logic more efficient and maintainable.

Cheers

jeudi 26 novembre 2020

In Rust, what's the pattern for when you need a reference-holding struct to sometimes own its referenced data?

Consider the following data structure:

struct ReferenceHoldingStruct<'a> {
    pub prop: &'a str
}

This pattern is often useful, especially in parsers (my use-case), for "giving" a struct some piece of string data without re-allocating it:

fn generate_these_1<'a>(input: &'a str) -> ReferenceHoldingStruct<'a> {
    ReferenceHoldingStruct { prop: input }
}

However, I've got a case where I have a struct like the above, but in one spot I need to generate instances that are "independent"; i.e. they own their own data:

fn generate_these_2<'a>(input: String) -> ReferenceHoldingStruct<'a> {
    ReferenceHoldingStruct { prop: input.as_str() }
}

I understand why this version doesn't work: the String being referred to doesn't live anywhere where Rust can see that it will hang around to keep fulfilling the struct's &str reference. I thought maybe this would work:

fn generate_these_2<'a>(input: String) -> (String, ReferenceHoldingStruct<'a>) {
    (input, ReferenceHoldingStruct { prop: input.as_str() })
}

because at least the String won't get immediately dropped. I thought maybe Rust could figure out that this tuple contains both the reference and the data it refers to, and that they'd therefore be valid as long as they're kept together like this. But no dice: this still doesn't work. It treats the reference as a borrow and the move to the tuple as a move, and you can't do both "at the same time".

So, I understand the problem, but not where to go from here. What's the standard practice for this kind of situation?

Under what circumstances should it be designed as an iterator

Under what circumstances should it be designed as an iterator.

I have a Polygon class whose attributes are aggregated by edges. Should I directly use an edge array as its member, or design Polygon as an iterator of the edge collection? Can I get some suggestions, and what are the reasons for your suggestion?

how can i draw a specific pattern is java

how can I draw :

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

What is the logic behind it, or if I want to draw something else such as an alphabet or a number the code I used under will draw a rectangle filled with stars. How can I use loops and if statements to make spaces in between the stars I showed above?

import java.util.Scanner;

public class rectangle {

    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        
        System.out.println("Enter size:");
        int size = sc.nextInt();
        
        System.out.println("Enter ShapeS:");
        String shape  = sc.next();
        for (int i = 1; i<=5*size; i++) {
            for (int j = 1; j<=3*size; j++) {
                System.out.print(shape);
            }
            System.out.println();
        }

Class composition/design pattern for similar classes - Java classes [closed]

The problem I am working on:

I am writing black-box tests for a legacy service - with the aim of writing a modern equivalent that will behave in the same way as the legacy variant. I have documented all the calls that the legacy service receives and these are now collected in about 30 JSONs of similar structure. The idea is that I write the tests for each call into the service, document all the outputs and then have a test suit that tests the functionality of the service which could then be tested against the new, to be written, service.

I am working in Java.

What I have done so far:

I have a bunch of JSON files, some nested, that represent requests to the server. There is about 30 of them. They have about 50 odd fields each. Majority of the fields have the same name and differ by value only - they either have a value (String, long etc) (which would vary from file to file but I am planning to use constants for those) or are null. About 20% of fields differ from file to file.

I have written POJOs for all of these and I realised that a lot of these POJOs are almost the same with some minor differences - the differences arise in the cases where the same field has a null value in one JSON and a non-null value in another.

I am struggling to think of a design pattern to use to reduce the number of similar objects and be able to construct the relevant objects with required fields as required for each type of request.

So, what I have done for one of the classes is have it implement an interface with default methods that throw an exception and then I use a helper method that takes an interface and constructs an object using try/catch to account for those fields that are not present. This is only a partial solution (ie it does not account for fields that are present but are null). Additionally, I am not happy with the solution because:

  1. it does not actually reduce the number of classes, it merely allows me to build an object using any class that implements an interface and make sure that it comes out as required
  2. if I follow this approach and implement similar structure for all the classes, my test suit is going to be very slow - it is going to keep throwing exceptions while building the objects
  3. the solution still does not account for null fields.

I do need the null fields to be present in the JSON request sent to the service as this is part of the functionality of the current service. IE:

{
   "field1":"some value",
   "field2": null
}

is part of the expected call.

What I am looking for:

I am sure that I am missing something very obvious in terms of composition or design pattern that could be helpful here - someone must have had a similar problem before and has found a way to efficiently deal with it. Any suggestions would be welcome.

What is Columbus Reverse Engineering?

I am studying a research paper on design pattern. In the paper,they used an approach called Columbus Reverse Engineering. I am not really sure what this is. Is it a Machine learning algorithm or any statistical method? And why is it used to detect design pattern?
I mean why do we need to detect design pattern? What is the motive? TIA

Java Interface does not take into consdieration method implementation from the super class

The following example with ducks, is based on the Head First design patterns book.

I have a game with different types of ducks. There is a super class Duck and it has two behaviours: fly and quack, which are stored in fields. The concrete classes decide (in the constructor) which behaviour a concrete breed has (see MalardDuck class).

I realised I want my ducks to not only have type Duck but also Quackable (so that I can have methods that accept only quackables - assuming that there are other types that quack - see Lake class). When I implement the interface in MallardDuck, the compiler complains that the class does not have the method quack although it is defined in its superclass - Duck class.

Now I could think of two solutions:

  1. Overwrite a method quack by just calling the method from the superclass: super.quack() <- but that seems unnecessary (in theory) - a child class has a direct access to superclass's public methods, so why the interface Quackable even complains...?
  2. Make Duck implement the Quackable -> this is rather illogical cause some Ducks don't Quack (their quackBehaviour is implemented with SiletnQuack class).

However in both solutions the duck:

  • HAS A quackable behaviour, AND
  • IS A quackable

Isn't that fundamentally wrong? What am I missing?

abstract class Duck{
    protected Flyiable flyBehaviour;
    protected Quackable quackBehaviour;
    public void quack(){
        quackBehaviour.quack();
    }
    void performFly(){
        flyBehaviour.fly();
    }
    void swim(){
        // swimming implementation
    }
    abstract void display();
}
interface Quackable{
    void quack();
}
class Quack implements Quackable{

    @Override
    public void quack() {
        System.out.println("Quack!");
    }
}
class Quack implements Quackable{

    @Override
    public void quack() {
        System.out.println("Quack!");
    }
}
class SilentQuack implements Quackable{

    @Override
    public void quack() {
        System.out.println("...");
    }
}
class MallardDuck extends Duck{
    public MallardDuck(){
        quackBehaviour = new Quack();
        flyBehaviour = new FlyWithWings();
    }

    @Override
    void display() {

        // it looks like a Mallard duck
    }
}

What if I want to accept ducks to this method as quackables (along with other animals):


class Lake{
    ArrayList<Quackable> quackingAnimals;
    void addQuackingAnimal(Quackable animal){
        quackingAnimals.add(animal);
    }
    void displayQuackables(){
        //...
    }
}

Solution 1:

class MallardDuck extends Duck implements Quackable {
    public MallardDuck(){
        quackBehaviour = new Quack();
        flyBehaviour = new FlyWithWings();
    }

    @Override
    void display() {

        // it looks like a Mallard duck
    }

    @Override
    public void quack() {
        super.quack();
    }
}

Solution 2:

abstract class Duck implements Quackable{
    protected Flyiable flyBehaviour;
    protected Quackable quackBehaviour;
    public void quack(){
        quackBehaviour.quack();
    }
    void performFly(){
        flyBehaviour.fly();
    }
    void swim(){
        // swimming implementation
    }
    abstract void display();
}

Best practice to organize SpringBoot Events/EventListeners

I think this is strongly related to Observer and Publish/Subscribe patterns but since I have still not seen production code using it, I have some questions on how you guys organize your code when using events and eventListeners in SpringBoot (though I believe it can be extended to any languages/frameworks).

Let's say I have 3 classes and their respective services :

Foo with FooService
Bar with BarService
Baz with BazService

When FooService creates a Foo object, I want BarService and BazService to execute some code to update their respective tables for exemple so I publish the FooCreatedEvent.

What are the best practices here since I have 2 different services ?

Solution 1 :

One class encapsulating everything

public class FooEventListener {

    @Autowired
    private BarService barService;
    @Autowired
    private BazService bazService;

    @EventListener
    public void handleFooCreatedEvent(FooCreatedEvent event) {
       barService.doSomething(event);
       bazService.doSomething(event);
    }

}

Solution 2 :

2 classes each encapsulating its own service

public class BarEventListener {

    @Autowired
    private BarService barService;

    @EventListener
    public void handleFooCreatedEvent(FooCreatedEvent event) {
       barService.doSomething(event);
    }

}

public class BazEventListener {

    @Autowired
    private BazService bazService;

    @EventListener
    public void handleFooCreatedEvent(FooCreatedEvent event) {
       bazService.doSomething(event);
    }

}

I like solution 2 in terms of design, but I think it can be a bit confusing to have BarEventListener handle FooEvents

What do you guys think ?

mercredi 25 novembre 2020

What design pattern should I use to combine three data sources that communicate in a chain?

Specific Questions:

  1. What is the best design pattern or strategy for this particular problem?
  2. How can I prevent potential cascading effects & re-writing the code?

Details:

I am developing a program in which I have three data sources (A, B, C). In order to grab data from B, I need information from A. In order to pull data from C, I need information from B.

Current Approach:

Description:

I used four classes. A mediator class that handles the passing of data from A, B, & C. Then, a separate class for A, B, & C that handles extracting, formatting, sub-setting, etc.

Process Flow:

  1. Inside the mediator class I instantiate classes A, B, & C.
  2. I run a function inside the mediator class called create_A_files().
  3. The data from A that B needs is then passed as an argument to B's create_B_files(A_necessary_data) function.
  4. Finally, the same is done from B to C through a create_C_files(B_necessary_data) function.

Problems with Current Approach:

I am fighting cascading effects. Any changes I make in A propagate and cause errors & bugs in B & C. Therefore, I have to go back and rewrite B & C to accommodate the changes from A.

Thank you in advance for your help! Narnia649

Pattern and Matcher is not giving the result what it should give in java

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main
{
    public static void main(String[] args) {
        ArrayList<String> celebURLs = new ArrayList<String>();
        ArrayList<String> celebName = new ArrayList<String>();
        String webHtml = "<img loading=\"lazy\" width=\"346\" height=\"440\" src=\"https://svenskainfluencers.nu/wp-content/uploads/Skärmavbild-2020-06-28-kl.-22.31.16.png\" alt class=\"wp-image-230\" srcset=\"https://svenskainfluencers.nu/wp-content/uploads/Skärmavbild-2020-06-28-kl.-22.31.16.png 346w, https://svenskainfluencers.nu/wp-content/uploads/Skärmavbild-2020-06-28-kl.-22.31.16-236x300.png 236w\" sizes=\"(max-width: 346px) 100vw, 346px\"><figcaption>Instagram: Isabella Löwengrip</figcaption>";
        Pattern p = Pattern.compile("<figcaption>Instagram: (.*?)</figcaption>");
        Matcher m = p.matcher(webHtml);
        while (m.find()){
            celebURLs.add(m.group(1));
            System.out.println(m.group(1));
        }
        Pattern pp = Pattern.compile("<img loading=\"lazy\" width=\"346\" height=\"440\" src=\"(.*?) alt=\"\" class=");
        Matcher mm = pp.matcher(webHtml);
        while (mm.find()){
            celebName.add(mm.group(1));
            System.out.println(mm.group(1));
        }
    }

In the above code I am practicing to make an android app name Guess the Celebrity that will download webcontent in html form form website and then i will use a random image to show and 4 different names.

To make it easier i have taken the img tag of one of the Celebrity and figcaption tag in which celebrity name is given and stored it in a String webHtml.

The code is running but it only gives me celebrity name but it does not give me the img url that i want to download.

Can you please help me to figure out how to resolve it.

DTO is really needed for Create / Update Domain?

Well, I've heard many times that we need to use DTO pattern to reduce the resource and decouple between client and server.

I totally agree with the necessity of DTOs for fetching data to clients since we don't need to fetch a fridge to get bread, so it completely makes sense.

But when it comes to creating or updating a domain, we probably need to write massive boilerplates since the data structure between Domain and DTO would be almost the same.

So here is the question, Do we really need to write a DTO for updating / deleting a domain?

How to make diamond pattern using java?

How to make this pattern if input N = 5 Output : diamond

Mine is like this, it become 2N if input N = 5 Output my diamond

Here's my code

int i,j;

    for(i = 0; i <= n; i++)
    {
        for(j = 1; j <= n - i; j++)
            System.out.print(" ");
        for(j = 1; j <= 2 * i - 1; j++)
            System.out.print("*");
        System.out.print("\n");
    }

    for(i = n - 1; i >= 1; i--)
    {
        for(j = 1; j <= n - i; j++)
            System.out.print(" ");
        for(j = 1; j <= 2 * i - 1; j++)
            System.out.print("*");
        System.out.print("\n");
    }

What should i fix??

Storing and iterating through a collection of objects with unrelated interfaces?

I have a group of POJOs that are unrelated in their interface (ex. one might store an int and a boolean, one may store only a String, etc.). They are, however, logically part of the same group - they are objects representing different types of updates with different data models depending on the specific type of update. I want to have a collection of these "update" objects and iterate through them, handling each concrete event differently depending on the class.

My thought on how to approach this is to use the visitor pattern, but I wasn't sure if the visitor pattern can/should be used with objects that aren't directly inheriting from the same superclass or implementing a common interface. Is having an interface like below where the only unifying factor is the accept method a valid approach, or is there a better-suited design approach for a case like this? I would then presumably have a Collection<Update> which I would iterate over.

public interface Update {
   public void accept(UpdateVisitor visitor);
}

Decoupling implementation from public API [closed]

Implementation 1

type DBAuthentication{ // talking to database
   field1 Type1
   field2 Type2 
}

func (d *DBAuthentication) f1(x str){
  // do something
}

func (d *DBAuthentication) f2(x, y int){
  // do something
}

Implementation 2

type LDAPAuthentication{ // talking to LDAP service
   field1 Type3
   field2 Type4 
}

func (d *LDAPAuthentication) g1(x []str){
  // do something
}

func (d *LDAPAuthentication) g2(x, y str){
  // do something
}

Implementation 3

type KeyStoreAuthentication{ // talking to keystore service
   field1 Type4
   field2 Type5 
}

func (d *KeyStoreAuthentication) h1(x float64){
  // do something
}

func (d *KeyStoreAuthentication) h2(y int){
  // do something
}

func (d *KeyStoreAuthentication) h3(z str){
  // do something
}

User provides credentials username/password to validate with above 3 implementations. Iterate these implementations and accept the credentials if any of the above 3 implementations validate successfully.

How should the public API Authenticate(username,password)de-couple from these three different implementations? user of the public API provides username/password

mardi 24 novembre 2020

What is the difference between a design pattern and an STL library component such as map in c++? [duplicate]

im currently prepping for my exam and our professor gave us this example question that may come up and Im not sure how to answear it. Thankyou :)

"What is the difference between a design pattern and an STL library component such as map?"

Why a Pattern (design pattern) must describe a relationship?

I'm learning design patterns and I'm reading the book: JavaScript Design Patterns by Addy Osmani. Explaining how a pattern must be considered as a real pattern, he writes this as a part of the rules:

It must describe a relationship: In some cases it may appear that a pattern describes a type of module. Although an implementation may appear this way, the official description of the pattern must describe much deeper system structures and mechanisms that explain its relationship to code.

But I don't get it. I don't understand what he means with "type of module" and why a pattern must describe a much deeper system structures.

If anyone could explain me in a better way what he meant I'd appreciate it!

This is the link of the book.

I want to add a Component class that stores an Entity pointer. But Entity requires Components to be built

Entity header

#include "Common.h"
#include "Components.h"

class EntityManager;

typedef std::tuple<
    CTransform,
    CLifeSpan,
    CInput,
    CBoundingBox,
    CAnimation,
    CState,
    CFollowPlayer,
    CPatrol,
    CDamage,
    CHealth,
    CInvincibility,
    COwner
> ComponentTuple;

class Entity
{
    friend class EntityManager;

    bool                m_active    = true;
    std::string         m_tag       = "default";
    size_t              m_id        = 0;
    ComponentTuple      m_components;

    // constructor is private so we can never create
    // entities outside the EntityManager which had friend access
    Entity(const size_t & id, const std::string & tag);

Components header

#pragma once

#include "Animation.h"
#include "Assets.h"


class Component
{
public:
    bool has = false;
};

class COwner : public Component
{
public:
    std::shared_ptr<void> owner = nullptr;

    COwner() {}
    COwner(const std::shared_ptr<void>& o)
        :owner(o) {}
};

class CTransform : public Component
{
public:
    Vec2 pos = { 0.0, 0.0 };
    Vec2 prevPos = { 0.0, 0.0 };
    Vec2 scale = { 1.0, 1.0 };
    Vec2 velocity = { 0.0, 0.0 };
    Vec2 facing = { 0.0, 1.0 };
    float angle = 0;

    CTransform() {}
    CTransform(const Vec2& p)
        : pos(p) {}
    CTransform(const Vec2& p, const Vec2& sp, const Vec2& sc, float a)
        : pos(p), prevPos(p), velocity(sp), scale(sc), angle(a) {}

};

// ALL OTHER COMPONENTS BELOW...

The focus is on COwner. I would like COwner to hold a shared_ptr to an Entity. But after adding shared_ptr I get an error because now Entity needs Components.h and Components.h needs Entity.h . I tried to get around this by using shared_ptr but I have no success on using that to access the class that the pointer points to use its functions .

is there anyway to solve this? If there is missing info, let me know and I will add it.

Get pattern from list in python

I've got this list:

['i', 'like', 'dog', 'with', 'big', 'eye']

i want to print it out like:

i
i like
i like dog
i like dog with big eye

More difficult? How can I create a dict like:

{'i':'like', 'i like':'dog', 'i like dog':'with', 'i like dog with':'big', 'i like dog with big':'eye}

In python3, what's the difference between defining a class method inside or outside __init__ function?

Example

class Foo:
    def __init__(self, val):
        self.val = val
    def f(self,arg=None):
        if arg: print(arg)
        else: print(self.val)
    @classmethod
    def otherclassmethods(cls):pass

class Foo2:
    def __init__(self, val):
        # self.val = val, no need that
        def f(arg=val):
            print(arg)
        self.f = f
    @classmethod
    def otherclassmethods(cls):pass

I found it's perfect to define a class method inside __init__ function:

  1. in the normal class method I don't need self argument anymore.
  2. I don't need setattr to Foo2, and it's encapsulated automatically.
  3. Function looks more similar to c++.

If I define all class members inside __init__ function, and I am more concerned with their real practical effect. Maybe in concept, a closure inside __init__ is not a class method, but I think it work well as a classmethod. Based on it my question is: what's the difference between defining a class method inside or outside __init__ function?

Please help me.

What are the reasons to use multiple programming languages in one software project? [closed]

As mentioned above I'm getting deeper into the actual application development and when I'm looking for technology stacks of companies I'm always wondering why they are using multiple programming languages. Wouldn't it be mostly reliable to use just one programming language to maintain a high degree of maintainability and the skill to refactor code form every developer? I do not really understand why it is so essential to use, e.g. 1) Python and Ruby in a Software Project or 2) Java and Go .

Can somebody give some insides why and depending on which factors you actually choose a Tech-Stack for a certain application.

Thanks for your help!

Creating instances of class using decorator design principle based on user input

At the moment I have executable code like this:

Sandwich sandwich_wTuna_wDoubleCheese = new Cheese(new Cheese(new Tuna(new Bread())));

For your better understanding, Sandwich is an abstract class that is extended by Bread and the SandwichDecorator. The sandwich decorator himself is again abstract and is extended by Cheese, Tuna, Tomatoes,.. you name it.

Now this works fine, however I have some bakeries that should sell these Sandwiches that were created using the decorator design principle. How am I going to do this?

I want that I can do something like this:

List<String> list=new ArrayList<String>();
list.add("Cheese");
list.add("Cheese");
list.add("Tuna");
Sandwich sandwich_wTuna_wDoubleCheese = bakery1.SellBreads(list);

Sure I could pass in the instances already and do the decorating within the bakery function, but I hope there are other ways.

Have you an idea, how to solve this? Thanks for your help and advice.

Java how to replace multi-level try-catch

I have a roughly similar construction:

try {
    ...some code
} catch (Exception e) {
    try {
        ...some code
    } catch (Exception ex) {
        ...another try-catch
    }
}

That is, the logic is that I need to execute the method. If an exception throws, then execute another, and so on. This code looks really bad. How can this be refactored?

Unity data models

I want to make 2d multiplayer board game. What is the proper way to store data on the client side? I have a user, user has an arbitrary amount of wallets and groups he is in. A group has list of all members. A member has own information. I do not need to store serialised data on client. All data will be requested from server on signing in. I have many MonoBehaviours that refers to certain user's field (each wallet, id, name, list of groups he is in, each group name, status, member etc.). How to manage all this data?

I am looking forward to ScriptableObject, but in the end I will have 1 huge UserSO. And when I will want to Wallet.prefab to display certain balance, I will need to store UserSO ref in it.

Could you give me some advice? Thanks.

lundi 23 novembre 2020

Which design pattern to use to avoid if/else in validation classes?

I am currently using HibernateConstraintValidator to implement my validations. But my reviewer is not fine with having if/else in code or ! operators. Which design pattern can I use to remove the if/else in my validation logic?

public class SomeValidatorX implements ConstraintValidator<SomeAnnotation, UUID> {

      @Autowired
      SomeRepository someRepository;
   
      @Override
      public boolean isValid(UUID uuid, ConstraintValidationContext context) {

             return !(uuid!=null && someRepository.existsById(uuid)); //The reviewer doesn't want this negation operator
      }
}

And in below code, he doesn't want if/else

public class SomeValidatorY implements ConstraintValidator<SomeAnnotation, SomeClass> {

      @Autowired
      SomeRepository someRepository;
   
      @Override
      public boolean isValid(SomeClass someObject, ConstraintValidationContext context) {
           if(someObject.getFieldA() != null) { //He doesn't want this if statement
                //do some operations
                List<Something> someList = someRepository.findByAAndB(someObject.getFieldA(),B);
                return !someList.isEmpty(); //He doesn't want this ! operator
           }
           return false; // He was not fine with else statement in here as well
      }
}

Side Note: We have to use Domain Driven Design (if it helps)

Controllers should contain all the requests from a specific entity or screen?

Controllers should contain all the requests from a specific entity or screen? For example, lets say we have a screen where whe can save new clients of a Electronic shop, edit exiting ones, etc. So we could create a ClientController. We have other screen where we can save and update our electronic components stock. So we could create a StockController. But, what about if we have other screen where we are asked to show a list of clients and a list of the stock components. Where do these two requests should go?

  1. Should the last two requests should go to a different controller named ListsController or something similar?

  2. Should the list of clients should go to the ClientController and the list of stock to the StockController?

What do you think are the benefits or reasons to choose any of the options?

Thanks!!

Demonstration apps for design patterns in Java for Android

Are there good demo apps with different design patterns written in Java for Android? I need more examples of them, from industry perspective

Spring downloading files from multiple sources

I need to implement the functionality of downloading files from different sources (storages). The storage can be a separate server in the local network, a remote server, etc. Moreover, each storage has different data transfer protocols (like http, ftp) and different credentials. How can this be done? Is there a pattern for this? Or have you ever done something like this?

Javascript Board Design

I want a JavaScript program to draw a 6x7 board where in the odd rows the first and last tiles are yellow and other tiles are white; and for the even rows, the colors are flipped

So something like this:

enter image description here

<body>
    <div id="div1"></div>
</body>
window.onload = function drawTheCеlls() {
  
    var board = document.getElementById('div1');

    for (var i=0; i<6; i++ ){
        var row = document.createElement('DIV')

        row.className = 'row'
    row.style.flexDirection = i % 2 === 0 ? '' : 'row-reverse'; 
    for (var j = 0; j < 7; ++j){
    var square = document.createElement('DIV')
    square.className = 'square'
    square.style.backgroundColor = j % 2 === 0 ? 'white' : 'black'
    row.appendChild(square)
    }
    board.appendChild(row)
    }

}


  
function drawOneCell(color) {
    
    

    var newButton = document.createElement("button");
    $(newButton).attr("class", color);
    $("#div1").append(newButton);

}

Appreciate the help

make a factory of factory

I have two factory:

class Factory
{
   public static function getInstance($type) {
     .....
   }
}

and

class Factory
{
   public static function getInstance($type) {
     .....
   }

}

so, now I want to make an factory of my two factory like this :

class FactoryOfFactory
{
  public static function getFactory($service)
  {
    switch ($service) {
      case 'fac1':
        $Factory = new Factory();
        break;
      case 'fac2':
        $Factory = new Factory();
    }

    return $Factory
  }
}

so I don't know to differentiate my two factory

thank for help

make a factory of factory

I have two factory:

class Factory
{
   public static function getInstance($type) {
     .....
   }
}

and

class Factory
{
   public static function getInstance($type) {
     .....
   }

}

so, now I want to make an factory of my two factory like this :

class FactoryOfFactory
{
  public static function getFactory($service)
  {
    switch ($service) {
      case 'fac1':
        $Factory = new Factory();
        break;
      case 'fac2':
        $Factory = new Factory();
    }

    return $Factory
  }
}

so I don't know to differentiate my two factory

thank for help

If you have multiple Applications, is it a good design practice to store users in one table with a column that differentiate the Application

I have a C# project called Authentication that allows users to login and get their login credential checked and if passes, returns the token.

I want to reuse that C# Authentication project for other Applications that I am designing. Is it a good practice to store all the users from different Applications in one table or is there a better way to go about coding for One Authentication project for many Applications?

Communicating form viewModel to ViewController - completion handlers?

In my view controller I have the following code:

    func handleCommentPost() {
        print("Handle post comment")
        
        if !self.customView.textView.text.isEmpty {
            if let comment = self.customView.textView.text {
                self.viewModel.createPostComment(postItem: postItem, user: self.user, comment: comment) { result in
                    switch result {
                    case .success(_):
                        self.customView.textView.text = ""
                        self.datasource.applySnapshot(with: self.viewModel.postDetailItems.value)
                        self.customView.textView.resignFirstResponder()
                    case .failure(let error):
                        print("Failed to save comment: \(error)")
                    }
                }
            }
        }
    }

and in my viewModel createPostComment is defined as:

    func createPostComment(postItem: PostItem, user: User, comment: String, completion: @escaping (Swift.Result<Comment, Error>) -> ()) {
        let userId = user.id
        let postId = postItem.post.id
        let timestamp = Int(Date().timeIntervalSince1970)
        let comment = Comment(postId: postId, userId: userId, comment: comment, createdTimestamp: timestamp)
        firstly {
            self.appViewModel.servicesProtocol.createComment(comment: comment)
        }.done { comment in
            let postDetail = PostDetailItem(comment: comment, like: nil, user: self.appViewModel.currentUser.value!)
            self.postDetailItems.value.insert(postDetail, at: 0)
            completion(.success(comment))
        }.catch { error in
            completion(.failure(error))
            print("Error creating comment: \(error)")
        }
    }

As you can see I am using completion handlers to let my controller know - from a design perspective is this ok? As you may have noticed, the properties are Combine subject properties because I was toying with the idea of subscribing to the changes rather than completion handlers, but I don't know what the right approach is here.

It feels like the completion handlers are very easy to read and understand whereas using something like Combine to notify the controller is a lot of "magic", and might be hard to follow?

Is there some documentation which design patterns were used in the source code of Go?

I am inspecting the Go language and the design patterns which were used in the implementation and having a hard time, since I am new to Go and the implementation of the language itself is written in Go. So my question is if there is some kind of documentation or anything like that which describes where design patterns were used?

dimanche 22 novembre 2020

what's the point of query/command objects in CQRS?

What is the point of having an additional transfer object?

Why is

cookingRecipeCommandHandler.Handle(new CreateCookingRecipeCommand(...)); 

better than

cookingRecipeHandler.CreateCookingRecipe(...);

I'm having a hard time to understand what the advantages of these additional objects are supposed to be.

Python: Better design to have a python object with intellisense get all available property

My main goal is to have a python object available for users, imported from the library, that can access all its properties using dot operations (that works with intellisense/auto complete -- very important). See sample code below.

Is there a better way to design this library? As you can see, there could be multiple classes, which are fairly similar. How could I pass the "parent" value without __init__, since I want to just access the values/property using all dot operation, without () in it. Basically I just want users to do something like Sample.parentA.john and not Sample().parentA().john or something

This could be fairly messy especially when it gets very nested. I tried reading/creating a table and access the members of the dictionary using dot operation (kinda from dot access dictionary, but the problem is, the object wont really autofill or cant use intellisense, so users will still need to know the structure or available properties, so it does not really work for my need.

It might also be cleaner having the whole data implemented in XML structure, and somehow have a code generate and object that can have intellisense detect available properties, but I cant seem to make it work with intellisense as well. Kinda like the dot operation using dictionary above.

In short, I want a python object that supports intellisense/autofill to help users get the available properties (which could be nested). And at the end, I really need just a string representation of all the options the user selected. Options meaning Sample.parentA.steve.joe user really selected options parentA, steve, and joe. And ofcourse, some options are only available, depending on what 'parent' option was selected.

mylibrary.py:

class GrandchildSarah():
    name = "ParentA_ChildSteve_GrandchildSarah"


class GrandchildJoeA():
    name = "ParentA_ChildSteve_GrandchildJoe"


class GrandchildJoeB():
    name = "ParentB_ChildSteve_GrandchildJoe"


class ChildSteveA():
    name = "ParentA_ChildSteve"
    sarah = GrandchildSarah
    joe = GrandchildJoeA


class ChildSteveB():
    name = "ParentB_ChildSteve"
    joe = GrandchildJoeB


class ChildJohn():
    name = "ParentA_ChildJohn"


class ParentA():
    name = "ParentA"
    john = ChildJohn
    steve = ChildSteveA


class ParentB():
    name = "ParentB"
    steve = ChildSteveB


class Sample():
    parentA = ParentA
    parentB = ParentB


def check(exp, obj):
    if isinstance(obj, str):
        print(f"expected: {exp} actual: {obj}")

    elif isinstance(obj, type):
        print(f"expected: {exp} actual: {obj.name}")

    else:
        print(f"expected: {exp} actual: {obj}")

main.py:

from mylibrary import Sample, check

a = Sample.parentA                    # can be completed using auto complete
check("ParentA", a)

a = Sample.parentA.john               # can be completed using auto complete
check("ParentA_ChildJohn", a)

a = Sample.parentA.steve              # can be completed using auto complete
check("ParentA_ChildSteve", a)

a = Sample.parentA.steve.sarah        # can be completed using auto complete
check("ParentA_ChildSteve_GrandchildSarah", a)

a = Sample.parentA.steve.joe          # can be completed using auto complete
check("ParentA_ChildSteve_GrandchildJoe", a)

a = Sample.parentB                    # can be completed using auto complete
check("ParentB", a)

a = Sample.parentB.steve              # can be completed using auto complete
check("ParentB_ChildSteve", a)

a = Sample.parentB.steve.joe          # can be completed using auto complete
check("ParentB_ChildSteve_GrandchildJoe", a)

Why isn't my text field hint appearing correctly on the text field?

I have an email field that was designed by a graphic designer. I want to use it on my login page but I want to add a hint to the field to tell the user that their email/username goes there. However, when I try to use Android Studio's built-in hint attribute, it shows the hint off-center to the field. How can I use the PNG field the designer made for me and still be able to use hints?

enter image description here

Better Approach than If

I have some Optional parameters in my application and I have to mount command with these parameters, so, now I'm using IF

class MergeBuilder(mergeBuilderConfig: MergeBuilderConfig) {

  def makeMergeCommand(): DeltaMergeBuilder = {

    val mergeSintax = mergeBuilderConfig.primaryKey
      .map(column => s"destination.$column = updates.$column")
      .mkString(" and ") + (if (!mergeBuilderConfig.partitionFilter.isEmpty) {
                              " and " + mergeBuilderConfig.partitionFilter
                            } else {
                              ""
                            })

    val mergeCommand =
      mergeBuilderConfig.deltaTable.alias("destination").merge(mergeBuilderConfig.sparkDf.alias("updates"), mergeSintax)

    if (mergeBuilderConfig.operationType == "upsert" && mergeBuilderConfig.setExpression.isEmpty) {
      mergeCommand
        .whenMatched(condition = mergeBuilderConfig.updateCondition.get)
        .updateAll(
        )
        .whenNotMatched()
        .insertAll()
    } else if (mergeBuilderConfig.operationType == "upsert" && !mergeBuilderConfig.setExpression.isEmpty) {
      mergeCommand
        .whenMatched(condition = mergeBuilderConfig.updateCondition.toString)
        .updateExpr(set = mergeBuilderConfig.setExpression.get)
    } else {
      mergeCommand.whenNotMatched().insertAll()
    }
  }
}

I will have more command Options, Do you have any idea how to avoid these Ifs?

Passing an extra parameter along method chain

I have several microservices on Spring Boot and one of them is designed for logging processes from other services. In the services that work with it, it is necessary to pass the session identifier variable along the chain of called methods. Methods can be called asynchronously via @Assync. The session can be started by the user through the controller or by schedule.

Example:

public void method1(..., Long sessionId) {
    ...
    if (condition) {
        obj.method2(..., Long sessionId);
    } else {
        method3(..., Long sessionId);
    }
}

My problem is that I would like to get away from explicitly passing a given variable to each method from the chain. Maybe there is some pattern or another solution.

Design pattern to evaluate conditions represented in JSON object structure

I have a group of conditions with AND or OR keys. I have to evaluate those conditions. Along with these conditions, I will be provided with a JSON object, which has data or values for the keys specified in "field" of conditions.

For example, in below conditions I have "field":"email", so I will receive the following JSON object as input:

{
"email":"abc@xyz.com"
}

If operator is EMPTY, it means I have to fetch value based on the "field" value in JSON and check if it is empty or not.

JSONObject conditions = {
    "conditions": [{
        "OR": [{
                "field": "email",
                "operator": "VALID_DOMAINS"
            },
            {
                "field": "email",
                "operator": "EMPTY"
            }
        ]
    }]
}

Only "AND" and "OR" operators will be present and conditions are dynamic, meaning those needs to be fetched from the database.

Note: the conditions will be boolean expressions only and it will be complex and nested conditions.

Design patterns in .net

We have multiple design patterns but when we develop the site , rarely we are using those as lack of understanding on this.

Can you please tell us the design pattern name with purpose like composite design pattern always use in tree hierarchy example.

Thanks! Please share your views.

Replace multiple values in data table column after multiple pattern match

Here is a snippet that could help a few 'R beginners' like me: I was referring to this thread for a need on my melted data table

Replace entire string anywhere in dataframe based on partial match with dplyr

I was looking for an easy way of replacing an entire string in one of the columns in data table with a partial match string. I could not find a straight fit on the forum , hence this post:

dt<-data.table(x=c("A_1", "BB_2", "CC_3"),y=c("K_1", "LL_2", "MM_3"),z=c("P_1","QQ_2","RR_3")
> dt
      x    y    z
1:  A_1  K_1  P_1
2: BB_2 LL_2 QQ_2
3: CC_3 MM_3 RR_3

replace multiple values in col y with multiple patterns to match :

dt[,2]<-str_replace_all(as.matrix(dt[,2]),c("K_.*" = "FORMULA","LL_.*" = "RACE","MM_.*" = "CAR"))

using as.matrix() on column excludes the warning on input to the str_replace_all() function The result is :

> dt[,2]<-str_replace_all(as.matrix(dt[,2]),c("K_.*" = "FORMULA","LL_.*" = "RACE","MM_.*" = "CAR"))
> dt
      x       y    z
1:  A_1 FORMULA  P_1
2: BB_2    RACE QQ_2
3: CC_3     CAR RR_3
>

very un-elegant, but worked for me, when the column data is large, this seemed to be a quick solution

Requires library(stringr) Any suggestions to improve are appreciated.

samedi 21 novembre 2020

vue application best practice/pattern to display data with people-friendly label?

A high-level vue application question:

A little background:

  • small team, still learning vue
  • creating a new large reasonably complex vue app from scratch
  • vue-cli scaffolded (vue 2, veux, router, i118n, bootstrapVue)
  • there are many different application entities – e.g. "user", “product”, etc.
  • there are many of each item, and each has a data record (from a db) that includes a number of boolean fields such as "active", “enabled”, “is_sensitive”.
  • item data displays in many different contexts, including: search results, table lists (e.g. browse), individual landing views for each (an item detail page), as well as ancillary lists (e.g. “A related item:”

The key problem:
In every display situation, the boolean values should to be translated from machine-friendly to people-friendly terminology.

The appropriate human-friendly term depends on the field itself (so there is no single translation for all fields).

Example: Machine-friendly data:

[
    {
        name: “Megaphone”,
        is_embarrassing: false,
        active: false,
    },
    {
        name: “Wankel Rotary Engine”,
        is_embarrassing: true,
        active: true,
    },
]

Human-friendly list:

+----------------------+----------+---------------------+
| Name                 | Active?  | Embarrassing?       |
+----------------------+----------+---------------------+
| Megaphone            | Inactive | Not embarassing     |
| Wankel Rotary Engine | Active   | Item is Embarassing |
+----------------------+----------+---------------------+

The key question:
What is the best way to solve this in a scalable, efficient, elegant, sensible way?

I have thought of a couple of options…neither of these feel scalable nor elegant, and are brittle.

(1) sequence of in-line v-if conditions within the component view template

    <p v-if=“item.property.is_embarrassing">
        Item is Embarrassing
    </p>
    <p v-else>
        Not embarassing
    </p>

(2) computed properties in the component

    <p>
        
    </p>
    detailsPropertyEmbarrassing() {
        return item.property.is_embarrassing ? “Item is Embarrassing : “Not Embarrassing”;
    },

I have also been noodling over the idea of some sort of Map that is imported along with the data and used to get the right labels, but I haven’t completely worked that out yet.

What is a solution for transforming data fields to people-friendly labels across an entire application, for a variety of different display situations?

(Side note: I may also need to transform the field in other ways, such as truncating length…)

And is there a way to establish this globally in the app in a manner that is scalable, both technically and organizationally, so that new components can display as desired, near-automatically?

This seems like a basic fundamental need in any app of size, not just vue, so I feel like this has been/has to have been solved before, but either I cannot find the right research keywords or am missing something obvious.

Thanks in advance!

Python: Better library/class design for intellisense

This is the best analogy I can come up with, similar to my actual problem, and its a bit more interesting, especially for a car enthusiast. Basically I have a library/class before that just takes string as its parameter. The problem with this is that its a bit hard for the users, because they have to know the string/options available to use it. Granted the backend could provide more error descriptions stating what the issue is/or whats available.

In order to make it a bit easier for users to use the library/class, I figured using an enum will help, and users can utilize intellisense to provide what options are available. The below example work fairly well, but the problem is that, it can provide a wrong model for a chosen make. For example Mclaren shouldnt have an F8 model, yet with this implementation, a user can select that.

Yes, the backend can do that check and provide an error stating this Model does not exist for this Make. But was wondering if there is a better way to design this, and package/provide it for users to easily use the library/class. Or is my best bet providing a superset of Make and Model (like my sample code), and the backend just have to do the validation?

In short, the main goals are:

  1. How to help users use the library, and provide them available options thru intellisense
  2. Still be able to have the string representation of the class the same. In this example, basically just have the same print out of the class as before.

sample code:

from enum import Enum


class Make(Enum):
    mclaren = "Mclaren"
    lamborghini = "Lamborghini"
    ferrari = "Ferrari"


class Model(Enum):
    # Mclaren models
    p1 = "P1"
    gt = "Gt"

    # Lamborghini models
    aventador = "Aventador"
    huracan = "Huracan"

    # Ferrari models
    f8 = "F8"
    sf90 = "SF90"


class Car():
    def __init__(self, make, model, option1=None, option2=None):
        self.make = make
        self.model = model
        self.option1 = option1
        self.option2 = option2

    def print_val(self, item):
        if isinstance(item, Enum):
            return item.value
        else:
            return item

    def __str__(self):
        return f"Car: Make: {self.print_val(self.make)} " \
               f"Model: {self.print_val(self.model)} " \
               f"Option1: {self.print_val(self.option1)} " \
               f"Option2: {self.print_val(self.option2)}"


print("String style")
a = Car(make="Mclaren", model="P1")        # example of user's code
print(a)

print("Class style")
a = Car(make=Make.mclaren, model=Model.p1) # example of user's code
print(a)

Output:

String style
Car: Make: Mclaren Model: P1 Option1: None Option2: None
Class style
Car: Make: Mclaren Model: P1 Option1: None Option2: None

Algorithm to get suggestions from items related to another

I would like to get some tips to create an efficient algorithm.

This is the scenario. I'm using rails and sqlite.

There're articles with many custom properties (or rows), in a one-to-many relation. Some properties are the same and are in common among articles and often many articles have three or more equal properties.

When creating a new article and inserting the first property, I would the app to suggest the most frequent properties existing in articles related to the first property in the other articles. So, after adding the second property, the app should suggest the most frequent properties existing in articles that contain both the two properties.

Any idea? Some libs already fitting it?

vendredi 20 novembre 2020

How can create a reyclerview like that?

Hi Im a newbie on Android studio and java , I have a bunch of images that I must show to my user on log and I wanted to use a recyclerview to show image with a good UI . I found this one on Driblle that I really love and I would like to implement it on my app . How can I do that ? Here a link of what I want to achieve

To Many Parameters Scala

I have an application that has a single EntryPoint, its a library to automate some data engineers stuffs.

case class DeltaContextConfig(
  primaryKey: List[String],
  columnToOrder: String,
  filesCountFirstBatch: Int,
  destinationPath: String,
  sparkDf: DataFrame,
  sparkContext: SparkSession,
  operationType: String,
  partitionColumn: Option[String] = None,
  tableName: String,
  databaseName: String,
  autoCompaction: Option[Boolean] = Option(true),
  idealFileSize: Option[Int] = Option(128),
  deduplicationColumn: Option[String] = None,
  compactionIntervalTime: Option[Int] = Option(180),
  updateCondition: Option[String] = None,
  setExpression: Option[String] = None
)

This is my case class, my single Entrypoint.

After that all these parameters are pass to other objects, I have objects to write in Datalake, to Compact files and so on. And these objects use some of these parameters, for example, I have a DeltaWriterConfig object:

DeltaWriterConfig(
  sparkDf = deltaContextConfig.sparkDf,
  columnToOrder = deltaContextConfig.columnToOrder,
  destinationPath = deltaContextConfig.destinationPath,
  primaryKey = deltaContextConfig.primaryKey,
  filesCountFirstBatch = deltaContextConfig.filesCountFirstBatch,
  sparkContext = deltaContextConfig.sparkContext,
  operationType = deltaContextConfig.operationType,
  partitionColumn = deltaContextConfig.partitionColumn,
  updateCondition = deltaContextConfig.updateCondition,
  setExpression = deltaContextConfig.setExpression
)

I use the DeltaWriterConfig, to pass these parameters to my class DeltaWriter. I was creating all these configs objects on the MAIN, but I think it is not good, because, I have 3 Config Objects to populate, so I have 3 big constructors on the application main.

Is there any pattern to solve this?

thank you

Update- request user input for application [closed]

I am new to coding and I have created a main method. Im looking for the system to ask the users for input which greeting card do they want. My code works but it runs one after the other. The question would be"Which greeting card do you want?" and they get to pick which one.

I have worked the code so and it shows all of the cards at once. Im trying to get it to be specific to the users input and only show that output. e.g I want a bday card and then show the bday card. Not the other ones

I'd appreciate your help thanks so much.

public class GreetingCardApp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        //main method
        //declare and create an instance of wedding card using the construction design pattern

        GreetingCard cardWedding = new wedding();
        cardWedding.completeCard();
       
        GreetingCard cardXmasCard = new XmasCard();
        cardXmasCard.completeCard();

    }

}

Does anyone know a repo where I can find implementations of design patterns in real projects (not for educational purposes)?

I'm mostly interested in Python implementations and mainly in the template method pattern. But any language or pattern would be great!

Is it possible to have multiple subjects in Observer pattern?

I've been working on the Observer pattern, with a one-to-many event. In this case, are multiple classes notified, i.e. more than one observer from one subject? Conversely, could there be more than one subject that I want to ask? Does this situation exceed the Observer pattern and create a different pattern?

Imagine a publishing house that prints newspapers, magazines and books. Users can subscribe to whatever they want. For example, a user might subscribe only to books or to books and newspapers at the same time. Each time a new one of these types is released, the relevant users should be notified. Users who are not registered should not be notified. In other words, if the user is only registered for books, a notification will not be sent for newspapers.

In this example, is the subject the publishing house? Or would books, newspapers, and magazines be separate subjects?

Example of design pattern Factory

This is the code I have, is this a factory DP and what does it do i have trouble understanding it

def chain_factories(field_factories, model_name): """ Instanciate a generator by calling all the field factories. """ generator = root_factory() for (fname, field_factory) in field_factories: generator = field_factory(generator, fname, model_name) return generator

def root_factory(): """ Return a generator with empty values dictionaries (except for the flag __complete). """ yield {'__complete': False} while True: yield {'__complete': True}

def randomize(vals, weights=None, seed=False, formatter=format_str, counter_offset=0): """ Return a factory for an iterator of values dicts with pseudo-randomly chosen values (among vals) for a field.

:param list vals: list in which a value will be chosen, depending on `weights`
:param list weights: list of probabilistic weights
:param seed: optional initialization of the random number generator
:param function formatter: (val, counter, values) --> formatted_value
:param int counter_offset:
:returns: function of the form (iterator, field_name, model_name) -> values
:rtype: function (iterator, str, str) -> dict
"""
def generate(iterator, field_name, model_name):
    r = Random('%s+field+%s' % (model_name, seed or field_name))
    for counter, values in enumerate(iterator):
        val = r.choices(vals, weights)[0]
        values[field_name] = formatter(val, counter + counter_offset, values)
        yield values
return generate

def cartesian(vals, weights=None, seed=False, formatter=format_str, then=None): """ Return a factory for an iterator of values dicts that combines all vals for the field with the other field values in input.

:param list vals: list in which a value will be chosen, depending on `weights`
:param list weights: list of probabilistic weights
:param seed: optional initialization of the random number generator
:param function formatter: (val, counter, values) --> formatted_value
:param function then: if defined, factory used when vals has been consumed.
:returns: function of the form (iterator, field_name, model_name) -> values
:rtype: function (iterator, str, str) -> dict
"""
def generate(iterator, field_name, model_name):
    counter = 0
    for values in iterator:
        if values['__complete']:
            break  # will consume and lose an element, (complete so a filling element). If it is a problem, use peekable instead.
        for val in vals:
            yield {**values, field_name: formatter(val, counter, values)}
        counter += 1
    factory = then or randomize(vals, weights, seed, formatter, counter)
    yield from factory(iterator, field_name, model_name)
return generate

def iterate(vals, weights=None, seed=False, formatter=format_str, then=None): """ Return a factory for an iterator of values dicts that picks a value among vals for each input. Once all vals have been used once, resume as then or as a randomize generator.

:param list vals: list in which a value will be chosen, depending on `weights`
:param list weights: list of probabilistic weights
:param seed: optional initialization of the random number generator
:param function formatter: (val, counter, values) --> formatted_value
:param function then: if defined, factory used when vals has been consumed.
:returns: function of the form (iterator, field_name, model_name) -> values
:rtype: function (iterator, str, str) -> dict
"""
def generate(iterator, field_name, model_name):
    counter = 0
    for val in vals: # iteratable order is important, shortest first
        values = next(iterator)
        values[field_name] = formatter(val, counter, values)
        values['__complete'] = False
        yield values
        counter += 1
    factory = then or randomize(vals, weights, seed, formatter, counter)
    yield from factory(iterator, field_name, model_name)
return generate

def constant(val, formatter=format_str): """ Return a factory for an iterator of values dicts that sets the field to the given value in each input dict.

:returns: function of the form (iterator, field_name, model_name) -> values
:rtype: function (iterator, str, str) -> dict
"""
def generate(iterator, field_name, _):
    for counter, values in enumerate(iterator):
        values[field_name] = formatter(val, counter, values)
        yield values
return generate

def compute(function, seed=None): """ Return a factory for an iterator of values dicts that computes the field value as function(values, counter, random), where values is the other field values, counter is an integer, and random is a pseudo-random number generator.

:param function function: (values, counter, random) --> field_values
:param seed: optional initialization of the random number generator
:returns: function of the form (iterator, field_name, model_name) -> values
:rtype: function (iterator, str, str) -> dict
"""
def generate(iterator, field_name, model_name):
    r = Random('%s+field+%s' % (model_name, seed or field_name))
    for counter, values in enumerate(iterator):
        val = function(values=values, counter=counter, random=r)
        values[field_name] = val
        yield values
return generate

def randint(a, b, seed=None): """ Return a factory for an iterator of values dicts that sets the field to the random integer between a and b included in each input dict.

:param int a: minimal random value
:param int b: maximal random value
:returns: function of the form (iterator, field_name, model_name) -> values
:rtype: function (iterator, str, str) -> dict
"""
def get_rand_int(random=None, **kwargs):
    return random.randint(a, b)
return compute(get_rand_int, seed=seed)

return []