dimanche 28 février 2021

What Java design pattern fits the scenario of adding a user to multiple systems based on csv values?

I am working on a project where I need to add users to multiple systems (active directory, a database, & Sisense) based on data received from a spreadsheet. I've coded can get the data input correctly into each system, but I am struggling to figure out how to organize my code, in terms of what design pattern to use.

I have a model class for each component that contains the field each system needs:

  1. ActiveDirectoryUser
  2. SisenseUser
  3. DatabaseUser

Then, I have what I call the worker class for each of these that actually does creates the user in the system. ActiveDirectoryWorker SisenseWorker DatabaseWorker

The basic flow of my code is

  1. Read in each line from the spreadsheet
  2. Validate the input is valid.
  3. Create a instance of each model class that contains the appropriate fields.
  4. Call the individual worker classes that control how the user get added to the respective system. The model instance will be passed into this class.

I've read up on some of the various design patterns, but none of the explanations are in "plain" English. Still learning the ropes here a bit, so I'd appreciate someone suggesting a model that fits my scenario.

How to think about OOP design choices for code re-usability and extensibility in Python?

This question is messy, and I know it needs cleaning up. Rather than vote to close and move on, please help me structure it correctly. I know the rules, but I don't know how to get my question answered by following them.

Context:

I've got this composition (new vocabulary word for me) of an OneHotEncoder object:

class CharEncoder:

    characters = cn.ALL_LETTERS_ARRAY

    def __init__(self):
        self.encoder = OneHotEncoder(sparse=False).fit(self.characters.reshape(-1, 1))
        self.categories = self.encoder.categories_[0].tolist()

    def transform(self, word):
        word = np.array(list(word)).reshape(-1, 1)
        word_vect = self.encoder.transform(word)
        return word_vect

    def inverse_transform(self, X):
        word_arr = self.encoder.inverse_transform(X).reshape(-1,)
        return ''.join(word_arr)

As you can see it has a class attribute characters which is essentially an array of all the ASCII characters plus some punctuation.

I want to make this CharEncoder class useful for more than just ASCII. Maybe someone else would really like to use a different character set, and I want to allow them to do so. Or maybe they want to encode entire words instead of individual letters... who knows!?

My problem:

I feel like there are so many design choices here that could make this code re-usable for a slightly different task. I feel overwhelmed.

  1. Do I make the character set a class attribute or an instance attribute?
  2. Do I write getters and setters for the character set?
  3. Do I instead write some parent class, and sub-classes for different character sets.
  4. Or do I make users pass their own OneHotEncoder object to my class, and not worry about it myself?

My question:

What are some considerations that might help guide my design choice here?

samedi 27 février 2021

Page Object class all share similar web tables, but tables on certain pages have a couple extra components. How should I combat this?

I have 4 page object classes to represent 4 operational pages. Each page contains similar table with a few having extra components like extra buttons.

Currently I have I'm faced with "large class" to handle the different variations of the table.

I have it conditioned to simply check the URL then continue performing actions on the table for that page.

Goal: I would like to figure out how I should refactor my code in a way that I can handle the table when I hit either of the pages without having so many page objects in one class and if conditions duplicating code.

Example: 3 pages use table 1 which contains an extra button

1 page uses table 2 which does not have an extra button

public class Table
{

    public readonly TableMap Map;
    public class Table()
    {
        Map = new TableMap();
    }
  
    public void OpenDoc()
    {
        var pageCurrentUrl = Driver.Url;
        switch(pageCurrentUrl)
        {
 
            case URLOne:
            case URLTwo:
            case URLThree:
               //open doc within table 1
               break;
            case URLFour:
               //open doc within table 2
               break;
        }
    }
}   

public class TableMap
{
    //table for three pages
    public class IWebElement ButtonOneTable1 => Driver.FindElement(By.CssSelector("element"));
    public class IWebElement ButtonTwoTable1 => Driver.FindElement(By.CssSelector("element"));
    public class IWebElement RowsTable1 => Driver.FindElement(By.CssSelector("element"));
    public class IWebElement ColumnsTable1 => Driver.FindElement(By.CssSelector("element"));
    
    //table for 1 page
    public class IWebElement ButtonOneTable2 => Driver.FindElement(By.CssSelector("element"));
    public class IWebElement RowsTable2 => Driver.FindElement(By.CssSelector("element"));
    public class IWebElement ColumnsTable2 => Driver.FindElement(By.CssSelector("element"));

}

Essentially I have way to many page objects in this class and I have code duplicate in that switch statement that I'd like to refactor.

Managing order processing of different types of items

Currently We have two step order confirmation:

  1. Create order in database with paid field as 0
  2. Accept request of user payment and on successful payment update paid to total order amount

I am having problem following this mehtod for other type of items introduced later.

So,

Item A is a service. Order is created in the database and a razorpay order is also created. It is a service based item so a booking is also created for this item. It's upto the user to pay anytime he wasnts.

On other hand,

Item B is not a service. So, Order is created in the database and a razorpay order is also created. But user has to pay to complete the order.

The problem is if booking is canceled for a service or a order is unpaid for combos, those orders just hangs in the db consuming space.

So I end up with having four APIs for handling order and payment of both types:

  1. /orders/service
  2. /payments/service
  3. /orders/combo
  4. /payments/combo

It's clear the above list will just grow if new items were introduced in the system.

Is there anyway I could combine them into single step?

I am using razorpay as payment gateway, which needs a unique order number so I have to create order in database before creating a razorpay order ot process payment.

Links: Razorpay Payment Flow

Reduce nesting when cleaning up multiple non-Closeable resources

I have a Closeable that needs to clean up multiple resources in the close() method. Each resource is a final class that I cannot modify. None of the included resources are Closeable or AutoCloseable. I also need to call super.close(). So it appears that I cannot handle any of the resources* using try-with-resources. My current implementation looks something like this:

public void close() throws IOException {
    try {
        super.close();
    } finally {
        try {
            container.shutdown();
        } catch (final ShutdownException e) {
            throw new IOException("Handling ShutdownException: ", e);
        } finally {
            try {
                client.closeConnection();
            } catch (final ConnectionException e) {
                throw new IOException("Handling ConnectionException: ", e);
            }
        }
    }
}

I'd prefer a solution with less crazy nesting but I can't figure out how to take advantage of try-with-resources or any other features to do that. Code sandwiches don't seem to help here since I'm not using the resources at all, just cleaning them up. Since the resources aren't Closeable, it's unclear how I could use the recommended solutions in Java io ugly try-finally block.

* Even though the super class is Closeable, I cannot use super in a try-with-resources because super is just syntactic sugar and not a real Java Object.

2D animation of plotting flow velocities over dunes with pcolormesh

I would like to plot an animation of flow velocities over dunes. I am experimenting with different dune lee angles, and plotting velocity patterns over many dune lee angles requires too much pages. In the example I work with dune lee angles of 15, 20 and 25 degrees, however I will use more different dune lee angles (16 in total) so an animation is hugely preferred over 16 plots.

Therefore, I would like to use the animation function to get a gif that provides flow patterns over dunes with different dune lee angles just in one plot.

However, I could not get to the solution that gives me this animation. So far I get the error: AttributeError: 'list' object has no attribute 'ndim'

The 3 individual velocity pictures (for dune lee angles of 15, 20 and 25, respectively) should look like the following (the vertical axis is overlapping too much but I think I can fix that on my own):

velocity patterns over 15 degrees

velocity patterns over dunes with 20 degrees

velocity patterns 25 degrees

these pictures should be replaced by each other continuosly.

And the code I wrote so far:

#first import all needed tools

import numpy as np
from math import *
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.animation as animation

#import the 9 csv datafiles with instanteneous velocities, filter the imported datafiles per column and transpose the files

dat = pd.read_csv(r'/Users/peterwesterman/Downloads/bistatic_plot_analysis_20210219_111339 (1).csv', sep='\t',skiprows=1, header=None)
df = pd.DataFrame(dat)
dfcol = pd.DataFrame(dat, columns=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120])
dfcol1 = dfcol.T
df1 = np.array(dfcol1)
dat2 = pd.read_csv(r'/Users/peterwesterman/Downloads/bistatic_plot_analysis_20210219_111410.csv', sep='\t',skiprows=1, header=None)
df2 = pd.DataFrame(dat2)
dfcol2 = pd.DataFrame(dat2, columns=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120])
dfcol2 = dfcol2.T
df2 = np.array(dfcol2)
dat3 = pd.read_csv(r'/Users/peterwesterman/Downloads/bistatic_plot_analysis_20210219_111456.csv', sep='\t',skiprows=1, header=None)
df3 = pd.DataFrame(dat3)
dfcol3 = pd.DataFrame(dat3, columns=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120])
dfcol3 = dfcol3.T
df3 = np.array(dfcol3)
dat4 = pd.read_csv(r'/Users/peterwesterman/Downloads/bistatic_plot_analysis_20210219_111553.csv', sep='\t',skiprows=1, header=None)
df4 = pd.DataFrame(dat4)
dfcol4 = pd.DataFrame(dat4, columns=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120])
dfcol4 = dfcol4.T
df4 = np.array(dfcol4)
dat5 = pd.read_csv(r'/Users/peterwesterman/Downloads/bistatic_plot_analysis_20210219_111706.csv', sep='\t',skiprows=1, header=None)
df5 = pd.DataFrame(dat5)
dfcol5 = pd.DataFrame(dat5, columns=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120])
dfcol5 = dfcol5.T
df5 = np.array(dfcol5)
dat6 = pd.read_csv(r'/Users/peterwesterman/Downloads/bistatic_plot_analysis_20210219_111833.csv', sep='\t',skiprows=1, header=None)
df6 = pd.DataFrame(dat6)
dfcol6 = pd.DataFrame(dat6, columns=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120])
dfcol6 = dfcol6.T
df6 = np.array(dfcol6)
dat7 = pd.read_csv(r'/Users/peterwesterman/Downloads/bistatic_plot_analysis_20210219_112100.csv', sep='\t',skiprows=1, header=None)
df7 = pd.DataFrame(dat7)
dfcol7 = pd.DataFrame(dat7, columns=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120])
dfcol7 = dfcol7.T
df7 = np.array(dfcol7)
dat8 = pd.read_csv(r'/Users/peterwesterman/Downloads/bistatic_plot_analysis_20210219_112313.csv', sep='\t',skiprows=1, header=None)
df8 = pd.DataFrame(dat8)
dfcol8 = pd.DataFrame(dat8, columns=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120])
dfcol8 = dfcol8.T
df8 = np.array(dfcol8)
dat9 = pd.read_csv(r'/Users/peterwesterman/Downloads/bistatic_plot_analysis_20210219_112540.csv', sep='\t',skiprows=1, header=None)
df9 = pd.DataFrame(dat9)
dfcol9 = pd.DataFrame(dat9, columns=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120])
dfcol9 = dfcol9.T
df9 = np.array(dfcol9)

