When should I authorize in controller constructor using authorizeResource like here and when should I use Authorizing Form Requests like here?
samedi 30 novembre 2019
What does this statement about MVC mean?
http://geekswithblogs.net/dlussier/archive/2009/11/21/136454.aspx says
MVC – Model View Controller
Let’s look at MVC first. You’ll notice a few things about the diagram:
The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality.
There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed.
Note the one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller.
The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.
What does the last sentence mean? Specifically, what do the three clauses mean:
-
"The Controller does pass back the Model"
-
"there is knowledge between the View and the expected Model being passed into it"
-
"not the Controller serving it up"?
There is an arrow from model to view, which means that whenever model's state changes, view will automatically update itself. This is not done via controller. So why do we need an arrow (one-to-many relationship) from controller to view?
Thanks.
What is DAO and DTO in Java? When should it be used and what are the advantages of using it?
Please explain with examples. To give more context, I have worked in Ruby on Rails and using Java for the first time. So any analogy related to Rails will be a huge help.
Is there a pythonic way of referring to the iterators variable names inside of the for loop?
Below is a code snippet:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
...
val = carry
for l in filter(None, [l1, l2]):
val += l.val
l = l.next
l1 and l2 are two linked lists. If a list is empty it is set to None such that the loop only processes a linked list if it has not been completely traversed. I want to use the loop to prevent code duplication. The issue is on line four, where upon an iteration of the loop neither l1 or l2 are updated with the next node of the list but l is instead. Does anyone know of any nice patterns to fix this issue? Apologies if this question has been asked before but I do not know of the correct terminologies to search for an answer. Perhaps defining a separate function or an anonymous function would be the best way to go?
Should DTOs have the same hierarchy of the original entity?
I am developing a restful APIs and we have animal kingdom entities where Animal is an abstract class and we have 2 sub-classes Dog and Cat.
Should the DTO has the same hierarchy as the original entities ? In other words, should I have AnimalDTO class, CatDTO class and DogDTO class ( where both Cat and Dogs inherits from animal )? Or I should have only Cat and dog DTOs that have all animal variables ?
What is the use of a Manager class?
I can't understand what is the use of the so called Manager classes(Game manager/security manager/round manager in a game ..etc)
some say that it basically manages interactions between multiple objects others say it is a bad practice and should be avoided
let's say i have a game with multiple rounds what would be the use of the (round manager / game manager / player manager etc..) in this case?
and if it is considered to be a symbol of bad design then what would be the perfect design if you want to make multiple different classes interact with each other?
Software Architecture - JPA Switch To Temporary Tables Dynamically?
Let's assume the following: We have N related tables in which data is coming every few seconds or so and the data is monitored by users. The goal is at time T1 to stop persisting into the N tables but rather somewhere else and later at time T2 to start persisting into the N tables again and migrate the data persisted between T1 and T2 into the N tables.
One good solution to this is by using caching for the period T1 - T2 but in this case the data is somewhat big so this is not going to solve it.
Another solution is (if it's possible) to create temporary tables at T1 and point all of the entities into the newly created tables. Then migrate the data at T2, point back the entities into the original tables and drop the temporary tables.
I know this is a bit off topic and I would like a recommendation for where I can learn more and ask architectural questions?
vendredi 29 novembre 2019
Design pattern suggestion to perform pipeline operation
Problem statement: I have to process request similar to a pipeline.
For example:
When a request comes, it has to undergo a sequence of operations, like (step1,step2,step3...).
So, in order to achieve that, I am using Template design pattern.
Please review and suggest if I am implementing this problem correctly, or there is a better solution.
I am suspecting my approach will introduce code smells, as I am changing values of objects very frequently.
Also, suggest if I & how can I use Java 8 to accomplish this?
Thanks.
Code:
package com.example.demo.design;
import java.util.List;
public abstract class Template {
@Autowired
private Step1 step1;
@Autowired
private Step2 step2;
@Autowired
private Save save;
List<String> stepOutput = null;
List<String> stepOutputTwo = null;
List<String> stepOutputThree = null;
public void step1(String action1) {
stepOutput = step1.method(action1);
}
public void step2(String action2) {
stepOutputTwo = step2.method(stepOutput, action2);
}
abstract public void step3();
public void save() {
save.persist(stepOutputThree);
}
final public void run(String action1, String action2) {
step1(action1);
step2(action2);
stepOutputTwo = step3();
}
}
How can I replace a block of code in a php file using preg_replace and regex expression?
I have a php config file that contains a few arrays use to store settings.
<?php
$array1 = array(
"item1' => "value1",
"item2' => "value2",
"item3' => "value3",
"item4' => "value4",
);
$array2 = array(
"item1"
"item2"
"item3"
"item4"
);
$array3 = array(
"item1' => "value1",
"item2' => "value2",
"item3' => "value3",
"item4' => "value4",
);
?>
I am not very good with regex expression (yet).I am having diffulties understanding how it works. I am trying to build a regex expression that would allow me to replace all lines in array2. Using preg_replace($pattern, $replacement, $str)
.
$str=file_get_contents('config.php');
$pattern = 'some regex';
$replacement = ' "itemA",
"itemB",
"itemC",
"itemD",';
$str=preg_replace($pattern, $replacement, $str);
file_put_contents('config.php', $str);
Is there a Design Pattern that solve this problem?
2 (+1) Requirements
1.- The user must be able to add many types of Equipment
2.- When the type of equipment is "SOME VALUE" then ...
N.- ... future requirement ... now when the type of equipment is "SOME OTHER VALUE" then ...
The situation is that in one side, I know that the "Types" could change, but also I know that some values must exist particular values of "Type" in order to perform particular behaviors.
private int SomeAction(Equipment e)
{
if (e.Type == "SOME VALUE")
{
// Do something for that special case
}
else if (e.Type == "SOME OTHER VALUE")
{
// Do something for that other special case
}
else
{
// Do the other thing
}
}
Gracefully pattern for the useful class like a "Schemes by inheritance"
Imagine, we have a some files:
scheme.py
scheme.One.py
scheme.Two.py
sceme.*.py
...
In file scheme we have the common class code with all class attributes we need.
class Scheme:
_VAR = "Variable"
def function_common(self):
pass
def function_first(self):
return "Main_Scheme"
def function_second(self):
return "Common_Scheme"
In other files we have the ONLY PARTICULAR attributes, which we want to replace in common class.
File 'scheme.One.py':
class Scheme:
_VAR = "Scheme1"
def function_first(self):
return "Scheme_One"
File 'scheme.Two.py':
class Scheme:
_VAR = "Scheme2"
def function_second(self):
return "Second_Scheme"
We need to determine the close scheme by some parameters (not in question) and get the appropriate class Scheme.
What is the best practice for this case, if we need to get like a "Factory of classes" in file 'scheme.py'?
I'm not PRO in Python.
Please, thorough answer...
Any Python version (>=3.74), appreciate for modern solutions...
Thanks very much!!!
Changing method behaviour depending on subtype of 2 input parameters
I am trying to create a card game with a clean class design. I would like to compare 2 cards and return the one with the highest "value".
I have an abstract card class and 2 classes inherited from it :
public abstract class Card {...}
public class ColoredCard extends Card {...}
public class TrumpCard extends Card {...}
I would like to use a compare method, which would have different implemented logic depending on subtypes of the card, like that (I put those method within an external "Comparator" class :
public Card compare(ColoredCard card, TrumpCard card2) { //implementation for 1st subtype combination
public Card compare(ColoredCard card, ColoredCard card2) { //implementation for 2nd subtype combination
//other type combinations
But it throws a compilation error whenever I call it from my Cards classes :
//within any my card subclass
public Card compareTo(Card c) {
return Comparator.compare(this, c); //compilation error because it cant determine "c" variable subtype
What design would you recommend for that purpose ? Is there a convenient solution to that problem ?
I would like to avoid to use instanceOf
instruction or reflection if possible.
Thank you,
Architecture design for event driven programming
Here is my problem statement and I'm stuck during architect design.
I have a project where admin can create a request, the request will go to all the engineers who are registered on our app. They will have 10 mins to opt in for the request, once 10 mins are elapsed, admin will receive one notification stating, "request round is completed, plz see the responses of engineer". Now admin can see a list of engineers who opted-in for the request. If admin selects one engineer, that engineer will be sent one notification saying "You have been selected, plz acknowledge". Engineer will have 5 mins to acknowledge and our admin will wait for his acknowledgement. If he doesn't acknowledge, admin will receive one another notificaiton stating engineer didn't acknowledge, select another. So admin will now select another engineer and same procedure will go. He will again have 5 mins to acknowledge. Once he acknowledges, process will be finished. So here once we create a flow chart, we see many events changes the status of one request. So I would like to have suggestions on what would be the approaches to design the architecture of such application? Apacke kafka, streams, rabbitmq, drools will fit anywhere in the applications?
I have thought of having 2 different spring boot projects, one for our core engine which will process the request and other is notification engine. From core engine, we will send the notification to notification engine via http/rabbitmq.
And for managing the threading of requests, I'm thinking of using executor service.
Please help with the suggestions to design a better architecture of the application.
My backend is java spring
Extracting numbers from a list based on the pattern using R
I am new in R, and i have small task but in same time is complected :(
Simply i have to create a list of number starting from (0000001) to (9999999) so, its seven digits number.
Then i have to extract any numbers that have the following digits pattern, and group them in different list as following:
-
Group A: (7 unique), where the number contains at least 7 unique numbers. (eg. 3896214)
-
Group C: ( 5 unique), where the number contains only with 5 unique numbers. (eg. 3816211)
-
Group C-1: ( 3 solid ) where the number contains at least 5 unique numbers but having triple solid digits e.g. 3816222. Note: this can take different form for example; (????xxx,??xxx??, ?xxx???, xxx????). Each form should be classified into separate list
I tried to use the grep codes but its not the appropriate way as this takes a lots of time and write a grep for each numbers out from 0-9 and so on.
please advice and suggest
Thank you,
jeudi 28 novembre 2019
Why ViewModel's object shouldn't manipulate database directly?
I am learning Android Architecture Components.
For exemple, and be more easier to understand, If i want to build a TO DO LIST app, my item creation DAO should be
@Dao
public interface ItemDao {
@Insert
long insertItem(Item item);
and my viewModel could be use this DAO to insert an item in my TODO list. But, in architecture component, it is recommanded to NOT manipulate the database by the viewmodel but by the repository.
So, the code should be like that
public class ItemDataRepository {
private final ItemDao itemDao;
public ItemDataRepository(ItemDao itemDao) { this.itemDao = itemDao; }
// --- CREATE ---
public void createItem(Item item){ itemDao.insertItem(item); }
It seems redundant when we cannot understand why.
My question is : why?
Websockets: Data Design Patterns
I'm looking for some help with best practices and standards for my first Websockets chat app. I don't have any reference for this– so this is what I have currently implemented. There are many types of Messages that can be sent in this service:
• Text Messages
• Video Messages
• Image Messages
... etc
So imagine chatrooms that multiple people can be in. Here is how I am thinking about sending messages from the client to server:
{
"type": "room.message",
"data": {
"meta": {
"color": "#FFFFFF"
},
"message": "Hello, how are you?"
}
}
This is the design for the message being sent down from the server to the clients connected to the room.
{
"type": "room.message_broadcast",
"data": {
"meta": {
"color": "#FFFFFF"
},
"message": "Hello, how are you?",
"user": userObject
}
}
From a best practices standpoint, does it make sense to follow this type
and type_broadcast
format? Following on from that, does it make sense how I'm structuring the interior data structure regarding type
and data
? Following this same pattern, we would do this for images:
{
"type": "room.image",
"data": {
"url": "https://www.google.com/someimage.png"
}
}
{
"type": "room.image_broadcast",
"data": {
"url": "https://www.google.com/someimage.png"
"user": userObject
}
}
From a design perspective, does this pattern make sense for a realtime chat room with multiple types?
What is the best way to storage data in flutter
For example, I have a class with a static field that can store my data, but I'm not sure if this is correct for OOP principles. What is the best way to do this?
class Data {
static String token;
static DoctorProfile doctor;
static UserProfile userProfile;
}
Should I have different APIs methods for different concrete classes?
I am writing an APIs for greeting cards.
A card contains just List of lines and Card ID. The card has method called Greeting.
A line is just set of characters.
I have an interface Card and several concrete classes that implements this interface, i. e, ChristmasCard, EasterCard... etc.
I am writing an API method that returns the card by ID.
From design perspective, is it better to write single API method that returns any type of card based on the ID, or, its better to write an API for every card type ?
Is this a legit strategy design pattern usage?
I've this problem : I have to implement a list in Java and I have to make sure to guarantee the insert operations working in 2 way : when the user want the list ordered by a first parameter, I have to insert every new element to the head of the list, while when the user want the list ordered by the second parameter I have to search the correct position where to insert my new element. Since the insert operation changes its behavior according to the sorting cryterion of the list, I thought it was the case to implement the insert operation using the design pattern strategy, the Strategy interface just have the add() method and the concrete classes that implements this strategy implement differently the insertion. Is this acceptable as use of dp strategy or there's some flaws in my design process? Thanks!
Best technology to use to create a web based virtual designer
I have seen some sites where the users have the ability to snap a photo, select a tile floor from a gallery and it renders it to the user's photo.
Something similar to what this site offers https://www.roomvo.com/
I want to ask what web technologies can be used to build something similar to this feature. Is there an API/Plugin that is made for this?
Can dependency injection be implemented to windows library projects?
Can dependency injection be implemented to windows library projects? Or this design pattern is not practiced in libraries?
Python static immutable properties
What's the correct way to implement static immutable properties in Python?
Minimal example:
A program module 'Family' has a class Parent
, defined below:
class Parent():
def __init__(self, type):
self.type = type
The parent can be of either of the two string types: 'mother'
or 'father'
. An external user of this class should be able to set the type when constructing, and later query parent.type
to get either of these two values. Furthermore, other parts of the Family module utilise the Parent
class and rely on either of these two values being returned. Therefore, the requirements of the type are as follows:
- be available both externally to users and internally to the Family module
- be always either 'mother' or 'father', therefore be based on immutable variables
A naive approach could encourage setting type by passing a string:
parent = Parent('mother')
But this allows for accidental misspellings (eg. Parent('omther')
). To prevent this, I utilise the following approach:
class Parent():
TYPE_MOTHER = 'mother'
TYPE_FATHER = 'father'
TYPES = [TYPE_MOTHER, TYPE_FATHER]
def __init__(self, type):
assert type in self.TYPES, ('Invalid type "%s"' % type)
self.type = type
parent = Parent(Parent.TYPE_MOTHER)
However, nothing would stop the user from changing these static variables as they like, eg:
parent = Parent('mother')
Parent.TYPE_MOTHER = 'burrito'
print(parent.type == Parent.TYPE_MOTHER)
#> False
To solve this, I considered using @staticmethod
and @property
annotations:
class Parent():
@property
@staticmethod
def TYPE_MOTHER():
return 'mother'
@property
@staticmethod
def TYPE_FATHER():
return 'father'
This wouldn't prevent the user from passing a string to constructor (eg. Parent('mother')
) but at least it would prevent them from screwing up the Family module by changing what the parent types can be.
Problems I have with this method:
- It's ugly, 4 lines of code instead of 1
- It feels hacky (possibly due to my experience with language-supported private static variables in other languages)
- My IDE's linter don't like it due to no 'self' argument (even if it's provided)
Questions for you:
- Is this method Pythonic?
- Is there a nicer way to do it?
- Can you suggest a pattern that will achieve such immutability, whilst also enforcing user to use only the variables that I want them to use, preventing them from passing primitive string to the constructor?
Automating checkers and error handling with decorator design
I have a collection of functions which helps me asserting and testing requirements on my data_frame. For this group of functions, I want to add a common decorator error_handler
, which will allows me, to customize, my error handling and creates decorators
for my checkers
such that if, i have a checker function with name assert_no_na
my decorator would be named as assert_no_naD
, like,
# Decorators.py
def assert_no_naD(error='raise'):
def deco(fobj):
def fwrapper(*args, **kwargs):
try:
return_value = fobj(*args, **kwargs)
except (e):
if errors == 'raise':
raise(e)
return return_value # wrapper returns func_result
return fwrapper # deco returns wrapper
return deco
# Checkers.py
def assert_no_na(data):
# assert all entrines in data are not null
pass
# has_attr(), is_dtype(), all_unique(), ...
As it is obivous, if i repeat the same for all my functions in Checkers.py
, i am only duplicating major chunk of my code.
I would like to build something along the lines of,
# GenDecorators.py
import functools as ft
import Checkers as Chk
# Iterate over functions in checkers
for func in dir(Chk):
if func.startswith("__") and hasattr(func, '__call__'):
continue # pass inbuilt functions
# build the decorators...
Dchk = alldecorator(Chk)
# how do i populate Dchk in the `Decorators` namespace with different name.
@ft.wraps(Chkerfunction)
def alldecorators(Chkerfunction):
def err_handler(errors = 'raise'):
def ideco(usrfunc):
@ft.wraps(usrfunc)
def wrapper(*args, **kwargs):
res = None # any exception raise, will not assign this, so need a default.
try:
fresult = usrfunc(*args, **kwargs)
res = Chkerfunction(fresult)
except Exception as e:
if errors == 'raise':
raise e
return fresult, res
return wrapper
return ideco
return err_handler
This make my application look like,
@assert_no_naD(errors='raise')
def collect_inventory_sheet(*args, **kw):
assert_no_na(args)
# some collection + cal
return inventory
I am stuck with the following problems,
- Collecting functions from a module. (not sure about the solution in example code)
- How to populate the
newely created decorator
in themodules namespace
with different name. eg. Chkerfunction = 'assert_no_na' then Decorator = 'assert_no_naD'
Need sample implementation of SOA Design Patterns using WCF
I am currently studying SOA Design Patterns by Thomas Erl.
As I searched the internet I could not find any sample implementations of the design patterns discussed in this book.
I would like to know if there is any resource that contains SOA design patterns implementation samples preferably using WCF
technology?
Thanks in advance
Write a class in PHP Symfony 4.4 using the design pattern Factory Method to instantiate Service classes
Using Symfony 4.4 with autowiring activated, I want to instantiate a class using the design-pattern FactoryMethod.
The class instantiated is a service with autowired arguments passed into the constructor.
It work well if the constructor is the same for each type of class to instantiate inside the factory method.
But, each service to instantiate has to autowire some specific service in order to work.
I found that we could use the "setter dependency injection". Articles describing it:
- https://symfonycasts.com/screencast/symfony-fundamentals/logger-trait
- https://symfony.com/doc/4.4/service_container/injection_types.html#setter-injection
I tried to implement the setter dependency injection but the code inside is never executed.
Considering the articles, we should enter the setters with the PHPDoc "@required" immediately after the __construct method has been called (from what I understood).
It doesn't work with my code (see below).
Is my implementation correct?
Is there a better way of doing it?
My code looks like:
// Controller
/**
*@Route("/my_action/{param}")
*/
public function my_action (ThingManagerFactory $thingManagerFactory, $param)
{
$thingManager = $thingManagerFactory->get($param);
$thingManager->doSomething();
}
// ThingManagerFactory
class ThingManagerFactory
{
private $firstManager;
private $secondManager;
private $thirdManager;
public function __construct(FirstManager $firstManager, SecondManager $secondManager, ThirdManager $thirdManager)
{
$this->firstManager = $firstManager;
$this->secondManager = $secondManager;
$this->thirdManager = $thirdManager;
}
public function get($param): ThingManagerInterface
{
if($param == 1) {
return new Thing1Manager(
$this->firstManager,
$this->secondManager,
$this->thirdManager,
);
} elseif($param == 2) {
return new Thing2Manager(
$this->firstManager,
$this->secondManager,
$this->thirdManager,
);
}
throw new \InvalidArgumentException("...");
}
}
// ThingManagerInterface
interface ThingManagerInterface
{
public function __construct(
$this->firstManager,
$this->secondManager,
$this->thirdManager,
);
public function doSomething();
}
// Thing1Manager
class Thing1Manager implements ThingManagerInterface
{
(...)
private $spec1Manager;
public function __construct(
$this->firstManager,
$this->secondManager,
$this->thirdManager,
)
{
(...)
}
/**
* @required
*/
public function setSpecificManager(Spec1Manager $spec1Manager)
{
// this code is never called
$this->spec1Manager = $spec1Manager;
}
public function doSomething()
{
// we pass here before going into setSpecificManager
(...)
}
}
// Thing2Manager class
// is similar to Thing1Manager with multiple other specific managers.
Thank you for your help.
mercredi 27 novembre 2019
Clean Architecture - Propagate changes from deeply nested child views to parent
Given the view hierarchy in the image above, if a user taps on the "Cell" view - which is 4 "levels" deep [UIViewController -> UIView -> UICollectionView -> Cell] - how do changes made propagate to the top level i.e. UIViewController?
If I was using redux or similar it would be quite simple, I would fire off an action and it would be handled accordingly. In clean architecture, what are the best practices to avoid issues of handing down delegate methods through 4 layers of code?
Best design pattern for linking Api results together
Language to use: C#
I have a situation where I have around 4/5 api calls to make but they are all dependent on the previous API call being successful.
For example:
- CommandA
- CommandB(Uses Result of CommandA)
- CommandC(Uses Result of CommandB)
and so on and so forth - it really as simple as that. I have bneen recommended the builder pattern, Chain of responsibility and command pattern but don't know which one would be the easiest to build upon if i have to add any more commands later on down the line. Thanks.
How to allow just data from an array into an input field?
for explanation i need this information for a project to handle Datamatrixcode - till this moment just everytime a number.
Okay i have a table with some numbers (unique_codes) and i take this numbers via SELECT these from a table (MySQL) and put them to an array ($row).
Scenario: the worker scans a number (and this numbers MUST BE a number from this $row list - then i $_POST this $row to other site to take it for the next step) otherwise i want a Error Exception.
My idea goes to us pattern like:
<form action="next site.php" method="post">
<input pattern="<?php $row['unique_code']; ?>"/>
<button class="btn btn-success">Send</button>
</form>
But this doesn´t work. How can i solve this? Try and catch as an alternativ ?
Composite Pattern: Is the root a simple Composite?
To implement the Composite pattern in Java I have an abstract class Component with the functions getChild(int i), add(Component c), remove(Component c), forAllDo() and getChildren().
It is implemented by the two classes Leaf and Composite.
Leaf throws for nearly every function an exception - only forforAllDo() something is done with it. How would you implement the Root? I would understand it as a normal Composite class - all the functions make the same sense. Have you any arguments that that is not the case?
Question about Strategy and Template Method pattern
so I've been using a strategy pattern together with the template method pattern to create some logic that changes over the years. Let me try to explain:
- My logic is different per Country (EN, PT)
- For each country it's also diff per year but some methods can be the same over the years.
So what I've got in terms of code is:
- common interface "IWork"
- a strategy class that giving the country and year returns the correct country-year class. ex: Work_EN_2018 or Work_PT_2019
- country-year implementations (ex: Work_EN_2018) that extends from a base class (BaseWork_EN)
- base class per country (BaseWork_EN or BaseWork_PT)
It all works good but now with over 10 years things are starting to be hard to maintain all because some methods are the same for multiple years but after a specific year logic changes. So our solution for now is if logic changes for a specific method we change the base class method with the new logic and for all previous years we override the method in the year class (ex: Work_EN_2017, Work_EN_2018, etc). This is very troublesome and hard to maintain so my question is how can this old logic be maintained in a better way?
For now, I'm thinking in creating an utils class with these old methods so that at least in older class years I just reference one single implementation, it's this the only solution?
Sorry if the description of the problem is not clear.
Thanks
I want to convert a binary code to a grey code using 16-to-1 MUX
The problem is that I didn't learned yet adders or VHDL (which a lot of people are telling me to use them) but all I have is 16-to-1 MUXs.
Should I link each MUX with the other from the select input? (Knowing that I have 4 inputs and 4 outputs obviously)
P.S: I am new to this kind of stuff and I am having a hard time to solve this.
Thank you in advance.
Is it advisable to have a static block inside static inner class
I am in between an implementation where I am planning to use static block inside static Inner class.
This implementation is being done as part of lazy initialization of a singleton class.
I am not able to find any information on google if it is advisable or a good practice to do so?
Any suggestions are welcome.
public class MySingleton {
private MySingleton() {
}
private static class InnerMySingleton {
private static volatile MySingleton mysingleton;
static {
mysingleton = new MySingleton();
}
}
public static MySingleton getInstance() {
return MySingleton.InnerMySingleton.mysingleton;
}
}
Hoc semantic-ui Popup
I'm trying to create HOC function that wrap any component with semantic Popup. I have a function 'withCopy' that returns React.Component. This code doesnt work. Ite returns Wrapped component without Popup and CopyToClipboard. This is my code:
export const withCopy = (WrappedComponent: any, content: string) => {
return class extends React.Component {
render() {
return <Popup
trigger={
<CopyToClipboard text={content}>
<WrappedComponent />
</CopyToClipboard>
}
content="Copy to clipboard"
position='bottom center'
/>
}
}
}
Any help?
mardi 26 novembre 2019
Design - Ruby- Create CSV files as per User defined header From same data source
I am working on requirements we have data in hash around 100+ keys. we need to generate CSV file as per user-defined header with some transformation, we may end up having 100+ template Main changes will be 1) Change column name such as Fname –> First name 2) Data transformation like Full name – > First name + Last name (adding 2 column) 3) Fixing the position of a column – Fname should be at 35 positions etc.
please suggest is it possible to define declarative way or any gem available. Can you let me know any design pattern we can apply here?
Thanks for help
Presenting a view controller based on a policy in swift
I have some policy in my application which values are changed. For instance:
var canGoToPageX
when the value of canGoToPageX is true, user can be redirected to "x" view controller
if canGoToPageX {
present X view controller
}
this View controller is presented in several pages, if a developer forgets to write the if condition, user will be redirected to a page which he doesn't allowed.
I wanna do something to avoid this mistake
Is there any design pattern for this?
Background processing Task - Rails
I have a Rails Application (5.2.3).
There is a Model called Invoice.
The User can import Invoices through a view, uploading a XML file.
Now, the stakeholders are asking to have a mailbox where any User could send XML files, and the files will be automatically uploaded to the system.
The System is currently running on AWS, so a just created rule in the SES (SIMPLE EMAIL SERVICE) for a x@x.com mailbox to save all the messages in a S3 Bucket, to be parsed lather.
I could just do a plain script with everything(get files from S3, extract XML, Create Invoice) and schedule a runner. However, what is the Rails way for this kind of situation?
I read about Service Objects, but I'm not sure if it's the best place to have this task.
Thank you
What is the cleanest way to cache an instance of ExecutorService when you can't use dependency injection?
I'm currently working on a task where whenever a new HTTP request is made to the server, an instance of the handler is created. This handler will hold the logic of processing the HTTP request. This background information is needed to note that a new instance of the handler will be created for each request. I cannot change that since that is just how the architecture was built.
Now, I have a scenario where I would like use an ExecutorService (say newFixedThreadPool
) in the logic of this handler. Since a new instance of the handler is created every time, I cannot do the following within the handler class:
private static final ExecutorService MY_EXECUTOR = ExecutorService.newFixedThreadPool(5);
This would be pointless since that line would be executed for every single request.
My initial solution was to have another class which would hold a reference to the ExecutorService, and then I would inject this instance into the handler. Unfortunately, I cannot inject arbitrary classes into the handler (once again, due to the architecture).
With these constraints in mind, how can I have a reusable ExecutorService?
This was the only thing I could come up with:
public final class HandlerHelper {
private static final ExecutorService MY_EXECUTOR = ExecutorService.newFixedThreadPool(5);
private HandlerHelper() { }
public ExecutorService getExecutorService () { return MY_EXECUTOR; }
}
However, that's pretty ugly. So I'm hoping somebody can help me out with a better design here.
PostgreSQL - Query keyword patterns in columns in table
we all know in SQL we can query a column (lets say, column "breeds") for a certain word like "dog" via a query like this:
select breeds
from myStackOverflowDBTable
where breeds = 'dog'
However, say I had many more columns with much more data, say millions of records, and I did not want to find a word, but rather the most common keyword pattern or wildcard expression, a query like this:
SELECT *
FROM myStackOverflowDBTable
WHERE address LIKE '%alb%'"
Is there an efficient way to find these 'patterns' inside the columns using SQL? I need to find the most common substring so-to-speak, per the query above, say the wildcard string "alb" appeared the most in a "location" column that had words like Albany, Albuquerque, Alabama, obviously querying the words directly would yield 0 results but querying on that wildcard keyword pattern would yield many, but I want to find the most repeating or most frequent wildcard/keyword pattern/regex expression/substring (however you want to define it) for a given column - is there an easy way to do this without querying a million test queries and doing it manually???
Does it make sense to put on every spring boot service an interface?
Which kind of design pattern speaks for and which against haven an interface on every Service in Spring / SpringBoot?
Java Builder Pattern implementation, which one is better?
Looking at Joshua Bloch's way of doing builder pattern in java I have this class:
public class NutritionFacts {
private final int calories;
private final int fat;
private final int sodium;
public static class Builder {
private int calories = 0;
private int fat = 0;
private int sodium = 0;
public Builder calories(int val)
{ calories = val; return this; }
public Builder fat(int val)
{ fat = val; return this; }
public Builder carbohydrate(int val)
{ carbohydrate = val; return this; }
public Builder sodium(int val)
{ sodium = val; return this; }
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
private NutritionFacts(Builder builder) {
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
}
}
which I can invoke this way to instantiate a NutritionFacts object:
NutritionFacts cocacola = new NutritionFacts.Builder().calories(140).build()
There is also a slight variation where I can have this class:
public class NutritionFacts {
private final int calories;
private final int fat;
private final int sodium;
public static class Builder {
private int calories = 0;
private int fat = 0;
private int sodium = 0;
private Builder(){
}
public Builder calories(int val)
{ calories = val; return this; }
public Builder fat(int val)
{ fat = val; return this; }
public Builder carbohydrate(int val)
{ carbohydrate = val; return this; }
public Builder sodium(int val)
{ sodium = val; return this; }
public NutritionFacts build() {
return new NutritionFacts(this);
}
}
public static Builder builder(){
return new Builder()
}
private NutritionFacts(Builder builder) {
calories = builder.calories;
fat = builder.fat;
sodium = builder.sodium;
}
}
And now I can do this to create an instance of NutritionFacts:
NutritionFacts cocacola = NutritionFacts.builder().calories(140).build()
What should be the preferred way to apply the builder pattern? Are the two mentioned approaches exactly the same in terms of results (clean, immutability, ecc.). Is anything wrong with second approach?
I'd like to have your expert opinion on this.
Best practice to use mapEventToState with incoming streams?
Is there any elegant way to map incoming streams from a private api directly inside mapEventToState() without having to create redundant private events in the bloc?
I came with this solution. It's ok with one single stream, but with multiple streams it starts to get a mess. Thanks in advance.
// (don't mind the imports, this is the bloc file)
class ExampleBloc extends Bloc<ExampleEvent, ExampleState> {
final MyPrivateApi api = MyPrivateApi.instance; // singleton
ExampleBloc() {
// api has a stream of booleans
api.myStream.listen((b) {
// if it's true fire this event
if (b) this.add(_MyPrivateEvent());
}
@override
ExampleState get initialState => InitialExampleState();
@override
Stream<ExampleState> mapEventToState(
ExampleEvent event,
) async* {
if (event is _MyPrivateEvent) {
yield SomeState;
}
}
// private Event
class _MyPrivateEvent extends ExampleEvent {
}
JavaScript handling multiple filter conditions
I have a big JSON information and some query strings are passed to filter that JOSN data. For example dept=eng&date=2019-11-26&passport=true. It need not be in any particular order. It can be by dept and then by date and then by passport, or only date or dept and then passport, or any possible combination.
Now, I am not asking for how to write filtering logic, but I want to know what is the best way to handle such combinations in code.
What I can think of is
if(dept){
result = {// do something}
if( date) {
result = { //do something more(result }
}
}
if(date) {
result = { // do something }
// handle all combinations
}
// more if conditions
I am pretty sure this is not the best approach.
Again I am not asking how to write all this filter logic but want to know what is the best way or pattern to handle such permutations and combinations of filtering.
What is the recommended way to update a LiveData variable in ViewModel from Repository in the MVVM design pattern?
I am a beginner in MVVM architecture. I want to retrieve a list of items from the database and I want to keep track of the number of items that i retrieve. I am following the MVVM design pattern. The following is the first approach I thought of:
class SampleViewModel extends ViewModel
{
private MutableLiveData<Integer> count = new MutableLiveData<>();
getItems();
public void getItems()
{
List<String> items = new ArrayList<>();
/*
* I am skipping the code to access the database and retrieving the list
* */
for (String item : items)
{
items.add(item);
count.setValue(items.size());
}
}
LiveData<Integer> GetCount()
{
return count;
}
}
Then observe the count
data from my activity. But, then I learned that, it is recommended to do database related tasks from the Repository and according to this doc, LiveData variable is not recommended to be passed from ViewModel to Repository. So, my question is how can I update count
variable from Repository or in other words, What is the recommended way to update a LiveData variable in ViewModel from Repository, so that it can be observed fro the activity properly?
Suppose I want a regex pattern for all the numbers in pdf which should identify ALL the numbers with special characters between numbers [duplicate]
This question already has an answer here:
Haemoglobin 136 g/L 130 - 170
Is this singleton implementation correct?
As the double lock checking doesnt works on optimized compilers I am removing it from my singleton class and instead going for early initialization.
Below is my new singleton class :
class MySingleton {
private static volatile MySingleton myInstance = new MySingleton();
public static getInstance() {
return myInstance ;
}
}
Apart from getInstance() there are setter methods in the class which set the values of the member fields.
Hope this implementation will not cause any data inconsistency when multiple threads will be updating various member fields using the same object.
Any suggestions or inputs are welcome.
Why isn't the "has-a" pattern more used in Javascript? [on hold]
I am a big fan of composition over inheritance in JS, so I use the "has-a" pattern a lot. Sometimes using this pattern forces me to pass the parent to the child in case it needs to access some parent's method.
The parent class:
import { ChildClass } from "./child.js";
class ParentClass {
constructor() {
this.someValue = 3;
this.child = new ChildClass(this);
}
someFn() {
console.log("Value from parent: ", this.someValue);
}
test() {
this.child.printParentValue();
this.child.callParentFn();
}
}
const parent = new Parent();
parent.test(); // works fine, prints both "Value from parent" and "Value from child"
And the child class:
export class ChildClass {
constructor(parent) {
this.parent = parent;
}
printParentValue() {
console.log("Value from child: ", this.parent.someValue);
}
callParentFn() {
this.parent.someFn();
}
}
However, I haven't seen this pattern used in another codebase yet, nor the this.parent = parent
thing.
Why isn't the "has-a" pattern more used in JS? Am I programming "against the language" here? Is there some other, more idiomatic pattern allowed by the language that I might be missing?
lundi 25 novembre 2019
Pattern matching against Excel worksheet data
I have an excel worksheet with multiple columns of data of which I am trying to find any strings with within the rows that is matches the pattern with format XnnnnnnnX; where X is any alphabet[A-Z] and n is a number [0-9]. Alphabets are non-case sensitive. There are exactly 7 numbers [n] in this pattern. Example: S1234567J or T1231112J Upon finding the pattern, I will need to highlight it or colorise it.
Is there any way to achieve this in excel without using regex?
Thanks in advance!
What is the community preferred Python design pattern for accumulating values in a dictionary? [duplicate]
This question already has an answer here:
I often find myself writing this pattern for accumulating counts about a thing in a dictionary. In this case, I'm gathering up host hardware information for a datacenter application, and the pattern is the same I have often used.
Today, I was wondering if there is a better way (more Pythonic) to construct this pattern?
I did take a look around S.O. the most common result is using append on a list to add things which do not exist, but that does not address how to do an accumulator in a dictionary where the incoming key/value may or may not exist in the dictionary already.
hardware_types = []
for host in hosts:
hardware_type = hosts[host]['hardware_type'])
if hardware_type in hardware_types:
hardware_types[hardware_type] += 1
else:
hardware_types[hardware_type] = 1
Thanks, Bob
Calculate value in API call and remember it across the whole request
I am looking for the best design to implement the following. I have ClassA and ClassB A method called MethodA in ClassA calls MethodB1 in ClassB. MethodB1 is something like
public bool MethodB1()
{
var x = ClassC.CalculateX();
if(x)
{
return false;
}
//do something else;
return true;
}
MethodA calls MethodB1 only once.
There are other methods in ClassB that call MethodB1 multiple times in a loop.
Typically we have two scenarios:
API endpoint => MethodA => MethodB1 (here we know the value of x that never changes in a single call) => MethodB2 => MethodB1 (called multiple times in a loop)
API endpoint => MethodB2 => MethodB1 (called multiple times in a loop and we will get the value of x that is not going to change in a single call)
Getting the value of x is expensive operation, I want to do it once in the first scenario and remember it in the current call to be used in other places in ClassA and ClassB. Any suggestions are welcome.
Shared access tokens in a distributed system
'm building a system that horizontally scales with many nodes. Any of these nodes could consume an API that's hosted on https://example.com/api. The authentication for this API is token based.
My question is, should each of my nodes authenticate separately and fetch their own token? Or should I build a shared cache between them and store the token there?
If latter, are there any standards for this design pattern, or better yet libraries that can do this for me? ie. stores the token in cache, and takes a lambda function + ttl for auth or renewal)
Thanks!
Create a simple case-insensitive RegEx which is made up of ONLY vowels and prime numbers?
rules:
the entire string for the pattern must be 4 characters in size.
it can contain vowels (a,e,i,o,u) and the first 4 prime numbers ( 2,3,5 and 7).
make it so that if you enter a vowel in uppercase, it still works.
My solution/attempt:
/^(?i)[a|e|i|o|u|2|3|5|7]{4}$/
but I can't help but wonder if its the most compact way of doing it, there has to be a way to shorten this ? ranges perhaps ? or break this down into two seperate expressions which work in unison ?
Using the above rules and expression the following would be observed:
E5i3 = TRUE ( valid )
o7A3 = TRUE ( valid )
0eiA = FALSE ( invalid )
is there a better way to shorten the expression i'm using ?
Class of an entity recognition
trying to start with nlp using with python using nltk or spacy : my question is : if I have a sentence : 'Barack Obama was the former President of united states' can I retrieve the word president ( it's to say the class of the entity ).
How best to design configurable overloaded operators?
I have a class called BitArray
which provides a convenient interface for working with variables as if they were hardware registers. So, for example, if x0
represents a 64-bit GPR, then if I say x0[15:8]
, then I want the second-to-least-significant byte.
In addition to a value
, every object possesses a width
property which specifies the number of bits the object holds.
I have overloaded most of the operator methods to provide functionality for bit-shifting, bit-wise operations, arithmetic, and so on. This was all pretty straight-forward, but the tricky part comes in when dealing with the width
. For example, what is the right behavior if I bit-wise or two BitArray objects together that have different widths? If I use the left-shift operator, should I left bits disappear off the end, or should I expand the width of the object? And so on.
I could simply pick answers to these questions, but I think that maybe different behavior might be desirable in different contexts and I would like the users of this class to be able to have some way of configuring the behavior. For example, I expect that when an object represents an actual register, the user will want the register to stay fixed at a specific width, but when the object represents a literal value that is being used in an expression, then the width should be dynamic.
My question is: what is the best way to go about doing this? Here are some of my ideas:
- Instead of using the operators, I could use explicit method names with additional parameters that tell the methods how to behave.
- I could add some static members to the class which tell the methods how to have.
- I could make non-static members so that it is configurable per-object.
- I could make separate subclasses, one which has dynamic width and the other with fixed-width.
I'm not crazy about option 1 because I really want the use of the class to be convenient, and that means being able to use all the builtin operators.
But I'm worried that if I do option 2 or 3 that it will be confusing from the users perspective what is happening at any given line of code because the behavior will depend on any other line of that might have changed the configuration fields.
Are there other good options I haven't thought of?
Proper Separation of Concerns When Using UnitOfWork?
I followed an online tutorial of the UnitOfWork pattern with Entity Framework as it has been awhile since I have used it. I am confused as to why in the tutorial the DataContext is a parameter of the public UnitOfWork constructor. This means if I use the UnitOfWork in another layer of the application, the other layer must be aware of the DataContext. This does not seem like a good separation of concerns. Am I missing something?
UnitOfWork:
public class UnitOfWork : IUnitOfWork
{
private readonly PurchasingDataContext _context;
public UnitOfWork(PurchasingDataContext context)
{
_context = context;
Items = new ItemRepository(_context);
Manufacturers = new LabelerRepository(_context);
Quotes = new QuoteRepository(_context);
Vendors = new VendorRepository(_context);
Contacts = new ContactRepository(_context);
}
public IItemRepository Items { get; private set; }
public ILabelerRepository Manufacturers { get; private set; }
public IQuoteRepository Quotes { get; private set; }
public IVendorRepository Vendors { get; private set; }
public IContactRepository Contacts { get; private set; }
public int Complete()
{
return _context.SaveChanges();
}
public void Dispose()
{
_context.Dispose();
}
}
Interface:
public interface IUnitOfWork : IDisposable
{
IContactRepository Contacts { get; }
IItemRepository Items { get; }
ILabelerRepository Manufacturers { get; }
IQuoteRepository Quotes { get; }
IVendorRepository Vendors { get; }
int Complete();
}
Best way to implement recurring jobs with node-schedule and FB Send API?
I'm trying to schedule a Messenger bot to send a message everyday at 12:00 using node-schedule to multiple users. I'd like to find the best way to do so overall having in mind any server shutdown/restart or human errors, since jobs will only continue to execute while the app is running.
I was thinking on having all the recipient ids stored somewhere else than memory in case the server restarts. Load them into an array and perform a given sendMessage
function for each recipient id using the schedule.scheduleJob()
which runs every 24 hours. Would this be a decent approach?.
Design patterns in c++ for a simple Battleship game (linux terminal only)
It almost kind of seems like C++ really wants to make things extra hard for design patterns because I really don't want to change my design, just to accommodate such strict static typing.
So, I have an assignment in my c++ class where we make the simple game of Battleship. The constraints are we can't use anything from the STL (so I had to make my own custom vector with templates which works very well, nearly identical to the c++ vector).
So here's the thing, originally I started very simply with a PlayerBase class that PlayerHuman and PlayerComputer were derived from. Being new to polymorphism, I thought it'd be cool to put pure virtual functions getReady() and getShot() in PlayerBase to force PlayerHuman and PlayerComputer to implement them. So far that seemed like a great idea.
Well, I ran into a little problem. (I'm really picky about trying to get a proper design down) I noticed how my design for getting player input was entirely dependent on the terminal. What if I wanted to easily switch out a terminal interface for a web interface? So, I should separate my user interface from my Player classes.
So now I had another choice. Should I have a separate HumanTerminalInterface object that is stored inside PlayerHuman (using aggregation) so I can easily swap that out with something else that matches that interface? OR... should I turn the class PlayerHuman into a public data structure that is passed to a function that changes it?
Ex:
PlayerHuman
GenericInterface UI = HumanInterface
PointData getShot()
return UI.getFiringSolution()
Or:
PlayerHuman Sean;
PointData = callHumanUI(Sean&)
I opted for the second option along with instead of callHumanUI I got more fancy:
fake_vector<PlayerBase> players
callUI(PlayerHuman)
callUI(PlayerComputer)
So, I'm feeling pretty good about myself by separating the interface from the logic and storing entirely different objects in the same vector under 1 base type! WAIT A SEC!!! callUI only recognizes the derived classes...
I can't put my objects that are stored in the Base class array in there and expect them to work. Well, I could not put them in an array? WRONG! I need to swap the players every turn. So swap(player1, player2).
This is all because I can't get c++ to recognize these data structures have different types even though they are in a generic base class array. I know that means my design is wrong if I'm trying to do it this way.
The whole point of polymorphism is to make it so types don't matter. So,this was my solution, and it was ugly. Inside the PlayerData structure, I added a string "playerType" that is either "human" or "computer" then inside the callUI functions I have an if statement that calls other functions based on if the structure is Human or Computer. Yes, it works, but that DEFEATS the whole point of overriding functions like this. We do that so we don't have to use IF statements.
Is there a better way to do this? I know there isn't any code in here, this is purely design concept with the limits of c++. If you really want to look through my 1300 lines of code, go ahead. https://pastebin.com/f0MZ2rvJ
Recommendation for Design pattern for errorcodes handling
Suppose you are dealing with a situation where you need to handle lot of errorcodes from different server, what would be the design pattern to apply?
- Suppose 400 is errorcode, sometimes errormessage can vary. For example, a) 400:Cannot handle , b) 400:Unknown User.
- I have currently created an enum, which lists all the error codes in one place, with its unique error message. So that, this enum could be used to map to a handler.
- My specific doubt is how to create handler class, what design pattern to apply here. Basically my objective is to write some beautiful code, which could be reused, in case of future, different error codes appear from the server.
Is there any open source code example, which I can refer to, handling similar scenario.
Adapter Pattern Application
GOF has the following point for application of Adapter pattern:
you need to use several existing subclasses, but it's impractical to adapt their interface by subclassing every one. An object adapter can adapt the interface of its parent class
What does it mean? Please give an example of the scenario? (Code is not required)
Thanks
How to design different kinds of (nearly) the same
I have the following problem (in Scala)...
I want to read wavefront files (.obj) and transform them to something I can work with later. The wavefront files I want to support are files with the following definitions for:
- TypeA: vertices and faces
- TypeB: vertices, texture and faces
- TypeC: vertices, normals and faces
- TypeD: vertices, textures, normals and faces
I will read them and create a Mesh (a model class for later use) of it with the following fields:
- TypeA:
Array[Float]
,Array[Int]
- TypeB:
Array[Float]
,Array[Float]
,Array[Int]
- TypeC:
Array[Float]
,Array[Float]
,Array[Int]
- TypeD:
Array[Float]
,Array[Float]
,Array[Float]
,Array[Int]
I discovered two approaches:
1. Approach:
each type gets it's own model class
- TypeA:
case class TypeA(vertices: Array[Float], index: Array[Float])
- TypeB:
case class TypeB(vertices: Array[Float], textures: Array[Float], index: Array[Float])
- TypeC:
case class TypeC(vertices: Array[Float], normals: Array[Float], index: Array[Float])
- TypeD:
case class TypeD(vertices: Array[Float], textures: Array[Float], normals: Array[Float], index: Array[Float])
With this approach I don't have to check if all fields are present. I can use them out of the box. The disadvantage is: I need to create a "build"-method for each type (something like: createTypeAFromFile(filename: String)
)
2. Approach I create something like a uber-model:
case class(vertices: Array[Float], textures: Option[Array[Float]], normals: Option[Array[Float]], index: Array[Float])
With this approach I only need one "build"-method, but the problem here, later I have to check if the fields I want to use are really present (for normals and textures)
Question:
Does anyone knows a better approach/design, for this kind of problem?
dimanche 24 novembre 2019
XSD pattern of a vector of ints separated by a char
I need to restrict this structure:
<IN> 43.3,42.4,42.2,42.0,41.8,41.6,41.2,40.8,40.4,39.8,39.4,38.7,38.0,37.3,36.5,35.7,34.8,33.9,33.0,31.9,30.9,30.0,29.0,27.9, 0.0</IN>
Does someone know the restriction pattern? I need to do something like that, I am not quite sure if its correct.:
<xs:simpleType name="inType">
<xs:restriction base="xs:string">
<xs:whiteSpace value="preserve"/>
<xs:pattern value="[ ]?[1-9]{1}[0-9]*[.]*[0-9]*([,]{1}[ ]?[1-9]{1}[0-9]*[.]*[0-9]*)*(, 0.0){1}"/>
</xs:restriction>
</xs:simpleType>
Thanks in advance
C - How to search for a pattern in a binary .dat file?
guys, I'm struggling with this problem. I want to search for a pattern in a binary .dat file.
This program of mine is a search by name of people registered in the system, I want to search for example by "Fu" and the program will display all information regarding users who have the pattern "Fu" in their names. The main problem encountered by me is that the program is detecting how many people have the default set in the search but it is displaying repeated information. I suppose I am manipulating the file in a wrong way.
Use the people.dat file for you to test the program: https://drive.google.com/open?id=1GwF6NZ16e2LA98Imnz_IKXQpjnCfllTg
#include <stdio.h>
include
include
typedef struct pes Pes;
struct pes {
int dia;
int mes;
int ano;
int numero_uf;
int uf;
char nome[101];
char enderCid[101];
char enderBair[101];
char numCasa[51];
char cpf[12];
char tel[13];
char email[31];
char login[51];
char senha[51];
char c;
char status;
};
void exibePessoasEncontradas(Pes** usuarios_encontrados, int quantidade);
int main (void) {
FILE* fp;
Pes* cadastro_pess;
Pes** usuarios_encontrados;
int i;
int aux;
int tam;
int achou;
char procurado[100];
char resp;
fp = fopen("pessoas.dat", "rb");
if (fp == NULL) {
printf("Ops! Ocorreu um erro na abertura do arquivo!\n");
printf("Não é possível continuar o programa...\n");
exit(1);
}
system("clear");
printf("\n =================================");
printf("\n | | | Programa Biblioteca | | |");
printf("\n =================================");
printf("\n >>> BUSCA PESSOA <<<");
printf("\n =================================");
printf("\n");
printf(" Informe o nome da pessoa a ser buscada: ");
scanf(" %100[^\n]", procurado);
i = 0;
aux = 0;
achou = 0;
cadastro_pess = (Pes*) malloc(sizeof(Pes));
while(fread(cadastro_pess, sizeof(Pes), 1, fp)) {
i += 1;
}
fclose(fp);
FILE* fp2;
fp2 = fopen("pessoas.dat", "rb");
if (fp2 == NULL) {
printf("Ops! Ocorreu um erro na abertura do arquivo!\n");
printf("Não é possível continuar o programa...\n");
exit(1);
}
tam = i;
usuarios_encontrados = (Pes**) malloc(tam * sizeof(Pes*));
char *ret;
while(fread(cadastro_pess, sizeof(Pes), 1, fp2)) {
for(int j = 0; j < strlen(procurado); j++) {
ret = strchr(cadastro_pess->nome, procurado[j]);
if((ret != NULL) && (cadastro_pess->status == '1')) {
usuarios_encontrados[aux] = cadastro_pess;
aux += 1;
achou = 1;
break;
// continue;
}
}
}
fclose(fp2);
if (achou) {
exibePessoasEncontradas(usuarios_encontrados, aux);
} else {
printf("\n %s não foi encontrado(a)...\n", procurado);
}
printf("\n Digite algo e tecle ENTER para continuar.\n\n");
scanf(" %c", &resp);
free(cadastro_pess);
return 0;
}
void exibePessoasEncontradas(Pes** usuarios_encontrados, int quantidade) {
for(int k = 0; k < quantidade; k++) {
int dia = usuarios_encontrados[k]->dia;
int mes = usuarios_encontrados[k]->mes;
int ano = usuarios_encontrados[k]->ano;
int numero_uf = usuarios_encontrados[k]->uf;
printf("\n\n Nome: %s \n", usuarios_encontrados[k]->nome);
printf(" CPF: %c%c%c.%c%c%c.%c%c%c-%c%c \n", usuarios_encontrados[k]->cpf[0], usuarios_encontrados[k]->cpf[1], usuarios_encontrados[k]->cpf[2], usuarios_encontrados[k]->cpf[3], usuarios_encontrados[k]->cpf[4], usuarios_encontrados[k]->cpf[5], usuarios_encontrados[k]->cpf[6], usuarios_encontrados[k]->cpf[7], usuarios_encontrados[k]->cpf[8], usuarios_encontrados[k]->cpf[9], usuarios_encontrados[k]->cpf[10]);
printf(" Data de nascimento: %d/%d/%d \n", dia, mes, ano);
printf(" Email: %s \n", usuarios_encontrados[k]->email);
printf(" Login: %s \n", usuarios_encontrados[k]->login);
printf(" Senha: %s \n", usuarios_encontrados[k]->senha);
printf(" Telefone: %s \n", usuarios_encontrados[k]->tel);
if(numero_uf == 1) {
char nome_uf[] = "Acre";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 2) {
char nome_uf[] = "Alagoas";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 3) {
char nome_uf[] = "Amapá";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 4) {
char nome_uf[] = "Amazonas";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 5) {
char nome_uf[] = "Bahia";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 6) {
char nome_uf[] = "Ceará";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 7) {
char nome_uf[] = "Distrito Federal";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 8) {
char nome_uf[] = "Espírito Santo";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 9) {
char nome_uf[] = "Goiás";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 10) {
char nome_uf[] = "Maranhão";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 11) {
char nome_uf[] = "Mato Grosso";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 12) {
char nome_uf[] = "Mato Grosso do Sul";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 13) {
char nome_uf[] = "Minas Gerais";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 14) {
char nome_uf[] = "Pará";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 15) {
char nome_uf[] = "Paraíba";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 16) {
char nome_uf[] = "Paraná";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 17) {
char nome_uf[] = "Pernambuco";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 18) {
char nome_uf[] = "Piauí";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 19) {
char nome_uf[] = "Rio de Janeiro";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 20) {
char nome_uf[] = "Rio Grande do Norte";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 21) {
char nome_uf[] = "Rio Grande do Sul";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 22) {
char nome_uf[] = "Rondônia";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 23) {
char nome_uf[] = "Roraima";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 24) {
char nome_uf[] = "Santa Catarina";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 25) {
char nome_uf[] = "São Paulo";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 26) {
char nome_uf[] = "Sergipe";
printf(" Estado: %s \n", nome_uf);
} else if(numero_uf == 27) {
char nome_uf[] = "Tocantins";
printf(" Estado: %s \n", nome_uf);
}
printf(" Cidade: %s \n", usuarios_encontrados[k]->enderCid);
printf(" Bairro: %s \n", usuarios_encontrados[k]->enderBair);
printf(" Numero da casa: %s \n", usuarios_encontrados[k]->numCasa);
printf("\n");
}
}
All Connections connect before app is Served
I have an application that has connects to Redis, Mongo, and Elasticsearch but how can I make sure all the connections are connected before the app is served? I notice that Elasticsearch usually takes longer and when I test my app using Supertest that the database connects but the console.info('Successfully connected to db');
doesn't log to the console before the tests start to run.
server.ts
const client = redis.createClient({ host: process.env.REDIS })
client.on('connect', function () {
console.log('Redis client connected');
});
mongoose
.connect(dbURL)
.then(() => {
return console.info(`Successfully connected to ${db}`);
})
.catch(error => {
console.error('Error connecting to database: ', error);
return process.exit(1);
});
};
const app = express();
export default app;
main.ts
import server from './server'
server.listen(8000)
Escaping meta-characters when searching for them in a string?
I was wondering, when trying to do a search for the .
, i tried this:
'\.'
, using a back slash to escape the meta-character
however when I tried to see if it would find it on this string:
My Silly Cat ate my hamster.
Oh well too bad.
my code simply returns False!
however when I tried this:
'\\.'
, the code searched the string and returned TRUE!
how and why does it return true when I double backslash the .
?
How is the following design pattern a Factory method. I believe it is more of a Abstract Factory than factory method
How is the design pattern used in the following question a Factory method?. I suspect it is neither Factory Method nor Abstract Factory. It is a mix of both.
interface Vehicle { }
class Car implements Vehicle{ } // Oil Vehicles
class Bus implements Vehicle{ }
class ElectricCar implements Vehicle{ } // ElectricVehicles
class ElectricBus implements Vehicle{ }
interface VehicleFactory{
Vehicle make(int seats);
}
class OilVehicleFactory implements VehicleFactory{ // Oil vehicle Factory
@Override
Vehicle make(int seats){
if(seats > 5){
return new Bus();
}
else{
return new Car();
}
}
class ElectricVehicleFactory implements VehicleFactory{ // Electric Vehicle Factory
@Override
Vehicle make(int seats){
if(seats > 5){
return new ElectricBus();
}
else{
return new ElectricCar();
}
}
class Client{ // Cient Code
boolean isElectric;
void doSomething(){
VehicleFactory factory;
if(isElectric){
factory = new ElectricVehicleFactory();
}
else{
factory = new oilVehicleFactory();
}
Vehicle vehicle = factory.make(5);
}
I believe it is NOT a factory method as:
-
It is using the interface VehicleFactory (which is used in Abstract Factory)
-
It is creating families of products such as Oil vehicles and Electric Vehicle
-
It doesn't use inheritance.
For the same reasons I believe that It is an Abstract factory method. But it doesn't use Composition for the factory.
What pattern is it exactly?
Thanks
Name of pattern where an object is stored by UUID
I am programming an application where I want to store Session information by a UUID. For this purpose, I wrote this code:
import uuid
class ObjectStore:
def __init__(self):
self.objects = {}
def add(self, obj):
uuid_value = uuid.uuid4() # UUID4 generates a random UUID
self.objects[uuid_value] = obj
return uuid_value
def retrieve(self, uuid):
return self.objects[uuid]
Is this structure a common pattern? If so, does it have a name?
Is there a design pattern or any typical solution for interrupting program execution without using exceptions?
I have method A called from another method of another class, which called from another method, etc. I have a condition in my A method and I want to do two things if it evaluates to false:
- print a certain message in a console
- interrupt program execution after that
The program must print an error message and then exit. I can implement it using exceptions, but I shouldn't, because it's not an exceptional case. Another way to do what I want is by using return value of method A. But in this case, I should use the return value of a method, calling method A, and so on. All the methods from the sequence of calls should return a value and no one of them can be ignored. I will have to write plenty of
if (!func()) return false;
and will be forced to print messages immediately before the first 'return' (using exceptions it is possible to print their own messages from a place where they were caught).
Is there any solution for my problem? Maybe there's something absolutely wrong in the way I'm thinking...
Flux Architectural Pattern VS Mediator Design Pattern?
I couldnot figure out the difference between Flux Architectural Pattern introduced by Facebook and Mediator Patter. What is the difference between the two?
Find padded hex (0xXX) in Lua string pattern
I have a Lua string...
str = "test,0x00,0x34,0x23"
and I want to find two elements within this string:
- The alphanumeric part (test)
- The comma separated hex values (0xXX)
I'm using the following pattern, which works...
_,_,a,b = string.find(str,"^(%a+),([x%x,]+)$")
print(a,b)
--> test 0x00,0x34,0x23
However, I want to catch errors, for example, malformed hex representations.
For example, using the above pattern example, it allows and successfully returns the following inputs:
str = "test,0x0x0,0x34,0x23" --> test 0x0x0,0x34,0x23
str = "test,0x00,34,0x23" --> test 0x00,34,0x23
str = "test,0x00,0x34,23x0" --> test 0x00,0x34,23x0
What pattern is needed to only accept valid padded hex form (string.format("0x%02x",72)
) please?
Making a Strategy turn based game similar to TFT (TeamFight Tactics)
I'm in my third year in computer science and this semester I have a Java project to make. so my instructor told us we have to make a strategy turn based game called TFT, even the characters are the same. I have very little experience in building games.So this is my first "BIG" project really.
The instructor gave us a general Class Diagram of the game but there are still a lot of unanswered questions about design patterns in the Diagram of the game. the Class Diagram is contained here in page 5 https://drive.google.com/file/d/1OV8fRTAaMEC-O_NafZZf1GD4ANOoDynW/view?fbclid=IwAR1_N9alZQXlcUcmt_tg-fKrKJCI4qvm1Ec9dsEHMIM21j5DZwB9dfxlaa8
i have the following questions:
What is the use of the DamageFactory?
what is the use of the RoundManager?
some abilites stay activated for a couple of rounds, how do i ensure this happens?
Why is there no need to make a class for every Champion and let them inherit from a champion class which has common features and attributes?
Redundant Function Call in Python
So I was looking at a certain class which has the following property function. However, the property method itself doest describe the proceduce instead calls another function to do so as follows:
class Foo():
@property
def params(self):
return self._params
@property
def target(self):
return self._target
def _params(self):
return print("hello")
def _target(self):
return print("world")
What I am trying to understand if it is somesort of pattern? I have seen similar thing in another class as well where the method with property decorator simply calls another method of same name with understore in the beginning.
How to correctly implement State Pattern?
- An Account could have various states such as Frozen, Active, NotVerified, Closed.
- And Account could perform following actions: Deposit(), Withdraw(), HolderVerified(), Close(), Freeze()
- These implementation of these actions could vary depending on current state of the account.
Below is my way of tackling the above scenario. However, what if we have a situation where we have to :
Deduct 10 percent of the deposit when the deposit is made when current state of the account is Frozen?
ACCOUNT
class Account
{
public decimal Balance { get; private set; }
private IAccountState State { get; set; }
public Account(Action onUnfreeze)
{
this.State = new NotVerified(onUnfreeze);
}
public void Deposit(decimal amount)
{
this.State = this.State.Deposit(() => { this.Balance += amount; });
}
public void Withdraw(decimal amount)
{
this.State = this.State.Withdraw(() => { this.Balance -= amount; });
}
public void HolderVerified()
{
this.State = this.State.HolderVerified();
}
public void Close()
{
this.State = this.State.Close();
}
public void Freeze()
{
this.State = this.State.Freeze();
}
}
IAccountState
interface IAccountState
{
IAccountState Deposit(Action addToBalance);
IAccountState Withdraw(Action substractFromBalance);
IAccountState Freeze();
IAccountState HolderVerified();
IAccountState Close();
}
Concrete Implementation of IAccountState
ACTIVE
class Active : IAccountState { private Action OnUnfreeze { get; } public Active(Action onUnfreeze) { OnUnfreeze = onUnfreeze; }
public IAccountState Deposit(Action addToBalance)
{
addToBalance();
return this;
}
public IAccountState Withdraw(Action substractFromBalance)
{
substractFromBalance();
return this;
}
public IAccountState HolderVerified() => this;
public IAccountState Freeze() => new Frozen(this.OnUnfreeze);
public IAccountState Close() => new Closed();
}
NOTVERIFIED
class NotVerified : IAccountState
{
public Action OnUnfreeze { get; }
public NotVerified(Action onUnfreeze)
{
this.OnUnfreeze = onUnfreeze;
}
public IAccountState Close() => new Closed();
public IAccountState Deposit(Action addToBalance)
{
addToBalance();
return this;
}
public IAccountState Freeze() => this;
public IAccountState HolderVerified() => new Active(this.OnUnfreeze);
public IAccountState Withdraw(Action substractFromBalance) => this;
}
How will you deal with the situation when you have to deduct 10 percent of the deposit when current state of the account is Frozen?
I am not sure how to modify Deposit method in NotVerified class to meet the requirement :
public IAccountState Deposit(Action addToBalance)
{
addToBalance();
return this;
}
What is maintainability of the code and how to write more maintainable code? [on hold]
- What is maintainability of code?
- How can we find if the code is maintainable?
- How can we write more maintainability code?
How to implement the following
Imagine a bussiness that goes to your house to do some kind of service, like a plumber. The plumber is a person, you are also a person, and the people that work in the office are also persons.
To model these classes, we would have a person class wich all actors are, technician class (the plumber), and a employee class(people at the office).
I thought of having a person class, and technician, employee, manager, and orther would be child classes.
How would you do it? how would you persist it?
Singleton Pattern not returning same object in my Java Code
Is there any wrong in my Code. Because the variable not changing its value while applying Singleton Pattern.
My Code :
class Singleton{
private final static Supplier<Singleton> INSTANCE = Singleton::new;
private int variable = 33;
public static synchronized Supplier<Singleton> getInstance() {
return INSTANCE;
}
void print(){
System.out.println(variable);
}
void change(int variable){
this.variable = variable;
}
}
public class Design {
public static void main(String[] args) {
Singleton.getInstance().get().print(); // print 33
Singleton.getInstance().get().change(99);
Singleton.getInstance().get().print(); // need to print 99 but it prints 33
}
}
Please correct me Guys, if I'm wrong in implement Singleton Pattern.
samedi 23 novembre 2019
Pass refresh and dashboard command to other modules
I have an angular app which is behave as dashboard. And there are libraries which are behave as widgets of the dashboard. When i do refresh or any dashboard specific command in side the dash board, all the widget also refresh and get the dashboard command. I use .forRoot() static method to pass data a between dashboard app and widget libraries but is there any other better way to pass refresh kind of operation from dashboard app to widget
Django Design question: How to break down the code properly
I would like to build an app which has some UI but a lot of backend activities. Basically, I would like to loop over list of files in a directory. for each such file, I would need to get a user feedback what is the type of the file, and then based on the file type, read all it's records and do some work on each. So the code will basically do:
Loop over all the files in a directory:
for each file --> Show the user the file name and then the user can select the right file type
Loop over all records in this file
Do Something
My question is where should the loop over the files should be? In the view or in the html?
If it is in the view, the HTML rendering to ask the user to select file type will be moving the control to the client (html) and then (after after user selection), It will return as a POST reply (outside the loop), right? So should the loop over the files be in the html itself?
What should be the right breakup between the HTML and the View?
Flutter dart design pattern - form data manipulation
Which is the better way to manipulate form data ? With immutability (with finak keyword on property models) or not ?
Model class immutable:
class Contact {
final String id;
final String name;
// many fields
Contact({this.id, this.name});
}
OR Model class without final keyword :
class Contact {
String id;
String name;
// many fields
Contact({this.id, this.name});
}
The model class Contact is loaded from database in this dummy example;
Here I use Contact model with immutability (with final keyword), and make a copy of the Contact, for every attribute change state:
...
Contact contact;
@override
void initState() {
// load from database
contact = Provider.of<ContactProvider>(context, listen: false).findContactExample();
super.initState();
}
...
Form(
key: _form,
child: ListView(
children: <Widget>[
....
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
initialValue: contact.name,
onSaved: (value) {
// make a copy of contact for every attribute change
contact = Contact(id: contact.id, name: value);
}
),
....
],
),
),
...
OR here I use contact without final keyword, and changing property directly in the object, without make a copy.... changing object state.
...
Contact contact;
@override
void initState() {
// load from database
contact = Provider.of<ContactProvider>(context, listen: false).findContactExample();
super.initState();
}
...
Form(
key: _form,
child: ListView(
children: <Widget>[
....
TextFormField(
decoration: InputDecoration(labelText: 'Name'),
initialValue: contact.name,
onSaved: (value) {
// changing object state
contact.name = value;
}
),
// .... there are many field
],
),
),
...
How to using delegate in Android using Java in Android Studio
How can I implement the delegate pattern for use on Android. For example to clean up the code in onCreate. Using Java in Android Studio.
Showing Ascii Bannner Art on TextView
I am trying to show some ASCII Banner Art to Textview in Android , but the output does not match the original string it comes with disordered !
here I am attaching the image of strings.xml
Best design for two different tables with 90% same columns
I have a feature_values
table which contains data stored by users: they can edit and update this table.
#user_feature_values
user | year | quarter | gdp | other
---------------------------------------
1 2018 Q1 1.5 1.2
1 2018 Q2 1.6 1.5
5 2017 Q1 -1.2 1.0
.......................................
.............
4 2017 Q4 1.0 2.5
There is another similar table which stores default values. Users can't edit this.
#default_feature_values
country | year | quarter | gdp | other
---------------------------------------
5 2018 Q1 1.8 2.0
10 2015 Q2 1.4 1.2
120 2017 Q3 -1.2 1.0
.......................................
.............
115 2016 Q4 1.5 2.15
Current scenario: Once the user is created, I am literally copying the default values into #user_feature_values
based on the user's country. So that they can edit the default values in their table with their own values. At a later time, they can opt for default values; which are copied to #user_feature_values
table from #default_feature_values
table.
Is this a bad design?
How well this can be implemented?
How to split a String and keep the delimiter '='
I have a string like this
String s = "p=YSp%hZ5=YunnYDUuGxVxAeLCZuVvSfoutO8=";
String[] array = s.split("=");
This array will give me an an output like this: p, YSp%hZ5, YunnYDUuGxVxAeLCZuVvSfoutO8
Desired would be to have those elements but keep the = sign like: p=, YSp%hZ5=, YunnYDUuGxVxAeLCZuVvSfoutO8=
I need to split it by = sing and keep the '=' sign somehow. Does anyone knows some pattern which will help me with it.
JAVA Find parentheses surrounded sections in a String using Matcher/Pattern
I'm using this
Matcher m = Pattern.compile("-?\\d+(\\.\\d+)").matcher(strings);
while(m.find()) {
double value = Double.parseDouble(m.group());
sb.append(value);
It works fine for the most part, but I'm trying to find numbers that may OR may NOT be surrounded by (parentheses). I'm wondering if its as simple as just changing this part
("-?\\d+(\\.\\d+)")
I tried using \p{Punct}?
at the beginning and end; obviously, that didn't work.
vendredi 22 novembre 2019
Urgent! Functional vs Non-Functional Requirements for AI software
I have to write documentation for my program and I am really short on time. They ask me to define functional and non-functional requirements.
However, it is a program that takes photos through the webcam, uses a neural network to classify the photos and shuts down the computer if it figures out the user is sleeping/away/whatever.
The entire focus of the project is the neural network. The app itself is simple, it is just to demonstrate that the net works. Even the user interface is almost non-existent, just like a start and stop option.
I have no idea what to write as functional and non-functional requirements. Can you help me?
Implementing C# IDisposible
I am trying to work out exactly what I need to do to dispose of a property in C# when using IDisposable. I can see the template, but I am not sure about actually disposing of objects.
I am working with the example given on this site: https://docs.microsoft.com/en-us/dotnet/standard/garbage-collection/implementing-dispose
I have added 3 properties:
privInt: Private value type. Would I dispose of this as it could be saved on the heap so may require GC??? If I would then how, cannot set to null or call dispose? If not then I assume it has to be left to GC - but is it not the point of Dispose to free resources???
NonIDisClassInstance - Do I set to null?? Is that enough
Can anyone comment on my implementation below and adivse on what is correct/wrong.
IDisClass - Just call dispose
class BaseClass : IDisposable
{
// Flag: Has Dispose already been called?
bool disposed = false;
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
//Private value type
private int privInt;
//Private class that does not implement IDisposible
Private NonIDisClass NonIDisClassInstance;
//Private class that does implement IDisposible
Private IDisClass IDisClassInstance;
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing) {
// Free any other managed objects here.
//
}
// Free any unmanaged objects here.
DisposeOfThis = ????;
NonIDisClassInstance = null;
IDisClassInstance.Dispose();
disposed = true;
}
~BaseClass()
{
Dispose(false);
}
}
How to design API for getting collections objects?
I have a lot of different lists. Objects of lists have fields that are objects too.
When I do request to the server, I get a response that sees like(people):
[
{
id: 1,
fistName: "Steve",
lastName: "Jobs",
companyId: 1
},
{
id: 2,
fistName: "Warren",
lastName: "Buffett",
companyId: 2
},
{
id: 3,
fistName: "Bill",
lastName: "Gates",
companyId: 3
}
]
Here companyId is ID of another object. The company, for example:
[
{
id: 1,
title: "Apple",
cityId: 1
},
{
id: 2,
title: "Berkshire Hathaway",
cityId: 2
},
{
id: 3,
title: "Microsoft",
cityId: 3
},
]
Here cityId is ID of objects cities etc.
When I get a list of people, I need to know the titles of companies and cities.
How can I design my API for it?
- One request that will send all the information. For example:
{
data: [], //Array of people
payloads: {
companies: [], //Array of companies
cities: [] //Array of cities
}
}
- Several requests each of which will send its information. Then I have to make several requests from client to server, each time requesting additional information.
Java design pattern for use different implementation of method with an abstract class as param
I got a problem of conception in my programm.
I got 4 classes (ChildA, ChildB, ChildC) who extends a parent class (Parent)
i got a method like it :
public void doInteraction(Parent a, Parent b){
a.doActionWith(b);
b.doActionWith(a);
}
My 3 child class and parent class :
public abstract class Parent {
public abstract void doActionWith(Parent other);
}
class ChildA extends Parent {
@Override
public void doActionWith(Parent other) {
System.out.println("childA use doActionWith abstract");
}
public void doActionWith(ChildA chila) {
System.out.println("childA use doActionWith childA");
}
public void doActionWith(ChildB chilb) {
System.out.println("childA use doActionWith childB");
}
public void doActionWith(ChildC chilb) {
System.out.println("childA use doActionWith childC");
}
}
class ChildB extends Parent {
@Override
public void doActionWith(Parent other) {
System.out.println("childB use doActionWith abstract");
}
public void doActionWith(ChildA childa) {
System.out.println("childB use doActionWith childA");
}
public void doActionWith(ChildB chilb) {
System.out.println("childB use doActionWith childB");
}
public void doActionWith(ChildC chilb) {
System.out.println("childB use doActionWith childC");
}
}
class ChildC extends Parent {
@Override
public void doActionWith(Parent other) {
System.out.println("childB use doActionWith abstract");
}
public void doActionWith(ChildA childa) {
System.out.println("childB use doActionWith childA");
}
public void doActionWith(ChildB chilb) {
System.out.println("childB use doActionWith childB");
}
public void doActionWith(ChildC chilc) {
System.out.println("childC use doActionWith childC");
}
}
When i call a.doActionWith(b); in doInteraction method : the abstract method is always used event the jvm knows the real type of a and b.
Why java dont use specific method with argument match exactly the type of param ?
The only solution i find , is to cast object to their child type. But i need to check their type with instance of.(imagine if i got 20 child class). And i remember my studies that an instance of reveals a bad conception.
I try some stuff like
public abstract <C extends Parent> void doActionWith(C other);
but same. I imagine a design pattern solve this problem but i dont find it. Maybe i should use interface, but i don't see how i should do it.
Thanks for reading.
fabien.
AngularJS prevent number input to add decimal values
I have the following input of type number:
<input class="number text-center" type="number" step="1" ng-model="item.formattedQuantity" ng-disabled="item.discount === '100.00'" ng-change="change(item)" ng-blur="blur(item)" min="0" />
What can I do to forbid users adding decimal values? I tried adding step=0.01 and ng-pattern ng-pattern="/^[0-9]+$/" but users could still place values like 1.5, 31.56, etc.
What can I do?
CakePhp 3.8 with Jquery autocomplete not working
I'm trying to use the autocomplete jquery function to complete a field with one of two source values: ['pere', 'mele']. unfortunately it does not work.
default.ctp
<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<script
src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"
integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<!------ Include the above in your HEAD tag ---------->
<?php echo $this->Html->script(['single']) ?>
in view file
<?php echo $this->Form->create($societa); ?>
<fieldset>
<h1>Aggiungi Società</h1>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->control('nome_societa',['class'=>'form-control','required' => true]);?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->control('nome_societa_abbreviato',['class'=>'form-control','required' => true]);?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->control('sede',['class'=>'form-control','id'=>'naruto','required' => true]);?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->control('cap',['class'=>'form-control','required' => true]);?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->control('citta',['class'=>'form-control']);?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->control('pr',['class'=>'form-control']);?>
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<?php echo $this->Form->button(__('Salva'),['class'=>'btn btn-primary']);?>
</div>
</div>
</fieldset>
<?php echo $this->Form->end();?>
<?php echo $this->Html->link('Indietro', ['action'=>'index'], ['class'=>'btn btn-primary']) ?>
in js file single.js
$(document).ready(function(){
$("#naruto").autocomplete({
source:['pere','mele']
});
});
in console google chrome
A cookie associated with a cross-site resource at http://bootstrapcdn.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
add#:1 A cookie associated with a cross-site resource at http://forum.jquery.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
add#:1 A cookie associated with a cross-site resource at https://forum.jquery.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
add#:1 A cookie associated with a cross-site resource at http://jquery.com/ was set without the `SameSite` attribute. A future release of Chrome will only deliver cookies with cross-site requests if they are set with `SameSite=None` and `Secure`. You can review cookies in developer tools under Application>Storage>Cookies and see more details at https://www.chromestatus.com/feature/5088147346030592 and https://www.chromestatus.com/feature/5633521622188032.
unfortunately the file does not work even if the console does not give errors