Front Mentor
- Linux:
-
- Show the screen resolution: xrandr -q
-
Program to record OBS Studio : ffmpeg(x11grab for other Display
Servers): example ffmpeg -f xwayland -s 1360x768 -i :0.0 -r 10 -b:v
1M /home/manuel/Documents/telescope-media-file.mp4
-
Edit video ShotCut and Convert to gif: ffmpeg -i output.mp4
output.gif
- Develop:
-
Indentation: Tabs for indentation, spaces for alignment
https://lea.verou.me/blog/2012/01/why-tabs-are-clearly-superior/
- Fonts to develop : DroidSansM Nerd Font
-
font-size: rem width: % in combination with a max-width, ch height:
question your self "do i rely need to set height" if yes -> use a
min-height padding/margin: rem or em, kevin often uses em for padding
of buttons media queries: em. px only for little things like shadows,
borders etc.
.woff2 fonts
https://gwfh.mranftl.com/fonts/finlandica?subsets=latin
- Architeture:
- MVC: Model View Controller
-
Hexagonal - Adapters and Ports : How to organize the app, separate
business logic from others (DB, API, User Interfaces) - Multiples
in/out ports
4 Parts: 1. Domain (Entities, business logic) 2. Inbound ports
(Interfaces) 3. Outbound port (Interfaces DB, email, etc) 4. Adapters,
concrete implementations of interfaces
- Docker:
- Show if docker is running well:sudo docker run hello-world
-
Add user to docker group: sudo groupadd docker -> sudo usermod -aG
docker $USER -> newgrp docker (to Restart docker group session)
- Dockerfile ->build (image) -> run (container)
- docker pull imageName : Download the image but not run it
- docker build -t imageName . : Create an image from Dockerfile
-
docker run --name myPersonalImageName imageName : Download(if
necessary) the image and run it
- docker run -d imageName : Run in detached mode
-
Run docker in interactive mode docker run -it --rm alpine sh (docker
run -it --rm alpine sh -c "apk add --no-cache bash && bash")
- docker images : show the images, use | head to show the last
-
docker ps : show all images. -a for stopped and running containers
-
docker start idContainer : start a docker stopped container.docker
stop idContainer
-
docker logs -f idContainer : show the log for the container. Can use
containerName
-
docker exec -it idContainer bash : Run a command in running container
-
docker run -dit --name my_alpine alpine-bash # Run the container in
detach mode docker exec -it my_alpine bash # Attach to the container
- docker logs -f : Show and wait for logs
-
docker run -dp 5000:3000 imageName : Run in port 5000 the app inside
container in port 3000
-
docker run -d -v /media/manuel/Datos/:/etc/todos -p 5000:3000
imageName : Shared a volume
Volumes to develop in container without re-build the image
-
docker run -dp 5555:5174 --name react-ts-list-app -v
/media/manuel/Datos/mgallegoa/conceptsProbes/react-ts-list-app/src:/app/react-ts-list-app/src
manuelarias/react-ts-list:v1 : Create a container and share a volume
for development
- docker builder prune : to purge the docker builder cache
-
Asymptotic notation:
Omega(n) notation: the lowest bound (best) of running time
Theta(o) notation: the average bound (average) of running time
Big O(O) notation: the upper bound (worse) of running time
-
Big O, BigO: Asymptotic notation
Video
- Time complexity
-
Constant: Not scale with the input of the function (take the constant
time to get the result). Big O(1)
-
Order of growth: O(1): constant O(log n): logarithmic. log 8=3. n/2.
Binary Search O(n): linear O(n log n): linearithmic (Quasilinear).
Merge Sort 1. Quick Sort : General-purpose, fast. 2. Merge Sort :
Guaranteed performance. 3. Timsort: Nearly sorted data 4. Timsort /
Merge: Stable + production-ready 5. Heap Sort: Low memory use needed
O(n2): quadratic (Polynomial algorithm run time). Two loops, one
inside other. Fibonacci sequence. O(n3): cubic. Tree loops, one inside
other two O(2n): exponential. 2 loops one after other O(n!): factorial
-
Data Structures:
Video
-
Arrays: Java Swift are homogeneous [int, int], but python and Js are
heterogeneous [int, string]
-
Constant: Not scale with the input of the function (take the constant
time to get the result). Big O(1)
-
BogoSort: MonkeySort, bad O(n x n!)
Bogo Sort example
selectionSort: O(n2) QuickSort: O(n2), best case O(n log n) MergeSort:
O(n log n)
- linearSearch: O(n) binarySearch: O(log n)
- Algorithms:
-
Golden Rules to solve problems:
-
If the coding problem require search in a O(1), use Set or Map
-
If finding/manipulating/dealing and farthest 'K' element in a
given element 'N', try Heap
-
If the problem has a SORTED Array, List or Matrix, use Two Pointer
or Binary Search
-
If require trying all Permutations and Combinations, use
Backtracking or Breadth First Search
-
If input in the form Tree or Graph, use Tree Traversals or Graph
Traversals called Breadth First Search BFS or Depth First Search
DFS
-
If is with Single Linked List use Two Pointers or Slow/Fast
Pointers
-
If the problem has a recursive solution, use Stack data structure
with a loop
-
If the problem is iterating an array with a Time Complexity of
O(n2) with Space Complexity of O(1), use HashMap/HashSet. It makes
Time Complexity O(n) but Space of O(n)
-
If the problem is iterating an array with a Time Complexity of
O(n2) with Space Complexity of O(1), try sort the array. It makes
Time Complexity O(n log n) but Space of O(1)
-
If the problem is optimize recursive solution, dynamic programming
can be used
-
If the problem has a group of string to manipulation/find/sorting
around substring, Tries or HashMap can be used
-
Coding Patterns
-
Two Pointers: indexes of Array/List. Process two elements at the
same time.
* Array/List sorted and comparison need between its elements.
* Array/List need some certain rearrangement/removal in-place.
- Two Sum II - Input Array is Sorted.
- Container With Most Water.
- Remove duplicate from Sorted Array.
- Next permutations.
- Trapping Rain Water
-
Fast and Slow Pointers: indexes of Array/List. Two pointers
iterate array/list at different speeds.
- Linked List Cycle
- Middle of the Linked List
- Palindrome Linked List
- Happy Number
- Circular Array Loop
Algorithms repository is use to define and implement in different
languages
-
Sliding window 1:48 minute: indexes of Array/List. Process two
elements at the same time.
* Array/List need some certain rearrangement/removal in-place.
- Two Sum II - Input Array is Sorted.
-
Find sum of natural numbers: public int sumNaturalNum(int
n){return n * (n+1)/2}
- MergeSort: O(n log n)
-
linearSearch: O(n)
binarySearch: O(log n)
-
Priority Queue: Data Structure allow find the max/min element in
constant time, support following operations:
1. insert(key)
2. deleteMax/deleteMin: remove key
3. getMax/getMin: get the key.
-
Complete Binary Tree: Is a Binary Tree where all levels are completed
except last level AND last level has a node in such a way that left
side is never empty.
-
Representation of Binary Heap:
1. Is a complete Binary Tree, the values are storage in an array by
traversing the level-order from left to right.
2. The first entry is empty.
3. Calculation of children (k index = 2*k,2*k +1): 1 index = 2,3 --> 2
index = 4,5 --> 3 index = 6,7
3. Calculation of parent (k parent = k/2): 7 index = 3 (3.5) --> 6
index = 3 --> 5 index = 2 (2.5)
Representation of Max Binary Heap:
1. The first entry is empty.
2. The second entry is the max value in the array (or root of the
Binary Tree).
-
Java
-
JIT: Just-In-Time Compiler, for efficiency compile bytecode in
runtime. JIT compile directly for higher speeds. same time.
-
ClassLoader: is a subsystem in JVM, first load the file class.
-
Memory allocation: Java have multiple, five most relevant are:
1. Class Memory
2. Heap Memory
3. Stack Memory
4. Program Counter Memory
5. Native Method stack Memory
-
* Association: relationship that has not ownership over another.
* Copy Constructor: Initialize an object of the same class.
* Marker Interface: is empty Interface, examples: Serializable and
Clonable.
* Java is not completely Object Oriented: Use 8 primitive data
types.
* Wrapper Classes are use to convert primitive to Objects.
* Pointers are eliminated in java.
* Java String Pool: Collections of string in java Heap, java first
search the string in the string pool if not exist created it .
* Exceptions: 1. Compilation 2. Runtime 3. Error.
* If not declared static in a main() method, it throws an run time
exception NoSuchMethodError.
-
* JDK and variants: Combine JRE and Dev tools used to design Java
Apps:
1. JDK Standard Edition 2. JDK Enterprise Edition 3. JDK Micro
Edition
* Access and Type Access specifiers: help JVM to understand the
scope of a variable, method and class, the four access specifiers
are: 1. Public 2. Protected 3. Default 4. Private
* Constructor implicitly return an instance but never a value.
* Dynamic in nature: Java is considered Dynamic in nature because
have run-time information used to resolve object access in
run-time.
* this and super keywords are references to objects keywords, this
refer to current and parent object.
* Method overloading is a type of polymorphism, can by next two of:
1. Vary arguments 2. Vary return-type.
* Static can not be referenced.
* Late Binding: unknown and till the method is called in
run-time.
* Method Dispatch: The method call is executed in run-time.
* Delete is fast in linked list than array because use a complete
memory block use the memory heap for the references.
* Life of 5 states of cycle of thread: 1. New born 2. Run-able 3.
Running 4. Blocked 5. Dead.
* Operator >> is for job the right shifting the sing bits and >>> is
to shift out the zero filled bits.
* Life of 5 states of applet: 1. Initialization 2. Start 3. Stop 4.
Destroy 5. Paint
* Generics: for compile-time safety.
* Externalizable interface: control flow over serialization process.
It incorporate readExternal and writeExternal methods
* Daemon Thread: least priority, run in background in VM and create
with setDaemon() method.
* Enum: Is an Interface, sequential access stored in a
collection.
* finalize method: Garbage Collector call the method finalize()
after collect the object, it is one time.
* super and this should be at the first in the constructor. public
constrctor(){super();this();}
-
* JSP: two types of text: 1. Static Data 2. JSP elements.
* JDBC: Java Data Base Connector, abstraction layer to establish a
connection.
* JSP Directives: Instructions processed by JSP Engine. After JSP
compiled in servlets, Directives used to set page-level
instructions, insert data and specify custom tags libs. Are used
between <%@ %>
* JSP Types of Directives: 1. include: include file and merge the
content with the page. 2. page: define specific attributes in the
JSP page, example: error page and buffer. 3. Taglib: declare a
custom tag library.
* Observer and Observable: Observable maintain a list of observers.
When Observable is updated (extends Observable), invoked the
update() method of EACH observer (implements Observer). The Observer
class, implement the Observable object with the update method.
* Session Manager: Random conversations between client and server. A
string of request and responses, most common is session ID.
* Spring Framework: Is an app framework and inversion of control
container for java. Is conducted to any java application.
* JCA: Java Cryptography Architecture, platform and gives
architecture and API for encryption and decryption.
* JPA: Java Persistence Api, for desktop and web app: 1) Java
Persistence API. 2) Query Language. 3) Java Persistence Criteria
API. 4) Object Mapping Metadata.
* Authentication in Java Servlets: Four different options: 1) Basic
Authentication: Username and password. 2) Form-base authentication:
Login form made for the programmer using HTML. 3) Digest
Authentication: similar to basic but with pass encrypted using hash
formula. 4) Client Certificate Authentication: Each client accessing
send a certificate, it requires SSL protocol.
* Garbage Collector: java 7 and before GC live in PermGen but
replace in Java 8 by Metaspace (also store classes, not in the
heap), GC can reclaim Metaspace.
* statics variables in all versions live in the heap.
* String live in global pool heap (before java 7 in the PermGen,
cause OutOfMemoryError), in heap the GC can clean the string like
other object.
* RMI: Remote Method Invocation: API allow to call remote methods
like local, layers: 1) Application layer: Client and server code. 2)
Stub & Skeleton layer: Stub client and Skeleton server. 3) Remote
Reference layer: Handle reference to remote object. 4) Transport
layer: Use TCP/IP, manage the connection.
* DGC Dinamic Garbage Collectors (RMI use DGC):
stream groupingBy.
-
Spring
-
@Bean : Are initialize, configure and managed by core container. Are
initialize and destroyed with the spring container.
* Non-final and non-private.
@Component: Class-level annotation to mark as Spring component,
Constructor-dependency injection is automatically using @Autowired
(Optional if only one constructor).
@Repository, @Service and @Controller are meta-annotation and allow
further re-fine components to support general architecture
principles.
* Bean-scope refer to the live-cycle of beans: there are 6 and the
Default is singleton: 1) Singleton. 2)Prototype: each time. 3)
Request: valid in web context for single http request. 4) Session:
valid for http session. 5) Application: for servlet context. 6)
Websocket
* @PrototypeScope or @Scope("prototype")
* Specials spring beans: 1) Environment (dev, test, production). 2)
Profile("cloud") can be active declarative in yaml-xml or
programmatically
* applicationContext.refresh() : Spring refresh the own context
* @PropertySource("classpath:database.properties") : Load a file in
the folder resources with the name database.properties
* @Value("$jdbc.url") annotation inject value in a variable from
properties. Also can be use with dynamic expression.
-
DI: Dependency Injection, there are 4 ways: 1) Constructor. 2)
Field, direct inject into field declaration (warning for testing) 3)
Method, like a normal void method but using @Autowired in the method
Spring know the classes passed by parameters are beans. 4) Setter,
follow the java naming convention to setAccount(Account acc)
* @Qualifier("name1") : Used to name beans and can injected using
the name1
* @Primary to specify the primary bean and when inject just need to
inject in the constructor, automatically know which bean call.
-
Best practices: 1) Split configuration classes. 2) Import
configuration: only the needed configuration.
* Spring boot: develop spring base app with very less or not
configurations. Also provide starters. Auto configure based in the
defined starters
* Why spring: 1) Standalone apps. 2) Embded server. 3) starters. 4)
Auto configuration. 5) production ready feature. 6) No XML
configuration
-
application.properties: spring.profile.active=dev,test and create a
file application-dev.properties
* The order of active profile matter: the last file override the
duplicate properties
* Other way to set properties is using the method
setDefaultProperties(Collection.singletonMap("spring.profile.active","dev"))
Using the annotation in @Bean @Profile("dev") indicate available
only for dev profile. This annotation can apply for class level.
-
REST Representational State Transfer
REST defined by Roy Field in 2000 Doctoral dissertation
Client-server Architecture
Stateless
Cache able
Layer System
Code on Demand(optional)
Uniform Interface: 1) Identification of resources. 2) Manipulation
of resources through these representations. 3) Selft-descriptive
messages. 4) Hipermedia As The Engine Of Application State HATEOS
* Should in plural nouns and one send id: GET accounts/1
* If nested resource, should be: GET accounts/1/payments/56
* GET. PUT. POST. DELETE. PATCH: To update only one part of the
entity. OPTIONS: Return the http methods that server support. HEAD:
Similar to GET but only respond the header response.
* 1XX Informational, 2XX success, 3XX Redirection, 4XX Client Error,
5XX Server Error.
200 OK, 201 CREATED, 204 NO CONTENT. 304 NOT MODIFIED (If the entity
is the same). 400 BAD REQUEST, 401 UNAUTHORIZED, 403 FORBIDDEN (User
Not permission), 404 NOT FOUND. 500 INTERNAL SERVER ERROR, 503
SERVICE UNAVAILABLE
* @ResponseStatus return the code if not error throw.
* @JsonProperty("c-product") case-sensitive and specify the name in
the json body.
* Java 14 introduce record: default fields are final and add
automatically the getters and setters, finalize in Java 16 -->
public record ClassName(String name, String phone) {}.
* JPA : @Table(name="my_table"): to give a different name.
@Id @GeneratedValue(strategy=SEQUENCE): unique and not updatable
@Column(unique=true, updatable=false): unique and not updatable
* @Query JPA support JPQL Java Persistence Query Language: custom
queries. In interface extends JpaRepository create the methods
* Example: List findAllByFirstNameLike(String firstName)
string equal
* Example: List findAllByFirstNameConaining() any string
could be part of the string
* First class: @OneToOne(mappedBy="student",cascade=CascadeType.ALL)
Second class: @OneToOne @JoinColumn(name="student_id"): Create a
column by the one to one relation
* @JsonManagedReference : Put in @OneToMany field to prevent cycle
in the table references
* @JsonBackReference : Put in @ManyToOne field to prevent cycle in
the table references
* Organize folders: 1) By Features: customers and inside enter all
classes related. 2) By Layers: create layers folders and every layer
have all the classes related to the layer. 3) By domain DDD
(screaming architecture): create business and inside create the
layers
* Validation from starter jakarta.validation: @Valid : To validate
in the controller to perform the validation. In the record put the
annotation to validate, for example @NotEmpty(message="message")
* ExceptionHandler(MethodArgumentNotValidException.class) to handle
the exceptions in a method, return ResponseEntity
-
Mockito: use the annotations @Mock, @InjectMocks and in the
@BeforeEach use MockitoAnnotations.openMocks(this)
Mockito.when(exampleMapper.mapper(dto)).thenReturn(newMapDTO)
Test multiples calls Mockito.verify(Class,
Mockito.timeout(2)).tomethod(dto) to verify the method take 2
seconds to execute
* @SequenceGenerator(name="my_sequence",
sequence_name="my_sequence", initialValue=1, allocationSize=1): To
create the sequence if not exist
* @TableGenerator(name="my_table_gen", table="table_name",
pkColumnName="id_name", valueColumnName="id_value",
allocationSize=1): To create the table if not exist
* @Column(name="f_name", unique=true, nullable=false, length=50) to
set attributes for the column field.
* @Entity can stay in 4 states : 1) Transient: Not in the session
(save, persist, saveOrUpdate, update). 2) Persistent: In the session
(detach, close, clear, evict)(save, saveOrUpdate, merge, lock). 3)
Detached: Removed from the session (delete). 4) Removed.
* @EqualsAndHashCode(callSuper=true) and @SuperBuilder used in
public class Video extends Resource : to implement inheritance
* @Polymorphism(type=PolymorphismType.EXPLICIT) : used to load the
children for extends class
* @Embeddable to declare an embedded entity and use @EmbeddedId for
the field to declare the id and in class declaration implements
Serializable
* It is possible to have an entity extend in many entities with
@Embeddable annotation
* Query creations: it is possible to create queries using the name
convention, for examples: 1) findBy[Property] 2) countAllBy[number
Property] 3) deleteAllBy[Property].
* Important, Spring JPA can return the type defined in the method:
List findByFirstNameAndLastName(String fn, String ln)
record, mapping, test
-
Sub-types of Inversion of Control : Instead code calling framework,
the framework call the code.
Here are the main sub-types or patterns of IoC:
1. Dependency Injection (DI) : The framework injects dependencies
into your class (constructor, setter, or field). Most common form of
IoC.
2. Service Locator : The object asks a central registry (service
locator) for its dependencies. The object still **fetches**, but the
**creation logic is centralized**.
3. Event-based IoC / Observer : Objects react to **events
triggered** by other components or the framework (common in GUI
frameworks).
4. Template Method Pattern** : A base class defines a **fixed
control flow** and lets subclasses **override specific steps**.
5. Strategy Pattern** : The behavior (algorithm) is **injected at
runtime** — behavior is **decoupled from context**.
6. Aspect-Oriented Programming (AOP)** : Cross-cutting concerns
(e.g., logging, security) are **injected** into objects at runtime
by the framework.
-
@SpringBootApplication is an alias for the next 3 annotation:
1. @Configuration : Mark the class as source definition.
2. @ComponentScan : Find an initialize those beans, where to find
the packages.
3. @EnableAutoConfiguration : Auto configure all base in the
class-path.
Spring Boot Actuator: Production ready features like:
1. Health checks : (/actuator/health).
2. Metrics checks : (/actuator/metrics).
3. Info checks : (/actuator/info).
4. Thread dumps, env variables, beans and more.
Exceptions: the best way is use @ControllerAdvice with
@ExceptionHandler in a class for Exceptions.
Externalized configuration: support properties from application.xml
or application.yaml, Command-line args, Environment variables,
configured server (Spring Cloud Config) for flexible configuration
without modifying code.
-
Node
-
* Node: Phases of Event loop:
1) Timers: scheduled by timers setTimeout() and setInterval(). 2)
Pending Callbacks: System level operations like TCP Errors, used by
low-level APIs and native bindings. 3) Idle/Prepare(internal):
Internal use, prepare poll for I/O. 4) Poll: I/O events, Wait here
if not timers are due. 5) Check: setImmediate(), after I/O. 6) Close
Callbacks: close resources, eg server.close() socket.close().
Between phases, runs: 1) process.nexTick() callbacks and 2) Micro
tasks
-
(Promises.then and queueMicrotask)
* Node multi-process using cluster module
* Node child_process module provides: 1) spawn: for long process,
streams 2) exec: memory process, < 1MB
* Node reactor patter: Event loop delegate to libuv library for
handling I/O events asynchronously, Node work under the hood