#make numpy arrays of x and z axis, z axis is the (vertical) cell distance that is measured, (streamwise) x data is measured at x = 0.1, 0.2 and 0.3 (m).
#create empty 2 dimensional velocity  numpy array with dimensions similar to x and z axis
#initialise pcolormesh plot

x = []
z = []
for i in df1[:]:
    z.append(i[0])
x.append(0.1)
x.append(0.2)
x.append(0.3)
    
x = np.array(x)
z = np.array(z)
v0 = np.empty((60,3))

fig, ax = plt.subplots(figsize=(5, 5))
fig.suptitle('flow velocity over dune')
dunevelocity = ax.pcolormesh(x, z, v0, shading="gouraud")
fig.colorbar(dunevelocity)
V = []

#initialise changing data

def init():
    del V[:]
    dunevelocity.set_array(V)
    return dunevelocity

#yield time series of velocity data

def velocity():
    for lee in np.arange(15,30,5):
        if lee == 15:
            #first velocity time series
            v1x1 = []
            v1x2 = []
            v1x3 = []
            for i in df1[:]:
                df11 = np.array(i)
                VelocitySum = 0
                VelocityAveraged = 0
                N = 0
                alleZ = []
                for j in df11[3:103]:
                    N += 1
                    VelocitySum += float(j)
                    VelocityAveraged = VelocitySum/N
                    alleZ.append(VelocityAveraged)
                v1x1.append(alleZ[-1])
            for i in df2[:]:
                df22 = np.array(i)
                VelocitySum = 0
                VelocityAveraged = 0
                N = 0
                alleZ = []
                for j in df22[3:203]:
                    N += 1
                    VelocitySum += float(j)
                    VelocityAveraged = VelocitySum/N
                    alleZ.append(VelocityAveraged)
                v1x2.append(alleZ[-1])
            for i in df3[:]:
                df33 = np.array(i)
                VelocitySum = 0
                VelocityAveraged = 0
                N = 0
                alleZ = []
                for j in df33[5:305]:
                    N += 1
                    VelocitySum += float(j)
                    VelocityAveraged = VelocitySum/N
                    alleZ.append(VelocityAveraged)
                v1x3.append(alleZ[-1])

#transpose velocities of first timeseries to right 2D place:
            index = 0
            Vtime1 = np.empty(1)
            for value in v1x1[:]:
                index += 1
                Vtime1 = np.insert(Vtime1, index, value)
            index = 0
            for value in v1x2[:]:
                index += 2
                Vtime1 = np.insert(Vtime1, index, value)
            index = 0
            for value in v1x3[:]:
                index += 3
                Vtime1 = np.insert(Vtime1, index, value)

            Vtime1 = Vtime1[1:]
            Vtime1 = Vtime1.reshape(60,3)

        elif lee == 20:
            #second velocty time series
            v2x1 = []
            v2x2 = []
            v2x3 = []
            for i in df4[:]:
                df44 = np.array(i)
                VelocitySum = 0
                VelocityAveraged = 0
                N = 0
                alleZ = []
                for j in df44[5:405]:
                    N += 1
                    VelocitySum += float(j)
                    VelocityAveraged = VelocitySum/N
                    alleZ.append(VelocityAveraged)
                v2x1.append(alleZ[-1])
            for i in df5[:]:
                df55 = np.array(i)
                VelocitySum = 0
                VelocityAveraged = 0
                N = 0
                alleZ = []
                for j in df55[3:503]:
                    N += 1
                    VelocitySum += float(j)
                    VelocityAveraged = VelocitySum/N
                    alleZ.append(VelocityAveraged)
                v2x2.append(alleZ[-1])
            for i in df6[:]:
                df66 = np.array(i)
                VelocitySum = 0
                VelocityAveraged = 0
                N = 0
                alleZ = []
                for j in df66[5:605]:
                    N += 1
                    VelocitySum += float(j)
                    VelocityAveraged = VelocitySum/N
                    alleZ.append(VelocityAveraged)
                v2x3.append(alleZ[-1])

            index = 0
            Vtime2 = np.empty(1)
            for value in v2x1[:]:
                index += 1
                Vtime2 = np.insert(Vtime2, index, value)
            index = 0
            for value in v2x2[:]:
                index += 2
                Vtime2 = np.insert(Vtime2, index, value)
            index = 0
            for value in v2x3[:]:
                index += 3
                Vtime2 = np.insert(Vtime2, index, value)

            Vtime2 = Vtime2[1:]
            Vtime2 = Vtime2.reshape(60,3)

        #third velocity time series
        elif lee == 25:
            v3x1 = []
            v3x2 = []
            v3x3 = []
            for i in df7[:]:
                df77 = np.array(i)
                VelocitySum = 0
                VelocityAveraged = 0
                N = 0
                alleZ = []
                for j in df77[5:705]:
                    N += 1
                    VelocitySum += float(j)
                    VelocityAveraged = VelocitySum/N
                    alleZ.append(VelocityAveraged)
                v3x1.append(alleZ[-1])
            for i in df8[:]:
                df88 = np.array(i)
                VelocitySum = 0
                VelocityAveraged = 0
                N = 0
                alleZ = []
                for j in df88[3:803]:
                    N += 1
                    VelocitySum += float(j)
                    VelocityAveraged = VelocitySum/N
                    alleZ.append(VelocityAveraged)
                v3x2.append(alleZ[-1])
            for i in df9[:]:
                df99 = np.array(i)
                VelocitySum = 0
                VelocityAveraged = 0
                N = 0
                alleZ = []
                for j in df99[3:903]:
                    N += 1
                    VelocitySum += float(j)
                    VelocityAveraged = VelocitySum/N
                    alleZ.append(VelocityAveraged)
                v3x3.append(alleZ[-1])

            index = 0
            Vtime3 = np.empty(1)
            for value in v3x1[:]:
                index += 1
                Vtime3 = np.insert(Vtime3, index, value)
            index = 0
            for value in v3x2[:]:
                index += 2
                Vtime3 = np.insert(Vtime3, index, value)
            index = 0
            for value in v3x3[:]:
                index += 3
                Vtime3 = np.insert(Vtime3, index, value)

            Vtime3 = Vtime3[1:]
            Vtime3 = Vtime3.reshape(60,3)
    V = [Vtime1, Vtime2, Vtime3]
    yield V, lee 

def run(array):  
    # update the data
    V, lee = array
    dunevelocity.set_array(V)
    ax.set_title(f"flow velocities over dunes with lee angle of: {lee} degrees")
    return dunevelocity

anii = animation.FuncAnimation(fig, run, velocity,interval=50,init_func=init)
plt.show()
anii.save('velocity patterns.gif', writer='pillow', fps=0.5)

What is the best design patterns(Factory Pattern, Abstract Factory Pattern and Singleton Pattern) for sales management system(java)

What is the best design patterns(Factory Pattern, Abstract Factory Pattern, and Singleton Pattern) for the sales management system(java)

Using Enum to represent VehicleType in cab Booking system

I am working on low level design of cab booking type of system and feeling stuck at modelling Vehicle in Booking class.I came up with following design.

Class Vehicle
{
    
    
}
Class Car extends Vehicle
{
    
}
Classs Bike extends Vehicle
{
    
}
Class Auto extends Vehicle
{
    
}
Class Booking
{
    int number;
    ...
    ....
    Vehicle Vehicle;
    VehicleType type;
    ...
    ...
}
enum VehicleType
{
    CAR,
    BIKE,
    AUTO
    
}

Now to see, which vehicle is used for booking, we can see the VehicleType from booking and then typecast the vehicle to that object(CAR,BIKE,AUTO).Is it a bad way model?

In general, if we have a reference to parent, and we want to know specific child class which is holds,is this a good way to do?Are there alternate approaches ?

Python - User registration class?

