Trying to stop a spam bot with html5 pattern. Can regex be written to prevent the input field from ending in: lowercase, uppercase, uppercase?
Few of spam bot examples I'm trying to stop:
AprilWexKV
MayfielpHL
pinupkazinoNK
Trying to stop a spam bot with html5 pattern. Can regex be written to prevent the input field from ending in: lowercase, uppercase, uppercase?
Few of spam bot examples I'm trying to stop:
AprilWexKV
MayfielpHL
pinupkazinoNK
We are developing a web application and it should allow a person to do certain actions only if they are authorized. So, every method in the controller needs to check if he/she is authorized to execute the action. The backend is java and the frontend is javascript.
Something like below,
public class StudentDataInputController {
public ModelAndView getDataInputView(HttpServletRequest request,HttpServletResponse response) {
if (isAuthorized(request)) {
// Do something
}
}
public String saveInput(HttpServletRequest request,HttpServletResponse response) {
if (isAuthorized(request)) {
// Do something
}
}
}
I am wondering if there is any design pattern to enforce this for every action defined inside the class. One solution is to define an interface or abstract class and have a dedicated class for every action implementing the interface or extending abstract. But, it will result in a lot of classes and also, I don't think it is feasible given that the return type of every action varies. Any suggestion will be helpful
I want to build a class that can compose multiple objects and use any of their interfaces.
Class A can use any of the interfaces of Class B and C
B can use any of the interfaces of C
C can use any of the interfaces of B
I have the above functionality written in JavaScript and I was wondering what's the best and correct way to achieve the same using TypeScript:
import { findLast, isFunction } from "lodash";
class Composite {
constructor(behavior) {
this.behaviors = [];
if (behavior) {
this.add(behavior);
}
}
add(behavior) {
behavior.setClient(this);
this.behaviors.push(behavior);
return this;
}
getMethod(method) {
const b = findLast(this.behaviors, (behavior) =>
isFunction(behavior[method])
);
return b[method].bind(b);
}
}
class Behavior1 {
foo() {
console.log("B1: foo");
}
foo2() {
console.log("B1: foo2");
this.getMethod("bar")();
}
setClient(client) {
this.client = client;
}
getMethod(method) {
return this.client.getMethod(method);
}
}
class Behavior2 {
foo() {
console.log("B2: foo");
this.getMethod("foo2")();
}
bar() {
console.log("B2: bar");
}
setClient(client) {
this.client = client;
}
getMethod(method) {
return this.client.getMethod(method).bind(this);
}
}
const c = new Composite();
c.add(new Behavior1());
c.add(new Behavior2());
c.getMethod("foo")();
c.getMethod("bar")();
// Output:
// B2: foo
// B1: foo2
// B2: bar
// B2: bar
Link to codesandbox: https://codesandbox.io/s/zen-poitras-56f4e?file=/src/index.js
I have the following architecture of finacial app:
The transfer service needs additional two services: accounts and account history. At the moment it synchronously calls both of them. I started to think whether this is a good design for following reasons:
Maybe embedding dependent services in transfer service's deployment unit is better idea? I could use dependensy injection just to inject implementation of currently used interfaces and avoid calls over the network? (I know it does not solve problem in the first bullet)
What are patterns and anti patterns here?
PS: I cannot (and do not want to) call these services from the mobile app nor facade API.
How do companies like Facebook and Google implement privacy controls at scale. For example, Facebook has a select audience type which includes public,friends, "friends except...", only me, specific friends, and even custom. From an implementation and design standpoint, how do these companies handle this? Are they defining rule bases access controls, are they manually coding in these features, do they have a privacy model they use, or is it an hybrid approach. If anyone have links to public avaiable design docs, conference links, white papers, and even reseach papers, please feel free to share. Everytime I try to search for how company "X" does privacy controls, I get the "Business" talk on privacy or access controls as what it relates to data center which is not what I'm looking for.
I've to use a library and need to check (if this instance of that) a lot. For example:
if(myInterface instanceof Foo) {
Foo foo = (Foo) myInterface;
if(foo.name.equals("Alex")) {
// use function that can handle Foo with name "Alex"
handleAlexFooLogic(foo);
}
if(foo.name.equals("Michael") {
// use function that can handle Foo with name "Michael"
handleMichaleFooLogic(foo);
}
}
else if(myInterface instanceof Bar) {
Bar bar = (Bar) myInterface;
if(bar.name.equals("Smith")) {
// use function that can handle Bar with name "Smith"
handleSmithBarLogic(bar);
}
// ...
} else if(....) {
// ...
}
I was first thinking about the Factory pattern then I'm just stuck because something is so contradicting, that I cannot explaining.
I also want to separate the if(foo.name.equals("Name"))
part to a different class, to avoid too much unpredict nested if-else
So what is the appropriate design pattern for this situation? Thank you!
I wanted to print any English alphabet(s) using '*' or any other given special character like how a dot-matrix printer works.
I could come up with a function def printLetters(string, font_size, special_char):
which when passed with any letter would print that letter using the special character specified.
Consider the letter 'A':
def printLetters('A', 10, '&'): # would print the letter A within a 10x10 matrix using '&'
&&&&&&&&
& &
& &
& &
&&&&&&&&&&
& &
& &
& &
& &
& &
and such code snippets for every character. Example for 'A':
FUNCTION_TO_PRINT_A:
space = ' '
#print first line
print('', special_char*(font_size-2))
for i in range(1, font_size-1):
#print(i)
if font_size//2 == i:
print(special_char*(font_size))
print(special_char, space*(font_size-4), special_char)
printLetters(10, "&")
But when the parameter string
has more than one characters, it prints gibberish after first character.
So I just wanted some ideas/code-snippets which would print the first row of all characters in string
first and so on until the last row so that all those characters line up side by side horizontally on the console.
I have a RabbitMQ design question. Let say I have 6 exchanges and 10 queues and split up as below
I have a microservice application which runs Kubernetes with the scale of 25 and all these applications acquire 1 rabbitmq connection per process. So 25 rabbitmq connections act as producer.
I have another application which also runs in Kubernetes with the scale of 1 and these applications acquire 1 rabbitmq connection. So 1 rabbitmq connection act as a consumer.
Numbers: Let say every exchange gets 100k messages per day.
Tech stack: Node.js + amqplib
Questions:
Thanks in advance :)
I have a Python application that is executed to continually monitor the system to search anomalies. This project has connections to database to store information and a set of componentes that are in charge of different monitor tasks. Each component can be paused and resumed, and an in memory state (status, uptime, last anomaly detected, detection parameters...)
The question is: how can I expose the operations to pause and resumen (or even change the detection parameters) a component to a web client (for example a React webapp)?. All the options that I can think has problems:
Maybe there is something that I'm missing and the solution is easier than all of this.
I have been trying to figure out a pattern to satisfy the SOLID Dependency Inversion Principle while using Spring-boot in a Maven multi-module project. The goal is to have an abstraction layer between my message provider and consumer. That way I can swap out my message provider easily and keep things loosely coupled.
ModuleA -> Spring-boot Kafka Consumer (should be easily replaceable)
ModuleB -> Abstract Message Provider (should be able to transform messages)
ModuleC -> MyMessage Processor (should be able to use the transformed messages for business logic)
According to the SOLID principle:
ModuleC should depend on ModuleB
Module A should depend on ModuleB
Using Spring-boot with dependency injection in a Maven multi-module project complicates this form me.
In ModuleA I receive messages using Apache Kafka libraries, all contained in its own maven module.
In ModuleB I expose a Java LinkedBlockingQueue that ModuleA can fill with messages as they come in.
It's here that I transform the message. To make the messages available to ModuleC I expose an
Observable Class as a Spring @Component.
In ModuleC I Inject the ModuleB Component and add an Observer to detect new messages.
This all works and here is the code for all to see.
Is this just WRONG. Is there a correct Spring way to do this? Though it works, something just smells wrong about it, to me.
Thanks you.
I’m a php newbie in design patters, can anyone give me some examples of implementation in real life?
I have a Domain object Like this :
public class Document {
public string Index {get; private set;}
public string Title {get; private set;}
public string Content {get; private set;}
public Document (string index , string title, string content){
///some domain rule here
Index = index;
Title = title;
Content = content;
}
protected Document(){}
}
Now I want to construct objects of type Document and fill their properties when I am fetching data from storage without any ORM like dapper.
I want to know how do the Dapper or JsonConvert fill objects using protected constructors and private property setters?
Is this a common practice and generally recommended, also for useState
?
Would it generally be advisable to turn this...
{
"id": "123",
"author": {
"id": "1",
"name": "Paul"
},
"title": "My awesome blog post",
"comments": [
{
"id": "324",
"commenter": {
"id": "2",
"name": "Nicole"
}
}
]
}
...into something like this:
{
result: "123",
entities: {
"articles": {
"123": {
id: "123",
author: "1",
title: "My awesome blog post",
comments: [ "324" ]
}
},
"users": {
"1": { "id": "1", "name": "Paul" },
"2": { "id": "2", "name": "Nicole" }
},
"comments": {
"324": { id: "324", "commenter": "2" }
}
}
}
(example taken from here)
I know this was a thing with redux, but I'm struggling to decide whether it makes sense with newer things like useState
, useReducer
or just Reacts context api etc.
In my use case, it seems like I could benefit from doing it this way, but not by so much, since the way I want to show the data sort of concurs with the way it comes back from the backend.
I just found these definitions of Inheritance and Interface. Honestly I do not understand it. Inheritance offers feature of overriding. So why is it not considere losse coupling. Also you can exchange it for another implementation.
Inheritance : It does not provide the functionality of loose coupling
Interface: It provides the functionality of loose coupling.
I want to separate all my tables to separate files, so they can independently handle their own creation and existence. I want to know if my design is practical.
Firstly, inside the main
method, the database is instantiated. Next, I can register all my table's create
methods to the DatabaseProvider
before I open the database. Once I call open
on the DatabaseProvider
, it starts looping through its _helpers
and calling each of them if, and only if, the database is getting created for the first time.
MAIN METHOD
WidgetsFlutterBinding.ensureInitialized();
DatabaseProvider dbProvider = DatabaseProvider();
dbProvider.register(TodoHelper.onCreate);
await dbProvider.open();
DATABASE PROVIDER
typedef DatabaseCreator(Database db, int version);
class DatabaseProvider {
static DatabaseProvider _instance = DatabaseProvider._();
Database db;
List<DatabaseCreator> _creators;
DatabaseProvider._() {
_creators = List<DatabaseCreator>();
}
factory DatabaseProvider() {
return _instance;
}
Future open() async {
Directory directory = await getApplicationDocumentsDirectory();
String path = directory.path + 'notes.db';
db = await openDatabase(path, version: 1, onCreate: _createDB);
}
Future _createDB(Database db, int version) async {
_creators
.forEach((DatabaseCreator creator) async => await creator(db, version));
}
void register(DatabaseCreator creator) {
_creators.add(creator);
}
Future close() async => db.close();
}
So now, a table would look like this, for example:
class TodoHelper implements TableHelper {
static TodoHelper _instance = TodoHelper._();
DatabaseProvider databaseProvider;
static Future<void> onCreate(Database db, int version) async {
await db.execute('''
create table $tableTodo (
$columnId integer primary key autoincrement,
$columnTitle text not null,
$columnDone integer not null)
''');
}
TodoHelper._() {
databaseProvider = DatabaseProvider();
}
factory TodoHelper() {
return _instance;
}
}
Note: Both tables and the database are singletons. The onCreate
method is static because I don't want to instantiate all tables just to create the database so I just register their create functions instead. That would be a waste of resources.
I'm trying to create a subclass in a particular case and I can not attach attributes or method to it. I think the new / init usage is not clear to me but I could not find ways to do that from the internet.
Here is a minimal working toy example showing what I am trying to do.
# I have this
class Human():
def __init__(self):
self.introduction = "Hello I'm human"
def create_special_human():
special_human = Human()
do_very_complicated_stuffs(special_human)
special_human.introduction = "Hello I'm special"
return special_human
# I want to create this class
class SuperHero(Human):
def __new__(self):
special_human = create_special_human()
return special_human
def __init__(self):
self.superpower = 'fly'
def show_off(self):
print(self.introduction)
print(f"I can {self.superpower}")
human = Human()
special_human = create_special_human()
super_hero = SuperHero()
super_hero.show_off() # fails with error "type object 'Human' has no attribute 'show_off'"
print(super_hero.superpower) # fails with error "type object 'Human' has no attribute 'superpower'"
I want to create the subclass Superhero
, and I need to initialize it with what is returned by create_special_human()
, because this function is very complex in the real case. Moreover, I can not modify the Human
class and create_special_human()
.
I am aware that the returned type is Human, which is wrong, but I don't know why that happens.
I have a Car
object that has several properties. Each of its properties are populated using a service (generally one property per service). Each of those services generally call a 3rd party web service (e.g. carClient
) to get its data. Most of my services also have logic on how to populate its Car
object field. For example:
@Service
@RequiredArgsConstructor
public class CarPriceService {
// client of a 3rd party web service interface
// I don't have control over this interface.
private final CarClient carClient;
public void setAutoPrice(Set<Car> cars) {
// in this case, only one call to the web service
// is needed. In some cases, I need to make two calls
// to get the data needed to set a Car property.
Map<String, BigDecimal> carPriceById =
carClient.getCarPrice(cars.stream().map(c->c.getId()).collect(Collector.toSet()));
for (Car car : cars) {
// in this case the poulating logic is simple
// but for other properties it's more complex
BigDecimal autoPrice = autoPriceById.get(car.getId());
car.setAutoPrice(autoPrice);
}
}
}
The order of populating the Car
properties is sometimes important. For example, CarValueService
sets car.value
using car.condition
which is set by CarConditionService
.
Is there a design pattern that works for handling the gradual build of an object over services? I'm aware of the Builder
pattern but not sure how it would apply here.
I am trying to model Team and Players relationship in terms of writable code following OOP.
Let's say I have a class Team
and Player
For representing the relationship between both, which option is better & why?
What are the pros & cons of each?
Option A
class Team {
// inside team class
List<Player> players;
}
Option B
//separate class
class TeamPlayers {
Team team;
List<Player> players;
}
I have a list of gene names that I am trying to filter out of a larger data set using grepl. For example:
gene_list <- c(geneA, geneB, geneC)
data <- c(XXXgene1, XXXgene2, XXXgeneF, XXXgeneA, XXXgeneB)
select_grepl <- data %>% filter(grepl(c(gene_list), data)==T)
I have tried the grepl code above but since the pattern is > 1 they only use the first geneA to search within the string. If I change c(gene_list) to a single pattern like "geneA", then the code works. Is there another solution?
Should I loop over a component and pass the item to that component or pass the array to the component and loop in there component? Is there some sort of design pattern choice here?
Is there any design pattern involved to implement count of visitors visit a web site.
Also what is the basis to evaluate which design patterns to be used, may be my question sounds generic but in terms of having better code maintainability , for scalability & performance how to choose best set of design patterns
Thanks
The problem relates to the tests design. I'm attaching a pseudo code. let's assume that:
Suppose this is an extended form which:
<form>
<input name="firstName" disabled={isFormSubmitting} />
<input name="lastName" disabled={isFormSubmitting} />
<input name="email" disabled={isFormSubmitting} />
</form>
Here the pseudocode for tests:
// APPROACH 1 - one field, single tests, single assertion
describe('first name field', () => {
test('should disable field when form is submitting', () => {});
test('should display "required" error when form has been submitted without value', () => {});
test('should send analytics event when user has started filling this field as the first one ', () => {});
test('should send analytics event when user has committed an error', () => {});
});
describe('last name field', () => {
/* the same tests + the ones specifir for the last name field */
});
describe('email field', () => {
/* the same tests + the ones specifir for the email field */
});
// APPROACH 2 - tests for all fields at once if business logic is the same for all fields
test('should disable all fields when form is submitting', () => {});
test('should display "required" error for all fields when form has been submitted without values', () => {});
test('should send analytics event with field name when a user has started filling any field', () => {});
test('should send analytics event with field name when a user has committed an error for any field', () => {});
// but where tests which busines logic is specific for particular fields?
// APPROACH 3 - group by business logic. "one business logic", single tests, single assertion
describe('disabling fields', () => {
test('should disable first name field when form is submitting', () => {});
test('should disable last name field when form is submitting', () => {});
test('should disable email field when form is submitting', () => {});
});
describe('showing required error', () => {
test('should display "required" error for first name field when form has been submitted without value', () => {});
test('should display "required" error for last name field when form has been submitted without value', () => {});
test('should display "required" error for email field when form has been submitted without value', () => {});
});
describe('sending "a user started filling a field" analytics event', () => {});
describe('sending "a user committed an error" analytics event', () => {});
My question is which approach is better:
Suppose you have a simple aggregate root like this:
Playlist {
String name
List<Song> songs
add(Song song) {
// Some business rules
songs.add(song)
}
}
Now suppose you want to introduce a business rule in the add(Song)
method that depends on other aggregate roots. For example: A song may not appear in more than 3 playlists. One way to do this would be to fetch this information (number of playlists containing the song) in the application layer and pass it to the add(Song)
method.
But now suppose furthermore that this business rule only applies under certain conditions. Imagine for example that playlists whose name starts with "M" don't have such limitation (completely arbitrary). Now fetching the information at the application layer would mean either implementing domain logic at the wrong level, or fetching data that you won't use. As business rules become more complicated this becomes more costly.
Now the obvious solution is: Use a domain service that has access to the Playlist repository and do your logic there. While this works, I was wondering if there is any pattern/architectural tip/reorganization that could be done to solve this problem without using a service to encapsulate the logic?
Thanks
I am learning design pattern in python and the subject is Singleton Objects so, I was writing my main code as PRO003 and import it into PRO004. This is PRO003 Code:
class SingletonObject(object):
class __SingletonObject:
def __init__(self):
self.name = None
def __str__(self):
return '{0!r} {1}'.format(self, self.name)
def _write_log(self, level, msg):
with open(self.name, 'a') as log_file:
log_file.write('[{0}] -> {1}\n'.format(level, msg))
def critical(self, msg):
self._write_log('CRITICAL', msg)
def error(self, msg):
self._write_log('ERROR', msg)
def warning(self, msg):
self._write_log('WARNING', msg)
def info(self, msg):
self._write_log('INFO', msg)
def debug(self, msg):
self._write_log('DEBUG', msg)
instance = None
def __new__(cls, *args, **kwargs):
if not SingletonObject.instance:
SingletonObject.instance = SingletonObject.__SingletonObject
return SingletonObject.instance
def __getattr__(self, name):
return getattr(self.instance, name)
def __setattr__(self, name):
return setattr(self.instance, name)
And The Out And This is PRO004 code:
from PRO003 import SingletonObject
obj1 = SingletonObject()
obj1.name = 'logger.txt'
obj1.error('This Code Have An Error')
print('File Name: ', obj1.name, 'Object Location: ', obj1)
obj2 = SingletonObject()
obj2.name = 'logger.txt'
obj2.warning('Be Careful About This Bug')
print('File Name: ', obj2.name, 'Object Location: ', obj2)
But This Is The Output:
Traceback (most recent call last):
File "D:\PYTHON PROJECTS\LEARN\DesignPatterns\S01\PRO004.py", line 5, in <module>
obj1.error('This Code Have An Error')
TypeError: error() missing 1 required positional argument: 'msg'
[Finished in 0.097s]
I think this code want self, but self is not giving and it is by class and it must not entered this is my idea but I do not know any more! What is the Problem Of This Code ? Help Me ! Thank you !!!
may i know how to ( in Perl ) , generate below All Possible Patterns in a file and on screen output , and each slot in the pattern can be accessed , ?!
many thanks for all ,
input value ,
1 , no. of slots ,
2 , no. of objects ,
for example ,
no. of object = 2 , { a , b } ,
no. of slots = 4 ,
then , output ,
no. of all possible patterns = 2^4 = 16 ,
then ,
row is 16 ,
column is 8 ,
eachSlot[i][j] = allow assign or change its value ,
then , output format look like ,
a a a a
a a a b
a a b a
a a b b
a b a a
a b a b
a b b a
a b b b
b a a a
b a a b
b a b a
b a b b
b b a a
b b a b
b b b a
b b b b
and ,
if see 'a' , then do sth actionX ,
if see 'b' , then do sth actionY ,
many thanks for all the advices and helps ,
As part of design decision, the components(microservice) involved in http request-response flow are allowed to produce messsages on a kafka topic, but not allowed to consume messages from kafka topic.
Such components(microservice) can read & write database, talk to other components, produce messages on a topic, but cannot consume messages from a kafka topic.
What are the design flaws, if such components consume kafka topics?
Hey everybody and first of all forgive my poor english.
I have to implement the pattern "Multiplex" as described in "The Little Book of Semaphores" by Allen. B.Downey (it's a free resource).
I can't and I don't want use semaphores introduced in C++20 and so, only using mutex and condition variable, I came to the following code, maybe clumsy and twisted (spoiler):
/*
PATTERN: Multiplex
TARGET: allows multiple threads to run in the critical section at the
same time, but it enforces an upper limit on the number of concurrent
threads.
In other words, no more than n threads can run in the critical section at
the same time
*/
//#include "stdafx.h" // Only for MS Visual Studio
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <thread>
#include <string>
#include <vector>
using namespace std;
//#define IF_EXPIRES_ON_ONLINE_COMPILER // comment/uncomment it if you need
mutex mtx_IO; // No interleaved output
vector<int> deb_evolution_of_threads_In_CR; // only for debug purposes
const int iterationForcpuConsumer = 1000;
void cpuConsumer(thread::id tid) // the first thing that came to my fingers
{
#ifndef IF_EXPIRES_ON_ONLINE_COMPILER
{
lock_guard<mutex> lg(mtx_IO);
cout << "\n\tBEG cpuConsumer from #thread = " << tid;
}
string str = "str";
for (int i = 0; i < iterationForcpuConsumer; ++i)
{
int j = i;
try
{
str += str;
}
catch (...)
{
str = "";
}
}
{
lock_guard<mutex> lg(mtx_IO);
cout << "\n\tEND cpuConsumer from #thread = " << tid;
}
#else
this_thread::sleep_for(chrono::milliseconds(1000));
#endif // !IF_EXPIRES_ON_ONLINE_COMPILER
}
const int totalNumThreadLaunched = 5;
const int upperLimitForThreadInCriticalRegion = 3;
const int nrOfIterations = 5;
mutex mtx_CR;
condition_variable cv;
int threads_In_CR = 0;
void threadLogic()
{
for (int i = 0; i < nrOfIterations; ++i)
{
{
lock_guard<mutex> lg(mtx_IO);
cout << "\nElaboration that precedes the critical region for #thread = " << this_thread::get_id();
}
unique_lock<mutex> ul(mtx_CR);
cv.wait(ul, []() {return (threads_In_CR < upperLimitForThreadInCriticalRegion); });
++threads_In_CR;
deb_evolution_of_threads_In_CR.push_back(threads_In_CR); // only for debug purposes
ul.unlock();
cpuConsumer(this_thread::get_id()); // Critical Region
{
lock_guard<mutex> lg(mtx_CR);
--threads_In_CR;
deb_evolution_of_threads_In_CR.push_back(threads_In_CR); // only for debug purposes
}
cv.notify_one();
{
lock_guard<mutex> lg(mtx_IO);
cout << "\nElaboration that follows the critical region for #thread = " << this_thread::get_id();
}
}
}
int main()
{
int DEBUG = 0;
deb_evolution_of_threads_In_CR.push_back(0);
vector<thread> vThreads;
vThreads.reserve(totalNumThreadLaunched);
for (int i = 0; i < totalNumThreadLaunched; ++i)
{
vThreads.push_back(thread(threadLogic));
}
for (int i = 0; i < totalNumThreadLaunched; ++i)
{
if (vThreads[i].joinable())
{
vThreads[i].join();
}
}
for (auto i = deb_evolution_of_threads_In_CR.begin(); i != deb_evolution_of_threads_In_CR.end(); ++i)
{
cout << "\n" << *i;
}
return 0;
}
Here a link to Coliru.
I thought and thought again, I analyzed and reanalyzed, I watched the outputs (but you know that they are not a proof) but now I need a comparison.
Can you tell if this code is correct? And if not, where are the traps? Every other suggestion about a better design (inside the constraints of C++11/14) is well accepted.
PS: I suppose that something might be declared 'atomic' (correct me if I'm wrong) but anyway I didn't study deeply the C++ memory model and so suggestions in that direction are well accepted in any case but, at the moment, these notions are not at the top issue list; if I suppose the I don't really know something I don't want use it.
Finally: can you suggest some metodology, some tool, somewhat that can guide the approach to this kind of code/problems? I was thinking to Petri Nets
Probably this will not be my last question about the implementation of some similar patterns, I hope it will also join you in the next discussions.
Thank for your attention and for your time
Need to process massive list of files.
The part I'm interested in has this pattern. (Note one or more of the patterns maybe not exist in the current logs, they only report if there is an error).
Which is why I search for pattern and then by error. Actually the logs are much longer with date and time info, which is not needed.
Ff bb Change: [2:0:1] ALPA (0x13211) Port WWN (c37076082034003d) Le Fg Count changed by (3) (8 - 5) St Lf Count changed by (11) (57 - 46) Pz Sq Ed Count changed by (2) (7 - 5) Ip Tp Wq Count changed by (52) (212 - 160)
What I need to do is:
Ff bb Change: [2:0:1] which is the port, so need just 2:0:1, I need to keep the errors on the line with the port.
Also need Port WWN (c37076082034003d) and then one of the errors like Le Fg Count changed by (3) or St Lf Count changed by (11)
Output needed would look like:
2:0:1 c37076082034003d 3
The I can use that output to sort by 2:0:1 and c37076082034003d an sum the 3
Every thing I tried just throws various errors over the last 2 days of trying.
I have an api which is consumed by a mobile client (the app) and a browser client (back office). Now as it has started to grow and I need to keep it as clean as possible I will create two different api's one for back office and one for the app. The problem I found is that I do not want to duplicate code, I hate it I know is a bad practice for known reasons. So, the database is exactly the same, as you can image. I am using mongo with mongoose. So what I would like to achieve, at a high level would be something like this
DATABASE Api-1 Api-2
Both apis hitting the same database code.
I thought creating a different repo for the database, but I am just imagining and guessing because I dont really know how to approach to this. And if I create a different repo..how can I "import" it in both apis?.
I really appreciate your help, and every proposal or idea is more than welcome
Thank you in advance.
It's taken from interview question. You have button in the center of UIViewController that when tapped, returns one of actions enum types. Depending on the action there should be different behaviour. Like:
In future there should be more complex actions that either change UIViewController or use native or 3rd party libs. Because there is nothing common between those action, I would just write simple Switch and do everything inside UIViewController. Do you know a smarter way?
Do you know a site having tutorials, to learn design patterns (implemented in Typescript) for free (or if not possible, in a paying version) ? It would be great to be near to 20 patterns to learn (if less and good quality, it s ok). tks,
I am writing a tool which runs several processes. These processes exchange information via message queue. It uses a config file for basic setting and writes to a log. So i pass a queue, a log object and the config down the structure of my program.
SomeClass(log, config, queue)
-> SomeClassLevel2(log, config, queue)
--> SomeClassLevel3(log, config, queue)
--> AnotherClass(log, config)
---> SomeClassLevel4(log, config)
So basicaly every class gets passed the same stuff and i have lines like this:
self.static_cluster_definition = StaticClusterDefinition(self.log, self.config)
self.dynamic_cluster_definition = DynamicClusterDefinition(self.log, self.config)
self.logic_cluster_definition = LogicClusterInformation(self.log, self.config)
self.host_definition = HostDefinition(self.log, self.config)
self.shutdown_vm = ShutdownVM(self.log, self.config)
self.vm_server_list = VMServerList(self.log, self.config)
self.vm_index = VMIndex(self.log, self.config)
Now i want to provide statistics, which have to be gathered from all over the place. So i have to introduce another object, which is passed down.
One day i would have to pass like 30 objects down the whole code structure.
Is there a better way to do this?
my question is : How to take my business logic out of controller and transfer it to a service ??? I am currently using two separate controllers for Post model in Laravel. One for user-related logic and one for administrator-related logic. pseudo code for AdminPostController :
class AdminPostController
{
public function index(MaybyIndexRequest $request)
{
$something = do lines of calculation
return return PostResource::collection($something);
}
public function storeAdminPost(StorePostRequest $request)
{
$something = do lines of calculation
return return PostStoreResource::collection($something);
}
}
pseudo code for UserPostController :
class UserPostController
{
public function maybyUserindex(AnotherIndexRequest $request)
{
$something = do lines of calculation
return return UserPostResource::collection($something);
}
public function storeUserPost(OtherStorePostRequest $request)
{
$something = do lines of calculation
return return UserPostStoreResource::collection($something);
}
}
I want to transfer the business logic of these two controllers to another class and call them with the help of, for example, a Facade like : class AdminPostController { public function index(MaybyIndexRequest $request) { $something = PostService::($request); return return PostResource::collection($something); }
public function storeUserPost(StorePostRequest $request)
{
$something = PostService::Store($request);
return return PostStoreResource::collection($something);
}
}
But I do not know with what design patterns I should do this. Or what I'm looking for is not a good way to get the code out of the controller !!! The way to solve this problem came to my mind : factory pattern : a class that has two methods called user() and admin().
class PostFactory
{
public function AdminCommands()
{
return new AdminPostCommands(); // a class that contains admin
}
public function UserCommands()
{
return new UserPostCommands(); // a class that contains user related logics
}
}
That the user method returns an instance of UserPostCommands class (including the user's logic) and the AdminCommands class method (contains the's post logic) .... or :
class PostFactory
{
public function Factory(User $user)
{
if ($user->isAdmin){
return new AdminPostCommands(); // a class that contains admin
}else{
return new UserPostCommands(); // a class that contains user related logics
}
}
a class that it takes an instance of the authorized user to decide whether the AdminPostCommands OR UserPostCommands class should be Returned. each of these two classes(AdminPostCommands or UserPostCommands ) has different methods. For example, the user may not be able to delete a post . Of course, user-related methods will only be used in the user controller and vice versa.
I am creating a tab navigator which listen to my database and renders 5 different icons, one of them with a badge.
Currenlty, I am making this with a switch-case, to avoid returning the same component with different props 5 times. But the reallity is that it doesn't look really professional. Any design pattern to refactor this code?
let iconName;
let iconType = "material-community"; // app default icons from material-community
let badgeNumber;
switch (route.name) {
case "Home":
iconName = "home";
break;
case "Interactions":
iconName = "heart";
badgeNumber = props.notifications;
break;
case "Camera":
iconName = "camera";
break;
case "Search":
iconName = "search";
iconType = "material";
break;
case "Profile":
iconName = "person";
iconType = "material";
break;
}
return (
<BadgedIcon
number={badgeNumber}
name={iconName}
type={iconType}
color={color}
size={24}
badgeStyle={styles.interactionsBadge}
/>
);
I'm unable to return a unique_ptr from a class member fuction, while implementing the Builder Design Pattern. As part of the builder design pattern, I want to create an object using the builder and transfer the ownership of the smart pointer to the client code. However, as I understand from the compilation error, I see that there is some problem in returing a unique_ptr from a class member function.
// Progarm to demonstrate builder design pattern.
#include <iostream>
#include <memory>
class person
{
std::string name_ {};
uint8_t age_ = 0;
std::string uniqueId_ {};
person(std::string name):name_(name) {
}
public:
// Person Builder
class personBuilder;
// Public member function to print his info.
void displayPersonInfo()
{
std::cerr << "\nName:" << name_
<< "\nAge:" << std::to_string(age_)
<< "\nUniqueId:" << uniqueId_
<< "\n";
}
// Destructor
virtual ~person()
{
std::cerr << "\nDestroy Person Object\n";
}
};
class person::personBuilder
{
std::unique_ptr<person> pThePerson;
public:
personBuilder(std::string name)
{
pThePerson = std::make_unique<person>(name);
}
personBuilder & age(const uint8_t age)
{
pThePerson->age_ = age;
return *this;
}
personBuilder & uniqueId(const std::string uniqueId)
{
pThePerson->uniqueId_ = uniqueId;
return *this;
}
std::unique_ptr<person> build()
{
return pThePerson;
}
};
int main(int argc, char** argv)
{
std::unique_ptr<person> myPerson = person::personBuilder("Sachin Tendulkar")
.age(40).uniqueId("AABBCC").build();
myPerson->displayPersonInfo();
return 0;
}
The following is the compilation error that I'm getting.
$ g++ 04_builder_02_short.cpp
04_builder_02_short.cpp: In member function ‘std::unique_ptr<person> person::personBuilder::build()’:
04_builder_02_short.cpp:58:16: error: use of deleted function ‘std::unique_ptr<_Tp, _Dp>::unique_ptr(const std::unique_ptr<_Tp, _Dp>&) [with _Tp = person; _Dp = std::default_delete<person>]’
return pThePerson;
^~~~~~~~~~
In file included from /usr/include/c++/8/memory:80,
from 04_builder_02_short.cpp:3:
/usr/include/c++/8/bits/unique_ptr.h:397:7: note: declared here
unique_ptr(const unique_ptr&) = delete;
^~~~~~~~~~
/usr/include/c++/8/bits/unique_ptr.h: In instantiation of ‘typename std::_MakeUniq<_Tp>::__single_object std::make_unique(_Args&& ...) [with _Tp = person; _Args = {std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&}; typename std::_MakeUniq<_Tp>::__single_object = std::unique_ptr<person>]’:
04_builder_02_short.cpp:41:51: required from here
/usr/include/c++/8/bits/unique_ptr.h:835:30: error: ‘person::person(std::__cxx11::string)’ is private within this context
{ return unique_ptr<_Tp>(new _Tp(std::forward<_Args>(__args)...)); }
^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
04_builder_02_short.cpp:11:5: note: declared private here
person(std::string name):name_(name) {
^~~~~~
$
There's only one problem with it -- it doesn't work. Why not? The most obvious reason is that the writes which initialize instanceand the write to the instance field can be reordered by the compiler or the cache, which would have the effect of returning what appears to be a partially constructed Something. The result would be that we read an uninitialized object. There are lots of other reasons why this is wrong, and why algorithmic corrections to it are wrong.but after java1.2, JMM has undergone a fundamental change, allocating space, initialization, and calling the construction method will only be completed in the working storage area of the thread.When there is no copy assignment to the main storage area, it is absolutely impossible for other threads to see this process. And the process of copying this field to the main memory area, there is no possibility that the space is not initialized or the construction method is not called after the space is allocated.
public class SingletonDemo {
private static SingletonDemo instance = null;
private SingletonDemo() {
}
public static SingletonDemo getSingletonDemo() {
if (instance == null) {
synchronized (SingletonDemo.class){
if (instance == null) {
instance = new SingletonDemo();
}
}
}
return instance;
}
I'm converting a project from Objective-C to Swift, and am running into a lot of bugs based on the change from an NSDictionary being a class that copies by reference to a Dictionary being a struct that copies by value. Here's a simplified example:
var recentMessages = [String: [String]]()
func logMessage(_ message: String, forChannel channel: String) {
let channelMessages = self.recentMessages[channel]
channelMessages.append(message)
}
In Objective-C, that updated the recentMessages
property. In Swift, that only updates the channelMessages
variable in the function scope, and I have to copy the change back to the property:
var recentMessages = [String: [String]]()
func logMessage(_ message: String, forChannel channel: String) {
let channelMessages = self.recentMessages[channel]
channelMessages.append(message)
self.recentMessages[channel] = channelMessages
}
This workaround isn't difficult, and this answer called it the best approach four years ago. But it is adding a lot of clutter and I'm afraid of forgetting to apply it every time. Is there a way to more directly replicate the previous behavior?
I could avoid creating the local variable and update the property directly, but that seems like a big limitation and in more complex cases that will make the code hard to read:
var recentMessages = [String: [String]]()
func logMessage(_ message: String, forChannel channel: String) {
self.recentMessages[channel].append(message)
}
In cases where the dictionary will be used repeatedly and with predictable keys, I think creating a custom class with properties that support all the keys would solve it. But I have places where a dictionary could include arbitrary keys that aren't predefined, or where a dictionary is only used briefly and creating a class for it would be overkill.
Is there another approach I'm missing that would restore that "copy by reference" behavior my current codebase depends on?
I'm writing a simple email verifier. I have a working solution, but it uses a wall of if-statements that all just return false. Is there a cleaner way or a design pattern for this kind of problem? (I only included the code I want to simplify)
if (prefix.length() == 0 || domain.length() == 0 || topLevelDomain.length() < 2) { // if prefix or domain length == 0, or topLevelDomain < 2
return false;
} else if (!isBuiltFrom(prefix, alpha + digit + special)) { // if any char in prefix is not (a-z), (0-9), '_', '.' or '-' return false
return false;
} else if (!isBuiltFrom(domain, alpha + digit + "-")) { // if any char in domain is not (a-z), (0-9), or '-' return false
return false;
} else if (!isBuiltFrom(topLevelDomain, alpha)) { // if any char in topLevelDomain is not (a-z) return false
return false;
} else if (special.contains("" + prefix.charAt(0))) { // if prefix leading special char return false
return false;
} else if (special.contains("" + email.charAt(prefixIndex - 1))) { // if prefix trailing special char return false
return false;
} else if (special.contains("" + domain.charAt(0))) { // if domain leading special char return false
return false;
} else if (special.contains("" + email.charAt(domainIndex - 1))) { // if domain trailing special char return false
return false;
}
return true;
I would like to construct a robot with or without a tool, a mobile base, and other parts. As I want to automatize the configuration of the parts, I have a class Robot with the parts as template arguments
For instance, in the code below, the code will build as long as we use tools that have the same constructor signature as ToolInterface. It does build with a Screwdriver but does not with a Gripper.
#include <iostream>
#include <string>
class ToolInterface
{
public:
ToolInterface(std::string _name):name{_name}{};
std::string name;
bool param_1;
char param_2;
};
template<class T, class... Args>
constexpr T* construct(Args... args)
{
if constexpr (std::is_same<T, nullptr_t>::value)
{
return nullptr;
}
else
{
return new T(args...);
}
};
template<class Tool>
class Robot
{
protected:
Tool* tool;
public:
Robot():tool(construct<Tool>("tool")){ // <--- here is my problem !!
if constexpr (! std::is_same<Tool, nullptr_t>::value)
{
//do stuff on/with tool->param_1, tool->param_2, ...
std::cout << "tool configured" << std::endl;
}
else
std::cout << "no tool" << std::endl;
};
};
class Screwdriver : public ToolInterface
{
public:
Screwdriver(std::string _name):ToolInterface(_name){};
};
class Gripper : public ToolInterface
{
public:
Gripper(std::string _name, bool _reversed):
ToolInterface(_name)
,reversed{_reversed}{};
bool reversed;
};
int main()
{
Robot<Screwdriver> robot_screwdriver;
Robot<nullptr_t> robot_null;
//Robot<Gripper> robot_gripper; //does not build
return 0;
}
Here are some ideas :
template<class Tool1, class Tool2, class MobileBase, class Camera> class Robot
solution 1 would look like
struct ToolConfig
{
std::string name;
};
struct GripperConfig : public ToolConfig
{
bool reversed;
};
class Gripper : public ToolInterface
{
public:
Gripper(ToolConfig& _config):
ToolInterface(_config)
,reversed{static_cast<GripperConfig&>(_config).reversed}{};
bool reversed;
};
Do you have a magic pattern to solve my problem ? Is my pattern wrong ?
I would like to ask if this is a sensible component design pattern in React.
Let's say I have the following components, App, ContentContainer and WithBlueBackground. The idea is to use a Ref
to set a blue background on the ContentContainer with the WithBlueBackground component.
The simplified code would look something like this.
// App.js
export function App() => {
const contentContainerRef = useRef();
return (
<ContentContainer contentContainerRef={contentContainerRef}>
<WithBlueBackground contentContainerRef={contentContainerRef}>
</WithBlueBackground>
</ContentContainer>
)
}
// ContentContainer
export function ContentContainer() => {
const contentContainerRef = useRef();
return (
<div ref={contentContainerRef}>
// Some content
</div>
)
}
// WithBlueBackground
export function ContentContainer(props) => {
useEffect(() => {
if (props.containerRef && props.contentContainerRef.current) {
props.contentContainerRef.current.style.backgroundColor = 'blue';
}
}, [props.contentContainerRef])
return <>{ props.children }</>;
}
This way if I want to have a green background in the content container I can create a new component that sets this style without the ContentContainer having to know about this. This increases the composability of the code which is promote in the react docs.
Nevertheless, passing the refs is a bit ugly.
My question is, is this a sensible pattern and if not is there another way to achieve what I am trying to do here.
How do I create a function generic enough that it doesn't have to use many switch statements within it to check what type of database the user chose?
My current approach is:
If a database type is supported, have a generic WriteData() function that handles all the credential details of that specific database type that were passed by the user.
Have a struct for each database type: mysql, postgres, connection string, etc...
Have a struct to represent each type of credential information used by the specific database
Marshal data into the struct depending which database type was chosen
Use maps like this:
var GetNewDB = map[string]interface{}{
"dbType1": dbType1{},
"dbType2": dbType2{},
"dbType3": dbType3{},
"dbType4": dbType4{},
"dbType5": dbType5{},
}
var GetCredentials = map[string]interface{}{
"dbType1": Type1Creds{},
"dbType2": Type2Creds{},
"dbType3": Type3Creds{},
"dbType4": Type4Creds{},
"dbType5": Type5Creds{},
}
Access generically the details of whatever database is chosen:
whateverDatabase := GetNewDB[dbTypeUserChose]
dbCredentials := GetCredentials[dbTypeUserChose]
In the above example, it doesn't necessarily matter that the variables are of type interface{}
Ultimately, this isn't working because each database needs specifics at certain points during the function - e.g. that one type of database needs a username and password, while another may not. It seems to be only solvable by dumping in many type switches or switch statements to give the specifics.
In cases where there is an object handling multiple other objects, how can the ownership be expressed at initialization?
For examples sake, let's say there is a Chicken hatching multiple eggs. It would not be good for the chicks to be without a parent, but the Chicken should also only focus its attention to its chicks. If this kind of relationship should be expressed at initialization, how would it be possible?
Which design pattern would be the best to use in this scenario?
It would be preferable to avoid using null
if possible, because that might introduce ambiguity into the system. If it's unavoidable to use it, how can the ambiguity best be minimzed?
Example program:
public class MyClass {
/**
* Handles eggs
* */
public static class Chicken{
private Egg[] eggs;
public Chicken(Egg... eggs_){
eggs = eggs_;
}
public void accept_signal(String message){
/* ... */
}
}
/**
* Signals when its ready to hatch
* */
public static abstract class Egg{
private final Chicken parent;
public Egg(Chicken parent_){
parent = parent_;
}
public void hatch(){
parent.accept_signal("chirp chirp");
}
}
/**
* The resulting children to be handled
* */
public static class YellowChick extends Egg{
public YellowChick(Chicken parent_){
super(parent_);
}
}
public static class BrownChick extends Egg{
public BrownChick(Chicken parent_){
super(parent_);
}
}
public static class UglyDuckling extends Egg{
public UglyDuckling(Chicken parent_){
super(parent_);
}
}
public static void main (String[] args){
Chicken momma = new Chicken(
// new YellowChick(), new BrownChick(), new UglyDuckling() /* How can these objects be initialized properly? */
);
}
}
I have created a Rest API that takes a request and gives response to the client. But My API is dependent on a third party service, that instead of giving a response, give a callback to my other endpoint. In order to send the service I need to wait for the callback to be received. How can I achieve it?
My Rest API that needs to send the response.
@POST
// @Produces(MediaType.TEXT_XML)
// @Consumes(MediaType.TEXT_XML)
public ConnectResponse postQuestionnaire(String connectString, @Context HttpHeaders headers) {
logger.info("---------- in connect post request ----------------------");
logger.info("---------- in connect post request ----------------------");
logger.info("---------- in connect post request ----------------------");
logger.info("---------- in connect post request ----------------------");
logger.info("---------- in connect post request ----------------------");
logger.info("---------- in connect post request ----------------------");
logger.info("---------- in connect post request ----------------------");
for (Entry<String, List<String>> entry : headers.getRequestHeaders().entrySet()) {
logger.info("Key = " + entry.getKey() + ", Value = " + entry.getValue());
for (String eachEntry : entry.getValue()) {
logger.info("eachEntry " + eachEntry);
}
}
logger.info("USSD received " + connectString);
logger.info("---------- in connect post request ----------------------");
logger.info("---------- in connect post request ----------------------");
logger.info("---------- in connect post request ----------------------");
logger.info("---------- in connect post request ----------------------");
logger.info("---------- in connect post request ----------------------");
logger.info("---------- in connect post request ----------------------");
logger.info("---------- in connect post request ----------------------");
ConnectRequest requestObj = new ConnectRequest();
try {
if (connectString != null && connectString.startsWith("<")) {
requestObj = marshallConnectRequest(connectString);
} else {
requestObj = convertKeyValueToObject(connectString);
}
logger.info("Request is " + requestObj);
} catch (JAXBException e) {
logger.error("----------------- Error in UnMarshalling ----------");
logger.error("----------------- Error in UnMarshalling ----------");
logger.error("----------------- Error in UnMarshalling ----------");
logger.error("----------------- Error in UnMarshalling ----------");
logger.error("----------------- Error in UnMarshalling ----------");
logger.error("----------------- Error in UnMarshalling ----------");
logger.error("----------------- Error in UnMarshalling ----------");
logger.error("----------------- Error in UnMarshalling ----------");
logger.error(e.getMessage(), e);
}
ConnectResponse connectResponse = new ConnectResponse();
connectResponse.setSession(requestObj.getSessionid());
connectResponse.setText("Hello");
logger.info("---------- returning response ----------------------");
logger.info("---------- returning response ----------------------");
logger.info("---------- returning response ----------------------");
logger.info("---------- returning response ----------------------");
logger.info("---------- returning response ----------------------");
logger.info("---------- returning response ----------------------");
logger.info("---------- returning response ----------------------");
logger.info("---------- returning response ----------------------");
return connectResponse;
}
public ConnectRequest marshallConnectRequest(String connectString) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(ConnectRequest.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (ConnectRequest) jaxbUnmarshaller.unmarshal(new StringReader(connectString));
}
public ConnectRequest convertKeyValueToObject(String connectString) {
return new ConnectRequest();
}
Instead of sending a simple response object I want to wait for the callback to hit at the following API.
@Path("/rest")
public class RESTWebservice {
/*
* @Context private MessageContext messageContext;
*/
final Logger logger = Logger.getLogger(RESTWebservice.class);
@POST
@Path("/sendResponse")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public ResponseJSON postQuestionnaire(RequestJSON requestJson) {
// performing operations
}
I have implemented a chat bubble that can render Images
, GIFs
, audios, and text
.
Currently, what I am doing is the following:
const Bubble = memo(
(props) => {
const { colors } = useTheme();
const { content, date, mine, onLongPress } = props;
const renderText = () => (/* JSX FOR TEXT */);
const renderGIF = () => (/* JSX FOR GIF */);
const renderAudio = () => (/* JSX FOR AUDIO */);
const renderImage = () => (/* JSX FOT IMAGE */);
return (
<...>
{content.type === VALID_CHAT_MESSAGES_TYPES[0]
? renderText()
: content.type === VALID_CHAT_MESSAGES_TYPES[1]
? renderAudio()
: content.type === VALID_CHAT_MESSAGES_TYPES[2]
? renderImage()
: renderGIF()}
</...>
)
});
I want to refactor this component but I am not sure about which pattern should I apply... Any ideas?
I have a problem with designing a proper solution for a factory for a family of common-based classes. I have a class called Verifier, the class will have only method Verify which accepts instance of Specification as a parameter
public abstract class Verifier
{
public virtual bool Verify(Specification spec)
{
//does the common job
return true; //or false
}
}
Then I have a set of concrete Verifiers
public abstract class FirstVerifier : Verifier
{
public override bool Verify(Specification spec)
{
//does the job, maybe even calls for base or maybe not
return true;
}
}
public abstract class SecondVerifier : Verifier
{
public override bool Verify(Specification spec)
{
//does the job, maybe even calls for base or maybe not
return true;
}
}
Then I have a nice factory which returns me a proper instance:
public class VerifierFactory
{
public static Verifier Create(string type) //not actually a string, but does not matter
{
switch (type)
{
case "First": return new FirstVerifier();
case "Second": return new SecondVerifier();
default: throw new Exception();
}
}
}
Now I have a requirement that the Verifiers can Verify not the instances of Specification but derived types of Specification, like:
public abstract class FirstVerifier : Verifier
{
public override bool Verify(SpecificationOne spec) //SpecificationOne derives from Specification
{
//does the job, maybe even calls for base or maybe not
return true;
}
}
public abstract class SecondVerifier : Verifier
{
public override bool Verify(SpecificationTwo spec) //SpecificationOne derives from Specification
{
//does the job, maybe even calls for base or maybe not
return true;
}
}
This obviously will not compile, and I don't want to do tricks like this:
public abstract class FirstVerifier : Verifier
{
public override bool Verify(Specification spec)
{
var realSpecification = spec as SpecificationOne;
if(realSpecification == null)
throw new Exception();
// do job
}
}
I am thinking of a solution (maybe a generic one) in which my factory returns proper type which in turn accepts proper type in Verify method, so that then I can use my factory to create verifiers and call verify, like this:
specifications.Select(s => VerifierFactory.Create(typeof(s)).Verify(s))
I'm trying to implement DDD in my project and I'm using Firestore as my persistence infrastructure. Firestore in Go has some specific types like *firestore.DocumentRef
.
I think that I should put it in my entity struct as it should represent my model, but my entity should also be db agnostic (I think).
So how should I handle from a DDD perspective this entity/struct:
type Holder struct {
SocialReason string `firestore:"social_reason" json:"social_reason"`
Contact value.Contact `firestore:"contact" json:"contact"`
Location value.Location `firestore:"location" json:"location"`
SubmissionDatetime time.Time `firestore:"submission_datetime" json:"-"`
UpdateDatetime time.Time `firestore:"update_datetime" json:"-"`
Status string `firestore:"status" json:"status"`
LastModifier *firestore.DocumentRef `firestore:"last_modifier" json:"-"`
CEP string `firestore:"cep,omitempty" json:"cep,omitempty"`
Country string `firestore:"country" json:"country"`
Region string `firestore:"region,omitempty" json:"region,omitempty"`
City string `firestore:"city,omitempty" json:"city,omitempty"`
}
TblBook.cs
public class TBLBook : IEntity
{
[Key]
public int BookId { get; set; }
public string BookName { get; set; }
[ForeignKey("TblCategory")]
public int CategoryId { get; set; }
public int WriterId { get; set; }
public string BookYearofPublication { get; set; }//Basım Yılı
public string BookPublishingHouse { get; set; } //Yayın evi
public string BookPage { get; set; }
public bool BookStatus { get; set; }
public TBLCategory TblCategory { get; set; }
}
TblCategory.cs
public class TBLCategory : IEntity
{
[Key]
public int CategoryId { get; set; }
public string CategoryName { get; set; }
public virtual ICollection<TBLBook> TblBooks { get; set; }
}
I did this because it is corporate architecture.
public class EfEntityRepositoryBase<TEntity, TContext> : IEntityRepository<TEntity>
where TEntity : class, IEntity, new()
where TContext : DbContext, new()
{
////return _context.Categories.Include(i => i.SubCategories).ToList();
public List<TEntity> GetList(Expression<Func<TEntity, bool>> filter=null)
{
using (TContext context = new TContext())
{
return filter == null ? context.Set<TEntity>().ToList() : context.Set<TEntity>().Where(filter).ToList();
}
}
}
Business:
public List<TBLBook> GetList()
{
return _bookDal.GetList();
}
Controller View
public IActionResult Index()
{
var query = new BookListViewModel
{
TblBooks = _bookService.GetList()
};
return View(query);
}
Index View:
<tr>
<td>@b.BookId</td>
<td>@b.BookName</td>
<td>@b.WriterId</td>
<td>@b.CategoryId</td> <!--Problem: @b.TblCategory.CategoryName-->
<td>@b.BookYearofPublication</td>
<td>@b.BookPublishingHouse</td>
<td>@b.BookPage</td>
<td>@b.BookStatus</td>
</tr>
My problem is; when i do this @b.TblCategories.CategoryName
throws null or error.
I cannot show the corresponding category name. how can I fill it, thanks. My English is bad, sorry. I tried to explain with pictures.
In short, here's what I want to do: The category ID appears. I want it to appear as the Category Name. but it looks blank, what should I fill with.
Output Photo: https://i.hizliresim.com/uNmld2.png
Well, i have next code:
#include <type_traits>
#include <iostream>
#include <string>
#include <list>
#include <functional>
class base_main
{
public:
virtual ~base_main()
{
}
// some methods
};
class base_1 : virtual public base_main
{
// some methods
};
class base_2 : virtual public base_main
{
// some methods
};
class base_3 : virtual public base_main
{
// some methods
};
class object : public base_1, public base_2, public base_3
{
// some methods
};
// in other *hpp file
class object_controller_listener
{
public:
virtual void object_created( base_main* o )
{
// well, i want to work only with base_1 and base_2 interfaces, but not with base_3, and also i don't want to know something about object class in this *hpp
// is it good code design?
auto* xxx = dynamic_cast<base_1*>( o );
}
};
class objects_controller
{
void create()
{
std::unique_ptr<object> obj;
// ...
for( auto listener : m_listeners )
listener->object_created( obj.get() );
}
std::list<object_controller_listener*> m_listeners;
};
int main()
{
}
The question is - how can i work only with base_1 and base_2 interfaces? Should i create two separate listeners for them, and send two events in create() function, or should i use dynamic_cast for downcasting and send only one event in create() function? Is this good code design or is this feels like code smell?
UPD:
For example: base_1 - is render_base class, which contains render data, and have functions for set and get this data base_2 - collider base class which contains collider data, and have functions for set and get this data base_3 is physic base class and object is inheritance of all this classes. And when i want work only with render class i use create event which send only render_base class to the render_system, which works only with renders objects and truly use polymorphism. But if i want in some other place work with collider and physic objects, without knowledge about render - how can i use polymorphism here in base classes?
I'm trying to create a model with observer design pattern. I'm wondering that my subject can have only one observer. I usually see one subject and many observers in examples.
I am using NestJS to build an API. I have a Gateway service to a 3rd-party API that decouples the HTTP calls from the data processing logic. Since I don't want to make requests to the API during development, I use a factory function that returns a Gateway class depending on the environment—TinkMockGateway or TinkGateway.
In the factory function I return the class instead of instances and it works. This is surprising because my implementation differs from the Angular / NestJS documentation. In both documentations [1, 2], they say that you must return an instance of the class you want to inject—which makes sense if we follow the Factory Pattern.
But, when I use the factory function below (NestJS), the dependency is injected correctly (the gateway) depending on the environment.
// other module providers...
{
provide: TinkGateway,
useFactory: () => environment.mockTinkGateway ? TinkMockGateway : TinkGateway,
}
Is the framework creating the instances for me or what is going on?
This is my first question.
I need some idea of what is the best application or design to apply to my small problem.
I have a data structure (see Figure 1) that I implemented as a Node. Each Node has an associate type (TypeNode) and some relationships (child attribute).
In some point of my program, I need to filter the information of the data structure. For example, keep only the Nodes of Type Material and Color. Thus, I need to receive a list of Node of type Material and Color.
The questions are:
Any Design Pattern that can solve this problem?. I was thinking the Criteria Design Pattern, but I am not sure if it will be the best solution.
Any other possible approach or application that can help?. For example, any (NoSQL) datasabe that stores the information of my data structure and then we can perform some "query" to keep only the Nodes of Type Material and Color.
I am open to any idea!
Thank you in advance.
CG
I want to find the smallest sequence of numbers that are repeated in a given array.
Example: 1, 2, -2, 1, 2, -2, 1, 2, should output 3 because "1, 2, -2" is repeated
Example: 1, 2, 1, should output 2 because "1, 2" is repeated
I try to learn design patterns. At this moment I got decorator. Product interface <?php declare(strict_types=1);
interface Product
{
public function getPrice();
public function getDescription();
}
BaseProduct
<?php declare(strict_types=1);
class BaseProduct implements Product
{
public function getPrice()
{
return 20;
}
public function getDescription()
{
return "This is base product";
}
}
SportProductDecorator
<?php declare(strict_types=1);
class SportProductDecorator implements Product
{
private Product $product;
public function __construct(Product $product)
{
$this->product = $product;
}
public function getPrice()
{
return $this->product->getPrice() + 20;
}
public function getDescription()
{
return "THis is product from Sport category";
}
}
HomeProductDecorator
<?php declare(strict_types=1);
class HomeProductDecorator implements Product
{
private Product $product;
public function __construct(Product $product)
{
$this->product = $product;
}
public function getPrice()
{
return $this->product->getPrice() + 50;
}
public function getDescription()
{
return "This is product from Home category";
}
}
Did I apply the decorator well here? Design patterns are taught, but it's tough. I have seen a lot of people do it in different ways.
Help me please. I am new .net core mvc and here. I am developing a very simple blog site. But I'm getting an error. Post class
using System.Collections.Generic;
namespace DataAccess
{
public class Post
{
public int PostId { get; set; }
public string PostTitle { get; set; }
public string PostWriter { get; set; }
public string PostDate { get; set; }
public string PostİmageUrl { get; set; }
public string PostContent { get; set; }
public List<Post> Posts { get; set; }
}
}
using System.Collections.Generic;
using System.Linq;
using DataAccess.Abstract;
using Microsoft.EntityFrameworkCore;
using static DataAccess.Entity;
namespace DataAccess.Concrete.SqLite
{
public class PostRepository : IPostRepository
{
private Context db = new Context ();
public List<Post> GetAll()
{
return db.Posts.ToList();
}
public Post GetById(int id)
{
return db.Posts.Find(id);
}
}
}
Home Controller
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Blog.Models;
using DataAccess.Abstract;
using DataAccess;
namespace Blog.Controllers
{
public class HomeController : Controller
{
private IPostRepository _postRepository;
private ICommentRepository _commentRepository;
private ICategoryRepository _categoryRepository;
public HomeController(IPostRepository postRepository, ICommentRepository commentRepository, ICategoryRepository categoryRepository)
{
this._postRepository = postRepository;
this._commentRepository = commentRepository;
this._categoryRepository = categoryRepository;
}
public IActionResult Index()
{
var Post = new Post ()
{
Posts = _postRepository.GetAll()
};
return View(Post);
// return View(new PostViewModel()
// {
// Posts = _postRepository.GetAll()
// });
}
public IActionResult Privacy()
{
return View();
}
}
}
My View
@model Post
@{
var P = Model.Posts;
}
<!-- Post Content Column -->
<div class="col-lg-8">
<!-- Title -->
@foreach (var item in P)
{
<h1 class="mt-4">@item.PostTitle</h1>
}
</div>
This is my code. [My database][1] [My error][2] [1]: https://ift.tt/2Ya1AUu [2]: https://ift.tt/3oogGk8 how do you think i can solve the problem?
I have been developing a C++ software driver for the adc peripheral of the MCU.
The individual analog inputs connected to the adc can be configured for operation in the unipolar or bipolar mode. To reflect this fact in my design I have decided to model the analog inputs by the AnalogInput
abstract class and then define two derived classes. UnipolarAnalogInput
for the unipolar analog inputs and BipolarAnalogInput
for the bipolar analog inputs. These two classes differ only in the implementation of the getValue()
method.
enum class Type
{
Unipolar,
Bipolar
};
class AnalogInput
{
public:
virtual float getValue() = 0;
};
class UnipolarAnalogInput : public AnalogInput
{
public:
UnipolarAnalogInput(uint8_t _id, bool _enabled, Type _type);
bool isEnabled();
bool isReady();
float getValue();
private:
uint8_t id;
Type type;
bool enabled;
bool ready;
uint16_t raw_value;
};
class BipolarAnalogInput : public AnalogInput
{
public:
BipolarAnalogInput(uint8_t _id, bool _enabled, Type _type);
bool isEnabled();
bool isReady();
float getValue();
private:
uint8_t id;
Type type;
bool enabled;
bool ready;
uint16_t raw_value;
};
My goal is to fullfill following requirements:
Here are my ideas
As far as the requirement 1.
The ideal state would be to have AnalogInput analog_inputs[NO_ANALOG_INPUTS]
. As far as I understand correctly this is not possible in C++. Instead of that I need to define AnalogInput *analog_inputs[NO_ANALOG_INPUTS]
.
As far as the requirement 2.
It seems to me that the best solution for the other systems than the embedded systems would be to use the factory method design pattern i.e. inside the AnalogInput
define
static AnalogInput* getInstance(Type type) {
if(type == Unipolar) {
// create instance of the UnipolarAnalogInput
} else if(type == Bipolar) {
// create instance of the BipolarAnalogInput
}
}
Here I would probably need to define somewhere auxiliary arrays for the UnipolarAnalogInput
instances and the BipolarAnalogInput instances where the instances would be allocated by the factory method and the pointers to those arrays would be returned by the getInstance()
. This solution seems to me to be pretty cumbersome due to the auxiliary arrays presence.
As far as the requirement 3.
for(uint8_t input = 0; input < NO_ANALOG_INPUTS; input++) {
analog_inputs[input] = AnalogInput::getInstance(AdcConfig->getInputType(input));
}
As far as the requirement 4.
Here I would say that what I have suggested above is applicable also for the embedded systems because the solution avoids usage of the standard new
operator. Question mark is the virtual method getValue()
.
My questions:
my problem is refactoring a program according to object-oriented programming principles. Program is running in a while loop endlessly and all operations in this main while loop. This main cycle has a switch-case statement. It has 11 cases and all cases are represent statements like unplanned_stop
, planned_stop
, read_data_from_x
, read_data_from_y
... Also, these states have if-else clauses in it to call different functions. Every state points to another state to the next step according to if-else decisions.
I have searched and State Design Pattern is seemed good for this solution but I am not sure. The main loop is like this:
while(programIsRunnning)
{
switch(programState)
{
case state.StartOfLoop:
if(..) doSomething();
else doAnotherThing();
programState = state.PlannedStop;
break;
case state.PlannedStop:
if(..) programState = state.ReadDataFromX;
else programState = state.ReadDataFromY;
case state.ReadDataFromX:
if(..) programState = state.UnplannedStop;
else programState = state.StartOfLoop;
.
.
.
I hope I could explain enough. This design is nasty and hard to understand to where to implement new specifications. For every new request for the program, I have to edit other states and if-else clauses. I am a junior and all can I think is recoding it with OOP design patterns. Any suggestions are welcome.
I have the following classes.
public class Container
{
private ResourceA a;
private ResourceB b;
private List<User> users;
public void handleUser(User u)
{
if (u is UserA ua)//cast into userA
{
ua.useResourceA(a);
}else if (u is UserB ub)
{
ub.useResourceB(b);
}
}
}
public class User
{
}
public class UserA: User
{
public void useResourceA(ResourceA a)
{
//do something with a
}
}
public class UserB: User
{
public void useResourceB(ResourceB b)
{
//do something with b
}
}
ResourceA and B behave very differently. It's not possible to have a base class for the two of them. Yet UserA and UserB share some functionality and I need a list containing resource users for various reasons. I then also need to handle resource grant requests from the base class. So I have to cast them. Which is bad.
I thought about the following approach which solves the casting issue but couples the classes even further:
public class Container
{
public ResourceA a;
public ResourceB b;
private List<User> users;
public void handleUser(User u)
{
u.useResource(this);
}
}
public abstract class User
{
public abstract void useResource(Container c);
}
public class UserA: User
{
public override void useResource(Container c)
{
useResourceA(c.a);
}
void useResourceA(ResourceA a)
{
//do something with b
}
}
public class UserB: User
{
public override void useResource(Container c)
{
useResourceB(c.b);
}
public void useResourceB(ResourceB b)
{
//do something with b
}
}
Is this a well know anti pattern? Is there a better way to do this?
Problem 1: suppose you have an array of n floats and you want to calculate an array of n running averages over three elements. The middle part would be straightforward:
for (int i=0; i<n; i++)
b[i] = (a[i-1] + a[i] + a[i+1])/3.
But you need to have separate code to handle the cases i==0
and i==(n-1)
. This is often done with extra code before the loop, extra code after the loop, and adjusting the loop range, e.g.
b[0] = (a[0] + a[1])/2.
for (int i=1; i<n-1; i++)
b[i] = (a[i-1] + a[i] + a[i+1])/3.;
b[n-1] = (a[n-1] + a[n-2])/2.
Even that is not enough, because the cases of n<3 need to be handled separately.
Problem 2. You are reading a variable-length code from an array (say implementing a UTF-8 to UTF-32 converter). The code reads a byte, and accordingly may read one or more bytes to determine the output. However, before each such step, it also needs to check if the end of the input array has been reached, and if so, perhaps load more data into a buffer, or terminate with an error.
Both of these problems are cases of loops where the interior of the loop can be expressed neatly, but the edges need special handling. I find these sort of problems the most prone to error and to messy programming. So here's my question: Are there any C++ idioms which generalize wrapping such loop patterns in a clean way?
I am faced with a C# design problem that C#'s limitations are making hard to achieve. I need some sort of design pattern/strategy to rescue me.
I must create the archetypical set of abstract shape classes: Base class Shape
with derived classes LineShape
, RectShape
, etc. Specific implementations will derive from these. The problem is that I really need to use classes here, not interfaces and this is forcing me to duplicate a lot of code.
To illustrate:
public abstract class Shape
{
public abstract int Id { get; } // Unique ID
public abstract string Name { get; set; } // Shape name. Defaults to the type of shape
public abstract bool IsLocked { get; set; } // May the user change this shape in any way?
}
public abstract class LineShape : Shape
{
public abstract Point P1 { get; set; }
public abstract Point P2 { get; set; }
}
public abstract class CircleShape : Shape
{
public abstract Point Center { get; set; }
public abstract double Radius { get; set; }
}
When I start creating the derived implementations (LineImpl
, CircleImpl
, etc), I find that the implementations of the Shape
functions are identical for all the Impl classes, yet specific enough that I cannot implement them in the abstract Shape
class itself.
So I need to find a way to share a common implementation of these function in my derived hierarchy.
In other words LineImpl
must derive from LineShape
. CircleImpl
must derive from CircleShape
, etc. I cannot find a way to insert a ShapeImpl
in there to handle the boiler plate stuff. So I am forced to implement all those Shape
functions over and over again, once in each Impl shape type.
I tried using generics to get my way out of this but unfortunately a generic class cannot specify its base class with a generic argument. In other words, the following approach (which I might do in C++) does not work in C#
public class ShapeImpl<TBase> : T where T : Shape { ... boiler plate implemented here)...}
public class LineImpl : ShapeImpl<LineShape> { }
public class CircleImpl : ShapeImpl<CircleShape> { }
So I am at a loss. Is there some C# trick or design pattern that can get me out of this? Or am I forced to implement the same functions multiple times?
I was studying design patterns and while I was studying Facade Design Pattern, I saw an explanation in the book as:
A Facade Pattern says that just "just provide a unified and simplified interface to a set of interfaces in a subsystem, therefore it hides the complexities of the subsystem from the client".
Yet when I analyze the implementation of Facade Design Pattern, what I see is that every method that is used inside of the class that is used for Facade Pattern is used as concrete classes.
What do we mean by set of interface in the explanation? Do we mean that we could use some interfaces for the concrete classes or is it something like we use with adapter which is the logic that we try to adapt different interfaces to use simplified versions of them?
Like below simple react component code:
class Test extends React.Component {
constructor(props){
super(props)
this.c1 = this.c1.bind(this);
this.c2 = this.c2.bind(this);
this.state = {
a:false,
b:false
}
}
c1(e) {
this.setState({a:true, b:false})
}
c2(e) {
this.setState({a:false, b:true})
}
render() {
return (
<div>
<div>
<input name="n" type="radio" onChange={this.c1} />
<input name="n" type="radio" onChange={this.c2} />
</div>
<div>
{
this.state.a && "aa"
}
{
this.state.b && "bb"
}
</div>
</div>
)
}
}
The code simply switch displaying 'aa' or 'bb' while click the radio button. But if I add a new radio button showing 'cc' to achieve the same function. I should:
All of those is ok, But I have to change the 'c1','c2' function that make my code coupling like:
class Test extends React.Component {
constructor(props){
super(props)
this.c1 = this.c1.bind(this);
this.c2 = this.c2.bind(this);
this.c3 = this.c3.bind(this);
this.state = {
a:false,
b:false,
c:false,
}
}
c1(e) {
this.setState({a:true, b:false, c:false}) // add 'c:false' which coupled
}
c2(e) {
this.setState({a:false, b:true, c:false}) // add 'c:false' which coupled
}
c3(e) {
this.setState({a:false, b:false, c:true})
}
render() {
return (
<div>
<div>
<input name="n" type="radio" onChange={this.c1} />
<input name="n" type="radio" onChange={this.c2} />
<input name="n" type="radio" onChange={this.c3} />
</div>
<div>
{
this.state.a && "aa"
}
{
this.state.b && "bb"
}
{
this.state.c && "cc"
}
</div>
</div>
)
}
}
I think this situation is very common in React. So I want decoupling my code no matter how many radio buttons I add. I do not need to change the code just add code to satisfy the 'Open Closed Principle'.
Do you have any recommendation? Thanks in advance.