I am working on a simple CRUD app as a personal project using Flask. I am currently working on the user blueprint and trying to use as less as libraries as I could (that's why I am using FlaskWTF for example). However, I am wondering if my RegisterForm make sense or I should not have to create a specific class for userRegistration?

user/views.py

user = Blueprint('user', __name__, template_folder='templates')

@user.route('/register')
def login():
    return render_template('register.html')

@user.route('/new-user',methods = ['POST'])
def register_user():
    form = RegisterForm(request.form.to_dict())
    if not form.validate_new_user:
        #ask to user to fix the issues
    return render_template('')

user/forms.py

class RegisterForm():
    def __init__(self, form_data):
        self.email = form_data.get("email")
        self.password = form_data.get("psw")
        self.password_two = form_data.get("psw-repeat-two")
        print(form_data)
        
    def is_new_user():
        #if self.email already in the database.users then return False
        return True 
    
    def both_password_match():
        if password != password_two:
            return False 
        return True
        
    def is_password_strong_enough():
        if len(self.password) < 8:
            return False
        elif re.search('[0-9]',self.password) is None:
            return False
        elif re.search('[A-Z]',self.password) is None: 
            return False
        return True
                   
    def validate_new_user():
        if self.is_new_user and self.both_password_match and self.is_password_strong_enough:
            ## register new user 
        

class LoginForm():
    ...

Why set up Dependency providers in angular?

I have created few services in angular with provideIn as root using the following code.

@Injectable({
    providedIn: 'root'
}

This makes the service available to the whole application and I can import it anywhere I like. This seems very easy to do and is very intuative. But I was reading angular docs and came across Angular Dependency providers. I understand the concept behind it is to expose the service only to those components that need it. But I don't understand whats the use of this? We can make service available at root level and access where ever needed. Are there any optimisations benefit of configuring depenceny providers or is it merely because of security reasons or for any other reason?

vendredi 26 février 2021

In Lua, what is the best way to explicitly determine when something should be a module?

I'm have a lot of trouble getting started on a project because I cannot tell when I should make something a module or when it should be a variable, that is local to the instance I'm creating, with it's own set of related functions.

My gut instinct is to turn nearly everything in to a module, but I know this not only is unnecessary but actually harmful to creating clear, distinct code. I'll give an example but a small bit of information is that I'm using lua and a library to create a game.

So most "objects" in my game are going to have a name and a description, but I don't really feel that either of these are going to need modules as they will work just fine as variables accessed with setter/getter functions within the object if necessary. But my brain keeps questioning if maybe I should have a description module because then I could setup and expand descriptions more to exist as more than just simple strings. I don't have any current intentions to do so, but that's a lot of code to rewrite if I hard code descriptions for every variable in the game and then decide I want or NEED to expand the utility/functionality of descriptions.

This next part is not exactly related to this precise question and is a bit personal, feel free to skip this when answering.

I've been programming for nearly 20 years now, all sorts of different languages, all sorts of different programs and more and more I find myself questioning things like this. Seeing too much infinite possibility in the way to do things but never seeing the single best way that works for me and I get stuck in analysis paralysis and write little to no code, never getting past my psuedo-code planning phase.

Why is the Factory pattern not needed in Haskell? And how are the needs that pattern addresses in OOP addressed in Haskell?

I've read this question about the Abstract factory pattern, but the only answer to it tries to emulate in Haskell what one would in OOP languages (although the forword is along the lines you don't need it in Haskell).

On the other hand, my intention is not really to force an OOP-specific pattern on a Functional language as Haskell. Quite the opposite, I'd like to understand how Haskell addresses the needs that in OOP are addressed via the Factory pattern.

I have the feeling that even these needs might not make sense in Haskell in the first place, but I can't formulate the question any better.

My understanding of the structure of the factory pattern (based on this video which seems pretty clear) is that

  1. there's a bunch of different products, all implementing a common interface
  2. there's a bunch of different creator classes, all implementing a common interface
  • each of the classes in 2 hides a logic to create a product of those in 1
    • (if I understand correctly, it's not necessary that there's a 1-to-1 mapping between objects and creators, as the creators could just hide different logics make different choices about which specific object to create based on user input/time/conditions/whatever.)
  • the client code will have the creators at its disposal, and everytime one of those is used it (the creator, not the client code) will know how to crate the product and which specific product.

How does all (or some) of this apply to Haskell?

Having several different product classes implementing a common product interface is a thing in Haskell, the interface being a typeclass, and the products being types (datas/newtypes/existing types). For instance, with reference to the spaceship-and-asteroids example from the linked video, we could have a typeclass for defining Obstacles anything that provides size, speed, and position,

class Obstacle a where
  size :: a -> Double
  speed :: a -> Int
  position :: a -> (Int,Int)

and Asteroid and Planet could be two concrete types implementing this interface in some way,

data Asteroid = Asteroid { eqside :: Double, pos :: (Int,Int) } deriving Show
instance Obstacle Asteroid where
  size a = eqside a ^ 3 -- yeah, cubic asteroids
  speed _ = 100
  position = pos

data Planet = Planet { radius :: Double, center :: (Int,Int) } deriving Show
instance Obstacle Planet where
  size a = k * radius a ^ 3
    where k = 4.0/3.0*3.14
  speed _ = 10
  position = center

So far I don't see any real difference between what I'd do in Haskell or in a OOP language. But it comes next.

At this point, following the example in the linked video, the client code could be a game that traverses some levels and generates different obstacles based on the number of the level; it could be something like this:

clientCode :: [Int] -> IO ()
clientCode levels = do
  mapM_ (print . makeObstacle) levels

where makeObstacle should be the creator function, or one of several, which given an input of type Int applies a logic to chose if it has to create an Asteroid or a Planet.

However I don't see how I can have a function that returns outputs of different types, Asteroid vs Planet (the fact they implement the same Obstacle interface doesn't seem to help), based on different values all of the same type, [Int], let alone understanding what the "factory" functions and their common interface should be.

Why isn't "\\" working as a delimiter pattern [duplicate]

I want to break down all the parents of a directory by using a simple Scanner and using "\\" as the delimiter.

import java.util.Scanner;

public class TestScanner {
    public static void main (String [] args) {
        String directory = "C:\\Users\\MyName\\New File";
        Scanner scanner = new Scanner(directory);
        scanner.useDelimiter("\\");
        while (scanner.hasNext()) {
            System.out.println(scanner.next());
        }
        scanner.close();
    }
}

However, I get an exception saying

Exception in thread "main" java.util.regex.PatternSyntaxException: Unexpected internal error near index 1 \
       at java.util.regex.Pattern.error(Pattern.java:1969)
       at java.util.regex.Pattern.compile(Pattern.java:1708)
       at java.util.regex.Pattern.<init>(Pattern.java:1352)
       at java.util.regex.Pattern.compile(Pattern.java:1028)
       at java.util.Scanner$1.create(Scanner.java:367)
       at java.util.Scanner$1.create(Scanner.java:365)
       at sun.misc.LRUCache.forName(LRUCache.java:72)
       at java.util.Scanner.useDelimiter(Scanner.java:1150)
       at TestScanner.main(TestScanner.java:7)

I've tried things like "[\\]+" and Pattern.compile("\\") but neither seem to work! Please help me out, and thanks in advance :)

Factory Method: "Patterns in Java" by Mark Grand vs GoF interpretation

I'm learning Java design patterns by "Patterns in Java", volume 1 by Mark Grand (Factory Method specifically). My point is to highlight difference between closest patterns for myself. There are good answers that clarify the difference between Factory Method and Abstract Factory (Design Patterns: Factory vs Factory method vs Abstract Factory, What is the basic difference between the Factory and Abstract Factory Design Patterns?). But I noticed that most of authors mean some other interpretation of Factory Method compared to one I have read in "Patterns in Java". The interpretation from the answers is closer to Factory Method from GoF book.

GoF interpretation:

GoF Factory Method interpretation

Grand's interpretation: Mark Grand's Factory Method interpretation

To be specific I will describe what in my opinion is a key difference between Grand's and GoF interpretations. The source of polymorphism in GoF interpretation is inheritance: different implementations of Creator create different types of Products. The source of polymorphism in Mark Grand interpretations apparently is "data-driven class determination" (example from book):

Image createImage(String ext){
    if (ext.equals("gif"))
        return new GIFImage();
    if (ext.equals("jpeg"))
        return new JPEGImage();
    ...
}

CreationRequester delegates object creation to other object that encapsulates "data-driven class determination" logic to pick a right type of ProductIF by discriminator argument.

Can any one please explain me:

  1. Is the Grand's Factory Method interpretation equivalent to Factory Method by GoF? Is it actually Factory Method at all? May be it is some kind of generalization or special case of GoF Factory Method? I can't see direct mapping between these interpretations taking into account UML class diagrams.
  2. Let's consider GoF interpretation now. Can one define a factory method in a separate interface (not in abstract class), like Mark Grand describes? Will it still be Factory Method? Can one consider Factory Method in GoF interpretation as a special case of Template Method that returns some product?
  3. If we consider Factory Method as Grand describes, then it becomes obvious that Factory Method is simply a special case of Abstract Factory that produces a single product. Am I right?
  4. If one just encapsulates a "data-driven class determination" logic into a separate class, can this structure be called "Factory Method"?

Can I annotate classes without data interactions with @Service?

I have a Spring Boot application which does ETL processes and not a web application. I know that the use of services is to separate concerns and provide loose coupling but can I use it with classes that do not deal with the data being processed. I have several classes that I put in my service package and annotated it with @Service such as:

S3Service.java

@Service
public class S3Service {

    @Autowired
    private final AmazonS3 s3Client;

    public File downloadFile(String filename) throws Exception {
        ...
    }

    public File uploadFile(String filename) throws Exception {
        ...
    }

}

FileSecurityService.java

@Service
public FileSecurityService {

    public File decryptFile(String filename) throws Exception {
        ...
    }

    public File encryptFile(String filename) throws Exception {
        ...
    }

}

I did it this way because I think it makes my code cleaner but I don't think this is what services are for. I am hesitant to make them Utility classes because they are a huge part of the process. Is it a bad practice to use @Service this way? If yes, where should I put these? Thank you.

React separation of concern with GraphqQL

I am currently working on a React and Graphql project. I see that there is no clear separation of concern when the Graphql queries are embedded in the views itself.

This would be a challenge if one has to move from Graphql to a better data layer or REST API.

Has anyone been able to achieve clear separation of concern, more like a plug and play data layer with React and Graphql.

Any references or sample architecture would be appreciated.

Thanks in advance.

How do I create a new column that that contains part of a string based on a pattern in R

Apologies if this has been solved before, I haven't been able to find a solution to this problem. I am trying to pull out the letter "N" out of a sting including the -1 and +1 position and report it in a new column, there may be more than one instance of N in the string and i would like it to report all of them. I can filter the peptides containing N using dt_contains_N <-dt[str_detect(dt$Peptide, "N"),] but I'm not sure how to extract it, I was thinking something like , dt_N_motif <- dt[substring(dt$Peptide, regexpr("N", dt$Peptide) + 1)] but im not sure how to include the N-position column information to extract the N-1, N and N+1 positions. For example a simplified view of my data table looks like: dt <- data.frame(Peptide= c("GESNEL", "SADNNEW", "SADNNEW"), N_pos=c(4,4,5)) . .

peptide N pos
GESNEL 4
SADNNEW 4
SADNNEW 5

and I would like it to look like this:

peptide N pos Motif
GESNEL 4 SNE
SADNNEW 4 DNN
SADNNEW 5 NNE

Any help would be great,

Thanks!

What can be a good way to call network class other than an activity in android?

I have created a network client app (using Retrofit) where I call for network request and response in the activity. I learned that it is a bad practice. If anyone can suggest that what can be a good design pattern that I can follow to do such an operation?

jeudi 25 février 2021

Python regular expression findall() not returning desired list

I am trying to extract urls from a big string using regular expressions.

This is my regular expression

url_pattern = r'(https?)*[-a-zA-Z0-9@:%._\+~#=\/\/]*\.[a-zA-Z0-9()]*\b([-a-zA-Z0-9()@:%_\+~#?&//=]*)'

This matches some undesired strings like 2.5 D.C etc. How can I get away with this and match only url patterns which may or may not contain 'http' or 'www.'?

Also, when I use urls = re.findall(url_pattern, text) to get a list of matched substring it returns this

text = 'The petition should be updated. The education committee has increased the spending from the Mayor\'s proposal -- a 2.38% increase over last year.  https://www.washingtonpost.com/local/education/despite-increases-in-funding-some-dc-schools-face-possible-cuts/2017/05/18/9e132516-3bdf-11e7-a058-ddbb23c75d82_story.html?utm_term=.5c053ce98ec2  On Thursday, the D.C. Council’s Committee on Education voted to add more money, raising the per-pupil spending increase to 2.38 percent. That measure now moves to the full council for a decision.'
Output:
[('', '%'), ('https', '?utm_term='), ('', ''), ('', ''), ('', '')]

How can I get it to return desired url list?

Edit: regexr link where match occurs although undesired strings like '2.8' 'D.C' etc are included: regexr link

PHPUnit how to test a Repository?

I have a group of Repository classes I'd like to test. All Eloquent methods are called in these classes, however I am unsure on how to proceed. The only thing that needs to be tested, is that the methods return the right data type. I want to be sure that getByEmail($email) for example actually returns a User object, but I don't care about the implementation details.

Every example I see tells you to inject the model in to the Repository class and mock it, then you can proceed by having that Mock expect very specific method calls. Is this the correct approach? Because it seems to me that would be forcing the developer to use very specific methods when building the Eloquent query.

Here's an example:

class UserRepository {
    public function __construct(User user) { ... }

    public function getByEmail(string $email) : ?User {
        $this->user->where('email', $email)->first();
    }
}

For the test with Mock to work I have to do:

class myTest {
    public function testMethodReturnsUserObject() {
        $user = Mockery::mock(User::class);

        $repo = new UserRepository($user);
        
        // now, if a developer changes the eloquent method calls, this will fail.
        $user->shouldReceive('where->first')->andReturn($user);

        $this->assertEquals($user, $repo->getByEmail('joe.bloggs@acme.com'));
    }
}

Any ideas what I should do to test that my method does indeed return a User object, without forcing the developer to use exactly one where() method, and one first() method in this example. What if the developer needs to instead make it ->select()->where()->where()->firstOrFail() . Now the unit test will break, even though it really shouldn't care about this, and only that the method returns a User.

Thanks!

Do you have to store resource if you publish it via rest api?

Let's say I have a rest api with a following endpoint: /foos/{fooId} which returns some object named of type foo. Now let's say I store different kind of resource in my database underneath, which is bars. Sample bar has some barId, and my resource available via api (foo) is a projection of a bar plus some other stuff. Does this design makes sense? If I don't store resource named foo and there is no such thing as fooId (just a projection of bar), is my api still restful?

Which Design Pattern is suitable for scheduled backup spring-boot application?

Business use case : I have IBM DB2 databases for 3 different domains and 3 environments (dev, QA, Stage). I want to create a spring-boot application which

  1. evokes itself at particular intervals(say every 30 days)
  2. Calls DB2, get data from table, save them in txt file(create new text file each time based on timestamp) and upload that file to azure blob storage, calls DB2 to delete those data.

Example: Domain1 - 10 tables Domain2 - 7 tables Domain3 - 15 tables

On 1st of every month, i want to trigger a backup for all the tables of domain1, domain2 on 10th of every month and domain3 on 15th.

For domain1, I have 10 tables. So DB2 will be called 10 times. 1 text file should contain data for single table only.

Which design pattern should I use? Technology: springboot

Should I opt for code repetition or consolidation with api service - JS

I'm working on a large CMS system where a particular module and its submodules take advantage of the same backend API. The endpoint is exactly the same for each submodule aside from its "document type".

So a pattern like this is followed:

api/path/v1/{document-type}

api/path/v1/{document-type}/{id}

api/path/v1/{document-type}/{id}/versions

As time goes on the number of modules that use this API grows and I am left with many, many redundant api services that implement 7 CRUD methods:

getAllDocType1s() {...}
getDocType1(id) {...}
getDocTypeVersion(id, versionId) {...}

etc...

I came to a point where I decided to make a single service and do something like this:

const BASE_URL = window.config.baseUrl + Const.API_ENDPOINT;
const ENDPOINTS = {
  "DOCTYPE1": "/v1/DOCTYPE1/",
  "DOCTYPE1": "/v1/DOCTYPE1/",
  "DOCTYPE3": "/v1/DOCTYPE3/",
  "DOCTYPE4": "/v1/DOCTYPE4/",
}

getAllDocuments(docType, headers = {}, params = {}, timeout = Const.TIMEOUTS.NETWORK_STANDARD) {
  let endpoint = BASE_URL + ENDPOINTS[docType.toUpperCase()];
  return http.get(endpoint, {headers, params, timeout})
      .then(response => {
        if (Array.isArray(response.data)) return response.data;
      })
      .catch(error => {
        console.error("FAILED TO LOAD CMS DOCUMENT LIST");
        throw error;
      });
}
...other methods

Where a type is specified and a mapped endpoint is used to build the path.

This reduces all of the document api services down to one. Now this is more concise code wise, but obviously now requires an extra parameter and the terminology is more generic:

getAllDocType1s --> getAllDocType

and it's a bit less 'idiot-proof'. What makes me insecure about the current way it is written is that there are 6 modules that use this API and the same 7 methods in each service.

The questions I keep asking myself are:

  • Am I bordering anti-pattern with the dynamic functions?

  • What if I had 10+ modules using the same API?

  • Is this a backend design problem? As in, should docType be a parameter?

How to clear expired data in cache?

I implemented an ExpireLRUCache class, which will clear the data when it's times out. There are two ways to achieve this.

  1. Use a timer to clear the expire data
  2. Call the clean function in Add and Get

So, which implementation is better?

how to copy all csv files from different source folders into target as per source folders using python?

I have code as below to copy all *.csv files from different source folders, but i want to copy in different folders as per source, i could able to copy all csv files to single folder but i want it into different folders as source folders.

import os
import shutil
import fnmatch

dir = 'C:\\data\\projects\\'
patterns = ['project1','project2']
dest = 'D:\\data\\projects\\'

for root, dirs, files in os.walk(dir):

    for pattern in patterns:

        for filename in fnmatch.filter(files, '*.csv'):
            source = (os.path.join(root, filename))
            print(source)
            shutil.copy(source, dest)

How to write Xunit test case of factory design pattern code block which is tightly coupled?

I would like to write xunit test case of below method. Could you please suggest alternate design so i can write xunit test case with minimum change in my current project.

public ActionResult Index(int id = 0, AssetFilterType filter = AssetFilterType.All)
        {
            using (var tracer = new Tracer("AssetController", "Index"))
            {
                
                RemoveReturnUrl();
                ViewBag.JobId = id;
                var response = ContextFactory.Current.GetDomain<AssetDomain>().GetAssetFilterAsync(id, 
 CurrentUser.CompanyId, filter); // Not able write unit test case , please suggest alternate design. 
                return View("View", response);
            }
        } 

current design is as follow

 public interface IDomain
            {
            }

 public interface IContext
        {
            D GetDomain<D>() where D : IDomain;
    
            string ConnectionString { get; }
        }

 public class ApplicationContext : IContext
    {
        public D GetDomain<D>() where D : IDomain
        {
            return (D)Activator.CreateInstance(typeof(D));
        }

        public string ConnectionString
        {
            get
            {
                return "DatabaseConnection";
            }
        }
    }

 public class ContextFactory
        {
            private static IContext _context;
    
            public static IContext Current
            {
                get
                {
                    return _context;
                }
            }
    
            public static void Register(IContext context)
            {
                _context = context;
            }
        }

//var response = ContextFactory.Current.GetDomain**< AssetDomain >**().GetAssetFilterAsync(id, CompanyId, filter);
This line serve purpose to call specific class method i.e GetAssetFilterAsync from AssetDomain. Although it is very handy and widely used in our application but due to design issue i am not able to write unit test case.

Could you please suggest design so with the minimum change we can write unit test case.

mercredi 24 février 2021

How to get asterisk pattern one after another?

I want to print two patterns in the same program but one in front of the other like this:

enter image description here

I have written the rest of the code but my pattern is indented normally:

x = input("Please enter any number: ")

for i in range(0,5):
    for j in range(0,5):
        print('*', end="")
    print()

print("\n")
for i in range(0,5):
    for j in range(0,5):
        if (i==0 or i==5-1 or j==0 or j==5-1):
            print('*', end='')
        else:
            print(' ', end= '')
    print()

My output: enter image description here

Any help would be appreciated!

What is the type of application that communicates with hardware and devices?

I am planning to design an application whos job is to manage and control some devices. There are some settings that can be set on the device through a GUI. At same time those devices trigger some events that need to be processed ( So will have multiple services to process events). Communication to devices are mostly through USB but some devices are Bluetooth and wireless. So I will have a middleware for communication between hardware and software services. Finally each device has a configuration settings that need to be stored in some cloud just for backup propose.

I want to understand how to design this system. The key input data is:

  1. All services are running in a local machine.
  2. There are communication between hardware and services.
  3. The only networking subject is to backup data on the cloud.

My questions are:

  1. Is this system can be considered as a standalone application? Can we refer to it as networked application because of communication between device and services? Or some Bluetooth and Wireless communications?

  2. Can we suppose to use event driven architecture just because of processing events (software or hardware events)? Note: It is important to handle events in the least time (to be real time)

In general what kind of architecture fits the requirements for this system? [Multi Layer, Event Driven...] and also if any suggestion about related design patterns.

Thanks.

Writing a flexible and clean method to handle multiple REST API calls in Spring

To set up the problem, let's imagine we have a downstream service that we need to call for some information. We set up an API endpoint and call another method which will hold our business logic and make the HTTP request. Based off of certain parameters that were sent to this method, we may potentially have to make several calls to the same endpoint, depending on what it returns. The method is currently setup like so:

public HttpEntity<String> getInfo(//parameters) {
    
    //setup HTTP headers etc.
    HttpEntity response = restTemplate.exchange(//stuff here);

    //based off of on the parameters given to this method, we will know whether or not we need to make additional calls
    //if we DO need to make additional calls, we will also need to inspect the response for information
    //this is difficult, because as you see below, this method doesn't start to procces the response until after error checking
    
    //do all error checking ie. checking for no data and other HTTP errors
    
    OurDataClass dataClass = objectmapper.writeValueasString(response.getBody());
    //do things to dataClass
    return new HttpEntity<String>(//dataClass and headers);

Given the current structure of this method, I don't know how to work it into something that's more extendable and maintainable. My first instinct was to just encapsulate the restTemplate and take care of additional calls there, but given the fact that I need to inspect the request contents of each call, something that is not done until the end of the current method, it would seem like we're doing a lot of double work. On the other hand, working the solution into the method without any encapsulation would make it even more difficult to maintain down the road (it's already a bit of a mess with error checking).

Am I overthinking it? Is it wrong to try to shoehorn in some sort of design pattern here?

Regex.Match returns different/wrong result in Unity compared to same exact code in a C# console app

I'm trying to get matches on a string in Unity using a Regular Expressions pattern. I've written the whole code inside a sample project and it worked perfectly fine.

tokens[line] = Regex.Matches(instructionLines[line], "^\\w*|(?<=q\\[)\\d*(?=\\]))";

I have validated that it matches what I need with regex101.

I have then printed out the result in my console, which was also correct.

Console App:
 h 0
 h 1
 h 2
 h 3
 cx 1 2
 t 1

Finally, I copy-pasted the code in Unity - and it doesn't match the first word of the line like it did in the sample project.

Unity Console:
 0
 1
 2
 3
 1 2
 1

I didn't change anything, the imports are the same (using System.Text.RegularExpressions;) and the regex is correct. Why does Unity do this, and how do I fix this incorrect behaviour?

Custom Label and Bar background colour in Recharts

I am new to Recharts and SVG and looking for some help trying to match the design below using Recharts.

Colors: #003C88, #003C8840, #7F7F7F, #D9D9D9

enter image description here

Here is https://codesandbox.io/s/recharts-barchart-forked-7sl6x?file=/index.js is what I have done so far to try to create the two stripe patterns in the design for the bar and to have a custom red / green label at the base of the two bars per month. As you can see both the background bar patterns are not the expected solid colours but have some opacity < 1 affecting them. So instead of the dark blue I get a light blue background colour. The patterns are also coming through the red / green labels I have at the base of the bars. How can I get the pattern background display without the opacity level of < 1. AND how would I ensure the red/green labels are not showing the patterns behind them?

Python: pipelining functions with multiple return/input values, or use OOP? Best Practices?

We have a data 'processing' function and a 'serializing' function. Currently the processor generates & returns 4 different data structures all from the same large data source input, and all outputs are related to each other.

Trying to separate out the 'data processing' from the 'serializing' step has gotten a bit.. messy. Looking for the best practise on what to do here.

def process(input):
   ...
   return a,b,c,d

def serialize(a,b,c):
   ...
   # Different serialization patterns for each of a-c.

a,b,c,d = process(input)
serialize(a,b,c)
go_on_to_do_other_things(d)

That feels janky. Should I instead use a class where a,b,c,d are member variables?

class VeryImportantDataProcessor:
   def processd(self,input):
      self.a = ...
      self.b = ...
      ...

   def serialize(self):
      s3.write(self.a)
      convoluted_serialize(self.b)
      ...

vipd = VeryImportantDataProcessor()
vipd.process(input)
vipd.serialize()

Keen to hear your thoughts on what is best here!

Note after processing and serializing, the code goes on to use variable d for further unrelated shenanigans, but a, b, c are all finished once they've been saved. Not sure if that changes anything.

How to replace abstract class? (composition instead of inheritance) - concrete problem

my problem started when I wanted to write unit test for an abstract class (test the common methods) than I discovered it would be probably better to prefer composition instead of inheritance (I can use mocks for the part which is changing "connection")

Now I have hard time to come up with some design which would be correct so could someone help me here?

Whole my code can be found here but for simplicity I will try to describe it shortly here. I have class PlcData which represents current status of variables I need which are read from PLC. The PlcData represents subject in observer pattern and I subscribe to it with different classes (I also need to know what exact attribute has been changed that is why PlcData implements "source" interface for each attribute I need to observe, I also need to get all data when the attribute is changed because based on some other attributes I search in database - that is why I send whole PlcData when any attribute changes). I would like to keep the observers of PlcData independent on connection (how the PlcData reads/writes variables from PLC).

Here is my original design with abstract PlcData:Current design

I would like to achieve something like this (a lot of programmers confirmed me that this is the correct way) where the PlcData is concrete class (I could use also interface for it in future) and the connection is as attribute of PlcData: New design

My problem is that I don't know how to correctly implement this. The each concrete class of "Connection" will use some library and will have a lot of specifics here but it should handle the subscription, read, write to those "important" variables (serialNumber, measuredCurve ... - in real code I have more of them but they are exactly given). But I would like this to be invisible for PlcData "user" so he would just call some factory method PlcDataProvider.getPlcData() and he would get instance of PlcData with initialised connection and he would just subscribe to variables he needs (or write to those variables and the PlcData class would handle how to send them to PLC over the "Connection" interface.

MY BIGGEST PROBLEMS

  1. I don't know how to correctly make the Connection updating the PlcData and how to write to real PLC variables over it (I am really lost here and I end up with three methods for each attribute (writeSerialNumber, readSerialNumber, subscribeToSerialNumber and the Connection needs to keep track of PlcData)

  2. How to correctly create PlcData using some factory

Is event bus an acceptable use of singleton?

Assuming an event bus used to control all events subscription/publishing in the code, is it a suitable target for the singleton pattern?

It seems to me it attends to all requisites to make it singleton and not run into the design problems that singleton usually ends up into.

What do you think? Is singleton an anti-pattern even in cases like this?

Java ValidatorFactory as an implementation of Abstract Factory design pattern?

I have to analyze an existing open source application (OpenDev) written in Java and one of the questions asks we identify 3 GoF design patterns implemented in the code. I was thinking about the Abstrat Factory, as I saw the use the ValidatorFactory interface in the code which seems, in theory, to implement this design pattern.

Here is the part of the code that I was thinking about :

bind(ValidatorFactory.class).toProvider(new com.google.inject.Provider<ValidatorFactory>() {

            @Override
            public ValidatorFactory get() {
                Configuration<?> configuration = Validation
                        .byDefaultProvider()
                        .configure()
                        .messageInterpolator(new ParameterMessageInterpolator());
                return configuration.buildValidatorFactory();
            }
            
}).in(Singleton.class);

I am not very familiar with Java projects, so don't quite uderstand the bind().toProvider() process and how exactly this piece of code would work.

Could I consider this an implementation of the Abstract Factory pattern? And if so, how could I clearly explain its implementation in this case?

Thank you in advance!

Find small matrix inside a bigger one but don't know how, in python (image attached)

I have a pattern that I have represented as a list of lists, and also tried as an array using numpy, and I have to find how many times this pattern exists within the bigger one, like this image

here In this cas it would be three times : Any ideas on how to solve?

Thanks!

(My code)

So far I have done this, but not even sure I am in the right direction. seems too complicated.

#Defined both pattern and bigger matrix as a list of lists.

imagen_1 = [[0, 0, 1, 0, 0],
         [1, 1, 1, 1, 1],
         [0, 1, 1, 1, 0],
         [1, 1, 0, 1, 1],
         [1, 0, 0, 0, 1]]

imagen_2 = [[1, 1],
         [0, 1]]


# Then tried this logic, but got too complicated to loop.
# At this point I am just trying to check the actual position and the nearest to the right

def repeticiones(original, patron):
 
 if len(patron) > len(original) or len(patron[0]) > len(original[0]):
     raise ValueError(f"La imagen patrón es más grande que la original. Por favor, proporcione una imagen patrón más pequeña a {len(original)} * {len(original[0])}")
 
 c = 0
 
 filas_patron = len(patron)
 columnas_patron = len(patron[0])
 
 j = -1
 i = -1
 
 for linea in range((filas_patron)-2):
     j += 1
     i = -1
     for columna in range((columnas_patron)-2):
         i += 1
         igual = original[j][i]==patron[0][0] and linea[j][i+1]==patron[0][2]
         if igual:
             return True
     
 return False

mardi 23 février 2021

SQL Database Design for Job Schedule Dependency

I am tasked with migrating a legacy application which schedules jobs based off a specific sequence and hierarchy. I am trying to come up with a multi- table design to make it scalable and easily updateable. Not sure where to start. This is how the job schedule hierarchy looks right now.

1

Job1 is the parent job which has o run first after which the level 2 jobs have to be picked up based off their priority(Pls note that the multiple jobs might have same priority.) The next level of jobs cannot start until its parent job has complete running( for e.g. Jobs 3, 4, 5 cannot run until Job 2 has been completed)

So the order in which this should run is, 1, 7,6,2, 3, 5, 4 Can we fit this into a database design.

How Kyle Simpson's OLOO Pattern handles a not initializated object?

Suppouse the next example extracted from another OLOO question:

var Foo = {
    init: function(who) {
        this.me = who;
    },
    identify: function() {
        return "I am " + this.me;
    }
};

Here, I want to throw an error or deny the call of identify if the object was not initialized before call the function. However, I dont want to add a verifier inside each public routine of the Object.

How can I handle it without duplicating that behaviour?

API Endpoint URL Difference between resourceName/create [POST] vs resourceName [POST]

I would like to know is it better to use

sku/article/create [POST]

or

/sku/article [POST]

In the first URL I specify the action, is that considered a good practice? I've seen both been used consistently, do people specify action specifically to increase code readability? What is the purpose of it?

E-Commerce low level design of Order class

I am in middle of shopping website design. As of now I am stuck at one point and need a little feedback. Let us say I have an order class defined as follow:

class Order {

    Payment payment;
    Address ShippingAddress
    int orderId;
    List<Item> orderItem;
    double orderValue;  
    Buyer buyer;
    Date orderDate;
    NotificationService notificationService;
    Shipment shipment;
    
    List<OrderLog> orderLog;

    public OrderStatus placeOrder();
    public OrderStatus trackOrder();
    public void addOrderLogs();
    public PaymentInfo makePayment();
    public int createShipment();

}

Does it make sense to have placeOrder(), makePayment() etc.,API in order class? Or shall I make a separate OrderManager that helps to do all order related stuff and order will act as a pojo?

To me first one seems correct because the placeOrder(), makePayment() seems to me as behaviours of order and they should be in order class but on other class I think it is too much for an order class to do.Am i violating some SOLID principle by taking one approach over another?

Handling same exception thrown by different methods

Is there an idiomatic way to catch an exception when multiple methods may throw?:

try:
    someMethod()  # raises OSError
    someOtherMethod()  # raises OSError
except OSError:
    handle()

The exception may or may not be caused by the same event internal to the helper functions, so in the current layout it seems impossible to discern which method threw the exception. To resolve, there are two cases I could implement.

The first case is wrapping each method in its own try/except:

try:
    someMethod()
except OSError:
    handle()

try:
    someOtherMethod()
except OSError:
    handle()

While this address the issue of identifying which helper function threw the exception, it presents a new problem. If successive helper methods require successful of preceding methods, separate try/except blocks lead to forced early returning as subsequent blocks should not be executed:

try:
    someMethod()
except OSError:
    handle()
    return

try:
    someOtherMethod()
except OSError:
    handle()

This seems like a code-smell and is therefore undesired. The second case is creating custom exceptions based on the content of the internally generated exception:

class FailedReadIOError(Exception):
    def __init__(self, msg):
        super().__init__(msg)

class FailedFolderError(Exception):
    def __init__(self, msg):
        super().__init__(msg)

def someMethod():

    try:
        # stuff
    except OSError as err:
        raise FailedReadIOError('thrown in someMethod') from err

    try:
        # stuff
    except OSError as err:
        raise FailedFolderError('thrown in someMethod') from err

def someOtherMethod():

    try:
        # stuff
    except OSError as err:
        raise FailedReadIOError('thrown in someOtherMethod') from err


try:
    someMethod()
    someOtherMethod()
except FailedReadIOError:
    handle_this()
except FailedFolderError:
    handle_that()

This adequately addresses the concerns but requires additional (minimal) code to be written. Is there a pattern that achieves the same result without the need to create custom exceptions when multiple methods throw the same exception?

What design pattern would be suitable for async image processing?

I have an app where user can select bunch of images and apply some backend async processing on them. Typical payload front frontend app looks like this:

{
 files: ['tmp.jpg', 'tmp2.jpg'],
 config: {'applyX': true, 'applyY': true},
}

Where applyX, applyY are namespaces for some processing functions. I want pattern to give ability to easily add new functions and unit test it properly.

How to extract telemetry code from different methods? Decorator pattern? AOP?

We are using Application Insights to monitor different service calls in our applications. Data for Application Insights is provided by many different methods and classes but always in an identical way/by identical code fragments:

public class MyClassA {

  public void myMethodA() {
    final Instant startTime = Instant.now();

    try {
      callSomeServiceA();
    } catch (final Exception e) {
      sendExceptionDataToAppInsights(e);
      throw e;
    } finally {
      sendDataToAppInsights(MyClass.getName(), myMethodA.getName(), startTime, Instant.now());  
    }
  }

}

public class MyClassB {

  public String myMethodB() {
    final Instant startTime = Instant.now();

    try {
      return callSomeServiceB();
    } catch (final Exception e) {
      sendExceptionDataToAppInsights(e);
      throw e;
    } finally {
      sendDataToAppInsights(MyClass.getName(), myMethodA.getName(), startTime, Instant.now());  
    }
  }

}

How am I able to extract those wrapping try catch fragments to one point of responsibility? I took a look at the dacorator pattern but I guess it doesn't fit because of the different method signatures. Or does it?
Or is there a way to achieve it with AOP?

Just a thought whether bulkhead pattern in reactive microservices would make sense

If a reactive microservice calls another microservice then bulkhead is by default nature of reactive microservices as reactive service which calls another mircoservice does not have to wait for the response, rather it can continue its execution for new threads.

lundi 22 février 2021

How can I create a new class variable in 100+ existing classes?

I am building a Java program that checks whether or not a car has prior damage by inspecting each part individually. Each part is divided into it's own class.

UML Diagram of a selection of car part classes

My problem is that each part already exists and needs a Boolean value called 'damage'. Is there a faster way to assign a damage variable to each class rather than doing it one by one?

How to optimize the structure of a sequence of functions?

i want to improve my javascript code and to optimize a frequent coding situation i have often to use. It is a sequence of function, which are collecting data from server or databases and as a result do something with it like draw a chart or fill a table. At the moment this block is not extremly good coded:

main();
 
function main () {  drawChart ();  }
 
function drawChart(){  getHistoricalTemp(); }
 
 
function getHistoricalTemp ()
{
  let Temperature = 38.1;
  getConversionfactor (Temperature);
}
 
function getConversionfactor (T)
{
  let Conversion = 1;
  getServerTime (T, Conversion);
}
 
function getServerTime (T, c)
{
  let time = 0;
  loadUsersettings (T, c, time);
}
 
function loadUsersettings ( T,  c,  z)
{
  let bgcolor = 255;
  initializeChart (T, c, z, bgcolor);
}
 
 
function initializeChart ( T,  c,  z,  bgc)
{
  console.info (" initializeChart: " + c + " | Temperature" + T + " Time: " + z + " color: " + bgc );
}

For the first i tried to improve this block to style it like a c++ class:


    let Temperature = null;
    let Conversion = null;
    let time = null;
    let bgcolor = null;

    function getHistoricalTemp() {  Temperature = 38.1;  }

    function getConversionfactor() {   Conversion = 1; }

    function getServerTime() {  time = 0; }

    function loadUsersettings() { bgcolor = 255;}

    function init() {
        console.log(`Opening database #`);

    }

    function draw_chart() { 
        
        getHistoricalTemp();
        getConversionfactor();
        getServerTime();
        loadUsersettings();
        console.info ("draw_chart with Temperature: " + Temperature + " | Conversion " + Conversion + " | time " + time + " | bgcolor " + bgcolor ); 
        }

    return {
        draw_chart: draw_chart,
        //close: init,
        //note: operations.note
    }
}

var chart = drawChart();
chart.draw_chart();
```

Is there a better way to code this wanted procedure? Whats the best practice to start all these function enclosed in the class?

Spring batch selecting item reader data provider based on specified source

I have a spring batch job that gets executed based on a HTTP request.

First step generates request file locally based on some static file (which contains list of instruments) in the classpath.

Second step uploads the file to a server.

@Configuration
@EnableBatchProcessing
public class BatchConfiguration {

    private final JobBuilderFactory jobBuilderFactory;
    private final StepBuilderFactory stepBuilderFactory;

    public BatchConfiguration(final JobBuilderFactory jobBuilderFactory, final StepBuilderFactory stepBuilderFactory) {
        this.jobBuilderFactory = jobBuilderFactory;
        this.stepBuilderFactory = stepBuilderFactory;
    }

    @Bean
    public Job generateRequest(final Step generateRequestStep, final Step uploadRequestStep) {
        return this.jobBuilderFactory.get("MyRequestJob")
                .start(generateRequestStep)
                .next(uploadRequestStep)
                .build();
    }

    @Bean
    public Step generateRequestStep(@Qualifier("instrumentFlatFileItemReader") final ItemReader<Instrument> instrumentItemReader,
                                    @Qualifier("") ItemWriter<Instrument> instrumentItemWriter) {
        return stepBuilderFactory.get("requestStep")
                .chunk(5)
                .reader(instrumentItemReader)
                .writer(instrumentItemWriter)
                .build();
    }


    @Bean
    @Scope(value = "step", proxyMode = ScopedProxyMode.INTERFACES)
    public FlatFileItemReader<Instrument> instrumentFlatFileItemReader(@Value("#{jobExecutionContext['feedType']}") String feedType) {
        FlatFileItemReader<Instrument> reader = new FlatFileItemReader<>();
        reader.setResource(new ClassPathResource("/path/to/static/file", getClass().getClassLoader()));

        DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer();
        tokenizer.setNames("column1", "column2");
        tokenizer.setStrict(false);

        DefaultLineMapper<Instrument> lineMapper = new DefaultLineMapper<>();
        lineMapper.setLineTokenizer(tokenizer);
        lineMapper.setFieldSetMapper(new InstrumentFieldMapper());
        lineMapper.afterPropertiesSet();

        reader.setLineMapper(lineMapper);

        return reader;
    }


    @Bean
    @StepScope
    public ItemStreamWriter<Instrument> instrumentItemStreamWriter(@Value("#{jobExecutionContext['FILE_OUTPUT_PATH']}") String requestFilePath) {
        BeanWrapperFieldExtractor<Instrument> fieldExtractor = new BeanWrapperFieldExtractor<>();

        DelimitedLineAggregator<Instrument> lineAggregator = new DelimitedLineAggregator<>();
        lineAggregator.setFieldExtractor(fieldExtractor);

        return new FlatFileItemWriterBuilder<Instrument>()
                .name("instrumentWriter")
                .resource(new FileSystemResource(requestFilePath))
                .delimited()
                .fieldExtractor(fieldExtractor)
                .lineAggregator(lineAggregator)
                .shouldDeleteIfExists(true)
                .build();

    }
}

currently, there is only one way to load the instruments, from the static file. I now have requirements where users can specify which media to load static from, e.g. local classpath, database or from call to webservice.

I am unsure of a pattern to follow to design this. Currently, I am using flat file item reader, but this won't work for database, external service. I need some help to put this behind an interface and have ability to derive the appropriate one based of the media type chosen:

for example: the http request can provide which media type to use:

{
  jobName: "REQUEST",
  cobDate: "2021-02-22",
  type: EOD,
  media: "DATABASE"
} //load list from database table

or

{
  jobName: "REQUEST",
  cobDate: "2021-02-22",
  type: EOD,
  media: "FILE_SYSTEM"
}  //load list from static file

Adding a structural or behavioral design pattern to my JavaFX project

I am working on a simple university project, which consists of a simple arcade JavaFX video game. I decided to create the ping pong game. The game code must be done using 2 design patterns. I used the Factory pattern to create the game so that I would be able to add more games to the project later. But for such a small project I can't seem to find a way to include another design pattern. Any design pattern ideas are greatly appreciated. My code design is the following:

Main.java (client class that displays the chosen game) Game.java (methods interface) GameFactory.java (Factory that creates games) PingPong.java (ping pong game class)

How to correctly use abstract classes (problems with testing)

I came over some problem with abstract classes and it is that there is problem to test them (the common part of the code without creating concrete implementation) and I would like to ask how should solve this problem correctly.

I need to have class representing current status (I use observer pattern here) of variables which I read from PLC and I also need to write to some of these variables. I would like this part to be connection independent (OPC UA, MODBUS ...) That's why I created class PlcData which represents all variables I need to write or read, this was an abstract class and I wanted to create different implementations based on connection type (PlcDataOpcua, PlcDataModbus ...)

But when I was trying to write unit tests I came over this problem, that I can not test the common code shared between all PlcData.

Based on the second most upvoted answer here I came up with something like this: enter image description here

But because the Connection needs to update informations in PlcData it needs to keep track of the PlcData instance. For me it seams more complicated than the original solution but of course it would be "testable".

Could anyone tell me which way to go or came up with better solution?

C# - Is it good practice to pass parameter from the factory (pattern) method to the returned strategy (pattern)?

Scenario: I'll have to convert different types (integer, bool, enums...). So i have created different strategies as this might extend in the future.

I created a factory class to select the approprioate strategy.

Is it a good practice to just pass the parameter to decide the strategy right further to the strategy-class itself as it will be used there anyway to proceed? Example: return new ConvertEnumToIntStrategy(valueToConvert)

Factory:

public static ConvertSourceValueStrategy GetStrategy(object valueToConvert)
{
    switch (valueToConvert)
    {
         case Enum e when e.GetType() == typeof(BeanstBerichtErhebung):
                return new ConvertBeanstBerichtErhebungToStringStrategy(); // pass valueToConvert?

         case Enum e:
                return new ConvertEnumToIntStrategy(); // pass valueToConvert?
         ...
     }
}

Example Strategy

public class ConvertEnumToIntStrategy : ConvertSourceValueStrategy
{
    public object Convert(object sourceValue)
    {
        return (int)sourceValue;
    }
}

Calling code:

var convertStrategy = ConvertSourceValueStrategyFactory.GetStrategy(sourceValue);
var valueToWrite = convertStrategy.Convert(sourceValue);

If i would pass the parameter, i could probably call it like the code below. But somebody could theoretically create a new strategy without a constructor for the parameter to pass as i can't force that with an Interface.

ConvertSourceValueStrategyFactory.GetStrategy(sourceValue).Convert();

How to decide whether a certain action should be done in the backend or the frontend?

So lately I have noticed that what dramatically reduces my productivity is spending time on trying to decide whether a certain action I should do on the backend or the frontend, modelling my databases and so on. And please keep in mind, I am trying to find the balance of being productive and at the same time keeping quality, and so it seems to me that I am falling into the "premature optimization is the root of all evil" thingy, in my case, reducing my productivity dramatically.

I am trying to figure out a, framework lets say, that will allow me to make these decisions easier.

For example, right now I am making a simple functionality, and I'll be specific, because it will be easier, so I have a functionality that allows the user to add a skill to the mongo document for skills, the problem occurs with the requirement that skills must be unique, for example only one skill named "Javascript" can be within the database, and so a check must be performed, the question is, where and how do I do the check?

There are of course many possibilities, but the two main ones I have in mind are:

1.

  • The user fills the form with the skill name
  • the data is sent to the backend
  • the backend attempts to create that skill
  • mongodb returns error that it already exists
  • error is sent back to the front end and displayed to the user

This approach works just fine, however the drawback imo, is it takes time and does not allow the user to see his mistake in "realtime".

2.

  • While the form is opening, send a get request to the server to get all currently existing skills is made
  • the user fills the form
  • as the user is filling the form, the check is performed in realtime with every pressed key, and so the user gets instant feedback if the skill already exists.

This would also work just fine, with the drawback, that if the collection of skills is huge, and a search must be performed on that collection at pressed key, processing will depend on the users device and the size of the collection, which could potentially lead to bad user experience.

So does this dilemma boil down to the expected amount of information to check against, if a collection is never expected to be huge enough to cause a problem do 2, if not, go with 1?

Do I start with the second approach and later move to the 1st if performance suffers at some point?

Do I go with 2 and use some more complex data structures that will allow for faster searches to mitigate that potential performance issue?

Keep in mind please, this is just one example, the same decision can be extrapolated to many other similar scenarios and thats whats tripping me.

Are Ports and Adapters supposed to abstract away the HTTP stack?

I am concerned about overengineering my code when thinking about Ports and Adapters architecture.

Two very common examples of the system contacting with the outside world are my HTTP stack and local filesystem. These are clear situations when the app is reaching out to the outside world, and testing will require certain amount of control and/or mocking.

My first though was: "Maybe I should have a central service or singleton and make sure any HTTP call goes through it"

For testing it would be amazing because I could force any test to crash if an unexpected call to the outside world is done without a mock or at least explicit concert by the developer. This also standardizes a single way to mock HTTP calls.

On the other side it feels like I am reinventing the wheel. I am a Javascript developer and the native library is not so good. Most people use a third party library which will spread as a dependency throughout the project.

My current approach is kind of re-inventing the wheel. I do create the abstraction layer (a service singleton) but keep it light using a third party library. The goal is trying to "contain" the spread of 3rd party library code over the project using a thin self made facade. Obviously things with a larger scope are an exception. For example abstracting away database access tends to cause more pain than glory.

Are self made abstractions for HTTP and local file system access a clear example of Ports/Adapters or just overengineering?

Kedro Conditional Pipes (or alternatives)

I am currently examining different design pattern options for our pipelines. Kedro framework seems like a good option (allowing to modular design pattern, visualization methods, etc.).

The pipelines should be created out of many modules that are either writting output to file or piping it to next module (depends on condition). In second case (pipe to next module) kedro falls of, as it reads the whole output into memory and then forwards to next step (or is there a possibility of unix-type pipeing)? I am working with Big Data, so this one is out for me. Why is this workflow different to a usual unix pipe? - unix pipes are reading in certain buffer size and forwarding it right away (I guess this gets swapped to disk and not kept in memory?). I would appreciate if you could point me to another framework that allows such functionality (I also don't mind implementing DP from scratch).

How to set RegEx global flag in HTNL pattern?

I want to client validate a form input (username + password) before sending it to the server (php). Therefore I applied the pattern attribute in the input tag. I came up with a RegEx expression that does the job on the server side:

(preg_match_all('/^[a-zA-Z0-9. _äöüßÄÖÜ@-]{1,50}$/', $_POST['username']) == 0)

thereby the global flag is set using preg_match_all (instead of preg_match.

Now I wanted to implement the same RegEx in my pattern attribute in the HTML form. HTML standard defines that RegEx in pattern follows RegEx in JavaScript, which devides the expression into "pattern, flags" devided by a comma. I would translate that into HTML like this:

pattern="^[a-zA-Z0-9. _äöüßÄÖÜ@-]{1,50}$,g"

That doesn't work. All JavaScript RegEx validators I have found enclose the pattern into slashes:

/^[a-zA-Z0-9. _äöüßÄÖÜ@-]{1,50}$/

and say, that the global flag would be bhind the last slash:

pattern="/^[a-zA-Z0-9. _äöüßÄÖÜ@-]{1,50}$/g"

That doesn't work either. Mozilla also states in their developer guide (I also read it elswhere):

No forward slashes should be specified around the pattern text.

So, how can I get the global flag into the pattern attribute of the input element?

dimanche 21 février 2021

I want a delegate object to access a private field of the main object

I want to structure my code the best way that's possible and I am facing a problem. I want to delegate the task of drawing it's data to another object. However, this other object needs to access a private field of the first object.

I have this piece of code:

class Grid {

    private val matrix = Array<Array<Int?>>(10) { Array(10) { null } }

    private val gridDraw = GridDraw(this)
    
    fun draw(canvas: Canvas) {
        gridDraw.draw(canvas)
    }
    ...
}

I want draw() method of GridDraw object to access matrix property. I can't do it if matrix is a private field and I don't want to make it public.

I don't like the idea of passing matrix inside draw method because in the future I would probably need to add more parameters to this method.

Is there a way to solve this problem?

Combined microservice for user and organisations

I am building a new microservice based application and decomposing it down by business capability. Where I am little unsure is around managing users and organisations. Basically, organisations should be created first and then users can be assigned to them. Should I have a single microservice that combines both users and organisations or separate them out?

how to add design patterns to my simple javafx project? [closed]

I need to use 2 design patterns for a simple ping pong game that I created for my upcoming project. I was using this guide : https://www.tutorialspoint.com/design_pattern/index.htm , But I can't seem to find a way to introduce any design patterns to this small project. Please help . This is my code it runs perfectly fine. I am using eclipse IDE.

Main.java:

package application;
    
import java.util.Random;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.canvas.Canvas;
import javafx.scene.canvas.GraphicsContext;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.TextAlignment;
import javafx.stage.Stage;
import javafx.util.Duration;

public class Main extends Application {
    
    //variable
    private static final int width = 800;
    private static final int height = 600;
    private static final int PLAYER_HEIGHT = 100;
    private static final int PLAYER_WIDTH = 15;
    private static final double BALL_R = 15;
    private int ballYSpeed = 1;
    private int ballXSpeed = 1;
    private double playerOneYPos = height / 2;
    private double playerTwoYPos = height / 2;
    private double ballXPos = width / 2;
    private double ballYPos = height / 2;
    private int scoreP1 = 0;
    private int scoreP2 = 0;
    private boolean gameStarted;
    private int playerOneXPos = 0;
    private double playerTwoXPos = width - PLAYER_WIDTH;
        
    public void start(Stage stage) throws Exception {
        stage.setTitle("Ping Pong");
        //background size
        Canvas canvas = new Canvas(width, height);
        GraphicsContext gc = canvas.getGraphicsContext2D();
        
        //JavaFX Timeline = free form animation defined by KeyFrames and their duration 
        Timeline tl = new Timeline(new KeyFrame(Duration.millis(10), e -> run(gc)));
        //number of cycles in animation INDEFINITE = repeat indefinitely
        tl.setCycleCount(Timeline.INDEFINITE);
        
        //mouse control (move and click)
        canvas.setOnMouseMoved(e ->  playerOneYPos  = e.getY());
        canvas.setOnMouseClicked(e ->  gameStarted = true);
        
        stage.setScene(new Scene(new StackPane(canvas)));
        stage.show();
        tl.play();
    }

    private void run(GraphicsContext gc) {
        //set graphics
        //set background color
        gc.setFill(Color.BLACK);
        gc.fillRect(0, 0, width, height);
        
        //set text
        gc.setFill(Color.WHITE);
        gc.setFont(Font.font(25));
        
        if(gameStarted) {
            //set ball movement
            ballXPos+=ballXSpeed;
            ballYPos+=ballYSpeed;
            
            //simple computer opponent who is following the ball
            playerTwoYPos = ballYPos - PLAYER_HEIGHT / 2;
            
            //draw the ball
            gc.fillOval(ballXPos, ballYPos, BALL_R, BALL_R);
            
        } else {
            //set the start text
            gc.setStroke(Color.WHITE);
            gc.setTextAlign(TextAlignment.CENTER);
            gc.strokeText("Click", width / 2, height / 2);
            
            //reset the ball start position 
            ballXPos = width / 2;
            ballYPos = height / 2;
            
            //reset the ball speed and the direction
            ballXSpeed = new Random().nextInt(2) == 0 ? 1: -1;
            ballYSpeed = new Random().nextInt(2) == 0 ? 1: -1;
        }
        
        //makes sure the ball stays in the canvas
        if(ballYPos > height || ballYPos < 0) ballYSpeed *=-1;
        
        //if you miss the ball, computer gets a point
        if(ballXPos < playerOneXPos - PLAYER_WIDTH) {
            scoreP2++;
            gameStarted = false;
        }
        
        //if the computer misses the ball, you get a point
        if(ballXPos > playerTwoXPos + PLAYER_WIDTH) {  
            scoreP1++;
            gameStarted = false;
        }
    
        //increase the speed after the ball hits the player
        if( ((ballXPos + BALL_R > playerTwoXPos) && ballYPos >= playerTwoYPos && ballYPos <= playerTwoYPos + PLAYER_HEIGHT) || 
            ((ballXPos < playerOneXPos + PLAYER_WIDTH) && ballYPos >= playerOneYPos && ballYPos <= playerOneYPos + PLAYER_HEIGHT)) {
            ballYSpeed += 1 * Math.signum(ballYSpeed);
            ballXSpeed += 1 * Math.signum(ballXSpeed);
            ballXSpeed *= -1;
        }
        
        //draw score
        gc.fillText(scoreP1 + "\t\t\t\t\t\t\t\t" + scoreP2, width / 2, 100);
        //draw player 1 & 2
        gc.fillRect(playerTwoXPos, playerTwoYPos, PLAYER_WIDTH, PLAYER_HEIGHT);
        gc.fillRect(playerOneXPos, playerOneYPos, PLAYER_WIDTH, PLAYER_HEIGHT);
    }
    
        // start the application
        public static void main(String[] args) {
        launch(args);
        }
}

Triangle pattern in java printing [closed]

enter image description here

Please help with this program

Extract a string between two set of patterns in Python

I am trying to extract a substring between two set of patterns using re.search().

On the left, there can be either 0x or 0X, and on the right there can be either U, , or \n. The result should not contain boundary patterns. For example, 0x1234U should result in 1234.

I tried with the following search pattern: (0x|0X)(.*)(U| |\n), but it includes the left and right patterns in the result.

What would be the correct search pattern?

design patterns for travel system

I have a small python project to work with 3 design patterns.

my idea is a travel book system (flight, train, bus) -> hier I tried to use the stratgy pattern to choise which way of travel (I'm not sure if that's right)

  • the user can book a place depens on the travel-type
  • the status of the trip can be changed from (availble - lated - canceled ) I tried to use State pattern

can you please help by implemnt an python example and correct me if i choised wrong design patterns.

thanks

Design a system of classes to filter messages at runtime in a Spring boot JMS app

I have a Springboot JMS application in which I have a class that is a component and receives messages from a JMS Queue/Topic since it implements the JMSLIstener Interface. My requirement is to have a design so that I can filter messages received like whether it is in XML or Json or plain text and have the specific Message processing class called to process the Message for further use.

Any sort of performance design ideas or system design ideas appreciated as I am new to system design.

vendredi 19 février 2021

Python OOP Design Pattern for Calculation Flows

I am relatively new to oop and had a quick question about the best way to approach coding a certain type of calculation. I'm curious if there's an established design pattern to approach this sort of problem.

Consider a chemical process flow where you convert materials (a,b) with attributes such as temperature, pressure, flow rate, etc. into a final product c. To get there, I need unit operations D,E,F... each with its own set of attributes (cost, size, etc.). I would only need information flow in one direction as closed loops will probably increase the complexity (if not, I would really appreciate insight into how closed loops would work).

a,b --> D --> E --> F --> c

Ultimately I would like to be able to do a system cost analysis, where I would sum up the cost attributes of D,E,F.

My current thought process to approach this is to define a "materials" object, then have D inherit materials, E inherit D... c inherit F then lastly a "system" object inherit c to analyze the system variables. Since I would like to be able to swap out D,E,F for say G,H,I, there also needs to be code for conditional inheritance where D must be able to accept inputs a,b (based on defined attributes) and E be able to inherit D for the same reason. One of the things I'm unsure of is how object c would be able to understand how to sum up attributes of all the inherited objects (probably based on some consistent naming convention of objects/attributes?).

Sorry for the somewhat lengthy question - if you are aware of AspenPlus, I'm looking to replicate a smaller scale version of this (ie no solvers) in Python. Thank you for reading through this!

Are you searching for a logo designer to create animal and pet logo?

This is a graphic designing team of professionals who are enthusiast to design amazing product branding. Working in this industry since past 4 years and always target to deliver some extraordinary product.

visit the link and contact : Click Now

How to design API to persistence layer?

Imagine the situation. There's a table with say 20 fields, like:

| n/n | name |
|-----|------|
| 0   | id   |
| 1   | foo  |
| 2   | bar  |
| ... | ...  |
| 20  | baz  |

and you need to design CRUD API for it. There's nothing complicated with create() and delete() methods, but update(..) and find(...) are real pain.

From UI perspective user can change or request a search by any of those fields and in any combination: update(foo=x, baz=y) or find(foo=x, bar<=y).

There are two pattern for DAL: Repository and DAO.

  1. Repository says "threat API like a collection of objects", so it's usually looks like that:

    Repository {
      replace(Pojo o)
      find(PojoSpec spec)
    }
    

    find() is ok, but using replace(Pojo o) means that we lose info about what fields has been actually changed. We have to either update the whole object or select-compare-update only changed fields (so +1 request, please don't tell about premature optimization, it's an API design question). Both options are sub-optimal, because DB also doesn't care about comparing values. It just rewrites all fields specified in the SQL query. What if table has 100 fields? 200? Would you rewrite 100 fields if just one of them has been changed?

  2. DAO is not really a pattern, it's just some persistence-oriented code around domain object with no real restrictions. So, API like findByFooAndBarAndBaz() is quite usual. It also doesn't solve update() problem though.

So, what's left? We could just pass changed fields as key-value pairs, but it's ugly and not type safe: replace(Map<String, Object> o). Type-safety can be fixed buy creating a metamodel, but exposing metamodel classes to services layer looks like sort of code smell.

The question is: what is the common approach to handle situations like that? Are there another DAL patterns? Am I right about metamodel code smell?