MenuPage

Thursday, March 20, 2025

test

 import java.util.ArrayList;

import java.util.List;

import java.util.concurrent.CompletableFuture;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;


class Main {

    Car car;

    String[] cars = {"Car1", "Car2", "Car3", "Car4", "Car5"};


    Main() {

        car = new Car();

    }


    void main() throws Exception {

        List<CompletableFuture<Boolean>> futures = new ArrayList<>();

        List<CompletableFuture<Void>> dependentFutures = new ArrayList<>(); // To track dependent actions


        for (String carName : cars) {

            CompletableFuture<Boolean> dbUpdateFuture = car.process(carName, futures);

            dependentFutures.add(dbUpdateFuture.thenAccept(success -> doSomethingElseCode(carName, success))); // Call doSomethingElseCode

        }


        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();

        CompletableFuture.allOf(dependentFutures.toArray(new CompletableFuture[0])).join(); // Wait for dependent actions


        boolean overallSuccess = futures.stream()

                .allMatch(future -> {

                    try {

                        return future.get();

                    } catch (Exception e) {

                        return false;

                    }

                });


        if (!overallSuccess) {

            throw new Exception("One or more updateInDatabase calls failed.");

        }


        System.out.println("All processing completed successfully.");

    }


    void doSomethingElseCode(String carName, boolean success) {

        if(success){

            System.out.println("Doing something else with: " + carName + " (after successful DB update)");

            // ... your code here ...

        } else {

            System.out.println("Doing something else with: " + carName + " (DB update failed)");

        }

    }


    // ... (rest of the Main class and other classes remain the same) ...

}

Monday, June 10, 2024

Machine learning basics starts

 Starting your journey into machine learning (ML) can be exciting and rewarding. Here’s a step-by-step guide to help you begin from the very basics:


### Step 1: Understand the Fundamentals

1. **Basic Mathematics and Statistics**:

   - Linear Algebra: Matrices, vectors, and operations.

   - Calculus: Derivatives and integrals.

   - Probability: Basic concepts and distributions.

   - Statistics: Mean, median, mode, standard deviation, and hypothesis testing.


2. **Programming**:

   - Learn Python: Python is the most commonly used language in ML due to its simplicity and the availability of libraries.

   - Get comfortable with libraries such as NumPy, pandas, and matplotlib.


### Step 2: Learn the Basics of Machine Learning

1. **Introduction to ML Concepts**:

   - Understand what ML is and the difference between supervised, unsupervised, and reinforcement learning.

   - Learn about common algorithms like linear regression, logistic regression, decision trees, k-nearest neighbors, and k-means clustering.


2. **Online Courses and Tutorials**:

   - **Coursera**: "Machine Learning" by Andrew Ng.

   - **edX**: "Introduction to Artificial Intelligence (AI)" by IBM.

   - **Kaggle**: Various free courses on ML and data science.


### Step 3: Hands-On Practice

1. **Basic Projects**:

   - Start with simple projects like predicting house prices, classifying emails (spam vs. non-spam), or recognizing handwritten digits (MNIST dataset).


2. **Kaggle Competitions**:

   - Participate in beginner-friendly competitions on Kaggle to apply what you've learned and see how others approach the same problems.


### Step 4: Deepen Your Knowledge

1. **Advanced Topics**:

   - Learn about advanced algorithms like support vector machines (SVM), ensemble methods (random forests, gradient boosting), and neural networks.

   - Study deep learning frameworks like TensorFlow and PyTorch.


2. **Specialized Courses**:

   - **Deep Learning Specialization** by Andrew Ng on Coursera.

   - **Fast.ai**: Practical deep learning courses.


### Step 5: Build and Deploy Models

1. **Model Evaluation and Tuning**:

   - Learn about cross-validation, hyperparameter tuning, and model evaluation metrics (accuracy, precision, recall, F1 score).


2. **Deployment**:

   - Understand how to deploy models using frameworks like Flask, Docker, and cloud platforms like AWS, Google Cloud, or Azure.


### Step 6: Explore Real-World Applications

1. **Case Studies**:

   - Study how ML is used in different industries (healthcare, finance, marketing, etc.).


2. **Research Papers and Blogs**:

   - Read research papers to stay updated with the latest advancements.

   - Follow blogs and YouTube channels from experts in the field.


### Suggested Resources:

- **Books**:

  - "Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow" by Aurélien Géron.

  - "Pattern Recognition and Machine Learning" by Christopher Bishop.

  - "Deep Learning" by Ian Goodfellow, Yoshua Bengio, and Aaron Courville.


- **Websites**:

  - [Machine Learning Mastery](https://machinelearningmastery.com/)

  - [Towards Data Science](https://towardsdatascience.com/)

  - [Kaggle](https://www.kaggle.com/)


### Consistency is Key

- **Practice Regularly**: Dedicate time every day or week to learning and practicing ML.

- **Join Communities**: Engage with online communities like Stack Overflow, Reddit, and GitHub to ask questions, share knowledge, and collaborate on projects.


By following these steps and utilizing these resources, you'll build a solid foundation in machine learning and be well on your way to mastering this fascinating field.

Monday, June 3, 2024

Different types of asset class

 Certainly! Here is a comprehensive list of different types of asset classes commonly recognized in the investment world:


### Traditional Asset Classes

1. **Equities (Stocks)**

   - Common stocks

   - Preferred stocks


2. **Fixed Income (Bonds)**

   - Government bonds

   - Corporate bonds

   - Municipal bonds

   - Treasury bonds

   - High-yield (junk) bonds


3. **Cash and Cash Equivalents**

   - Treasury bills

   - Money market funds

   - Certificates of deposit (CDs)

   - Commercial paper


### Real Assets

4. **Real Estate**

   - Residential properties

   - Commercial properties

   - Industrial properties

   - Real Estate Investment Trusts (REITs)


5. **Commodities**

   - Precious metals (e.g., gold, silver)

   - Energy (e.g., oil, natural gas)

   - Agricultural products (e.g., wheat, corn)

   - Industrial metals (e.g., copper, aluminum)


### Alternative Investments

6. **Private Equity**

   - Venture capital

   - Buyout funds

   - Growth capital


7. **Hedge Funds**

   - Various strategies (e.g., long/short equity, market neutral, event-driven)


8. **Infrastructure**

   - Transportation (e.g., toll roads, airports)

   - Utilities (e.g., water, electricity)

   - Communication (e.g., cell towers, fiber optics)


9. **Collectibles**

   - Art

   - Antiques

   - Rare coins

   - Stamps

   - Wine


10. **Derivatives**

    - Options

    - Futures

    - Swaps

    - Forwards


11. **Cryptocurrencies**

    - Bitcoin

    - Ethereum

    - Ripple

    - Litecoin


### Other Financial Instruments

12. **Mutual Funds**

    - Equity mutual funds

    - Bond mutual funds

    - Money market funds

    - Hybrid funds


13. **Exchange-Traded Funds (ETFs)**

    - Equity ETFs

    - Bond ETFs

    - Commodity ETFs

    - Sector ETFs


14. **Annuities**

    - Fixed annuities

    - Variable annuities

    - Indexed annuities


15. **Insurance Products**

    - Life insurance

    - Health insurance

    - Property and casualty insurance


### Specialized Asset Classes

16. **Sovereign Wealth Funds**

    - Investments managed by a national government


17. **Foreign Exchange (Forex)**

    - Trading of currencies


18. **Carbon Credits**

    - Certificates representing the right to emit a certain amount of carbon dioxide or other greenhouse gases


### Emerging and Niche Asset Classes

19. **Intellectual Property (IP)**

    - Patents

    - Trademarks

    - Copyrights


20. **Peer-to-Peer Lending (P2P)**

    - Loans made directly between individuals through online platforms


21. **Royalties**

    - Payments received for the ongoing use of an asset, such as mineral rights or music royalties


22. **Litigation Finance**

    - Investment in legal cases in exchange for a portion of the proceeds from a favorable judgment or settlement


### Sustainable Investments

23. **Environmental, Social, and Governance (ESG) Investments**

    - Investments in companies or projects that meet certain environmental, social, and governance criteria


By diversifying across these various asset classes, investors can tailor their portfolios to their risk tolerance, investment goals, and time horizons, thereby optimizing potential returns while managing risk.

Swap

 In finance, a swap is a derivative contract through which two parties exchange financial instruments, typically cash flows. These cash flows are often referred to as "legs" of the swap. Understanding the concepts of the "financial leg" and "exposure leg" is crucial for grasping how swaps function.

Financial Leg

The financial leg of a swap refers to the cash flows that are determined by a specific financial index or rate. This could be:

  1. Fixed Rate Leg: Payments are made based on a fixed interest rate. For example, one party agrees to pay the other a fixed interest rate on a notional principal amount.
  2. Floating Rate Leg: Payments are made based on a variable interest rate, such as LIBOR (London Interbank Offered Rate) or another reference rate. The rate is reset periodically according to the terms of the swap agreement.

Exposure Leg

The exposure leg of a swap is the leg that exposes the parties to the underlying risk they wish to hedge or speculate on. This leg's value or cash flows are linked to the performance of the underlying asset, index, or rate that the swap is based on. For instance:

  1. Interest Rate Swap: One leg is typically tied to a floating interest rate (exposure to interest rate changes), and the other to a fixed interest rate (providing certainty).
  2. Currency Swap: One leg is tied to the cash flows in one currency, while the other leg is tied to another currency, exposing parties to exchange rate risk.
  3. Commodity Swap: One leg is linked to the price of a commodity (e.g., oil or gold), providing exposure to fluctuations in commodity prices.

Swap Example

Consider an interest rate swap where Party A pays a fixed rate and receives a floating rate based on LIBOR from Party B:

  • Financial Leg (Fixed Leg): Party A pays a fixed interest rate to Party B on a notional principal.
  • Exposure Leg (Floating Leg): Party A receives payments from Party B based on the floating LIBOR rate.

In this example:

  • Party A's exposure: The floating rate leg exposes Party A to changes in LIBOR. If LIBOR rises, Party A will receive higher payments, and if it falls, they will receive lower payments.
  • Party B's exposure: The fixed rate leg exposes Party B to the risk of fixed payments regardless of LIBOR movements.

Key Points

  • Objective: Swaps are often used for hedging purposes to manage risk or for speculative purposes to take advantage of anticipated changes in the underlying rates or prices.
  • Risk Management: By exchanging these legs, parties can achieve desired financial outcomes, such as locking in fixed rates, gaining exposure to variable rates, or hedging against currency or commodity price fluctuations.

Understanding these concepts helps in recognizing how swaps can be utilized for financial strategy, risk management, and speculative purposes in various financial markets.

Tuesday, February 28, 2023

 As you know not everything in Java is an object. There are a few groups of data types (also known as primitive types) that will be used quite often in your programming. For performance reasons, the designers of the Java language decided to include these primitive types.

Creating an object using new isn't very efficient because new will place objects on the heap. This approach would be very costly for small and simple variables. Instead of creating variables using new, Java can use primitive types to create automatic variables that are not referenced. The variables hold the value, and it's placed on the stack so it's much more efficient.

Java determines the size of each primitive type. These sizes do not change from one machine architecture to another (as in most other languages). This is one of the critical features of the language that makes Java so portable.

Take note that all numeric types are signed. (No unsigned types).

Finally, notice that each primitive data type also has a "wrapper" class defined for it. This means that you can create a "nonprimitive object" (using the wrapper class) on the heap (just like any other object) to represent the particular primitive type.

For example:
int i = 5;
Integer I = new Integer(i);
OR
Integer I = new Integer(5);



Data Types and Data Structures

Primitive TypeSizeMinimum ValueMaximum ValueWrapper Type
char  16-bit    Unicode 0  Unicode 216-1  Character
byte  8-bit    -128  +127  Byte
short  16-bit    -215
(-32,768)
  +215-1
(32,767)
  Short
int  32-bit    -231
(-2,147,483,648)
  +231-1
(2,147,483,647)
  Integer
long  64-bit    -263
(-9,223,372,036,854,775,808)
  +263-1
(9,223,372,036,854,775,807)
  Long
float  32-bit    32-bit IEEE 754 floating-point numbers  Float
double  64-bit    64-bit IEEE 754 floating-point numbers  Double
boolean  1-bit    true or false  Boolean
void  -----    -----    -----    Void

 

Monday, August 20, 2018

Singleton Design pattern

The Singleton pattern is deceptively simple, even and especially for Java developers, but it presents a number of pitfalls for the unwary Java developer which make it hard to implement properly. In this article, I’ll talk about several ways to implement the Singleton pattern in Java, and leave it to you to decide which one is best suited for your circumstance depending on your requirement.
With the Singleton design pattern you can:
  • Ensure that only one instance of a class is created
  • Provide a global point of access to the object
  • Allow multiple instances in the future without affecting a singleton class’s clients

The classic Singleton pattern1

In Design Patterns: Elements of Reusable Object-Oriented Software, the GoF describe the Singleton pattern like this:

Ensure a class has only one instance, and provide a global point of access to it.
public class ClassicSingleton {
2     private static ClassicSingleton instance = null;
3 
4     private ClassicSingleton() {
5         // Exists only to defeat instantiation.
6     }
7 
8     public static ClassicSingleton getInstance() {
9         if (instance == null) {
10             instance = new ClassicSingleton();
11         }
12         return instance;
13     }
14 }


Above code is easy to understand, the ClassicSingleton hold a static reference to the single instance and returns that reference from the static getInstance() method.
There are several interesting points concerning the ClassicSingleton class.
 1 > ClassicSingleton employs a technique known as lazy instantiation to create the singleton; as a result, the singleton instance is not created until the getInstance() method is called for the first time. This technique ensures that singleton instances are created only when needed.

2> It’s possible to have multiple singleton instances if classes loaded by different Classloaders access a singleton. That scenario is not so far-fetched; for example, some servlet containers use distinct Classloaders for each servlet, so if two servlets access a singleton, they will each have their own instance.

3> If ClassicSingleton implements the java.io.Serializableinterface, the class’s instances can be serialized and deserialized. However, if you serialize a singleton object and subsequently deserialize that object more than once, you will have multiple singleton instances.

4> ClassicSingleton class is not thread-safe. If two threads—we’ll call them Thread 1 and Thread 2—call ClassicSingleton.getInstance() at the same time, two ClassicSingleton instances can be created if Thread 1 is preempted just after it enters the if block and control is subsequently given to Thread 2.

5> A privileged client can invoke the private constructor reflectively with the aid of the AccessibleObject.setAccessible method. If you need to defend against this attack, modify the constructor to make it throw an exception if it’s asked to create a second instance.
As you can see from the preceding discussion, although the Singleton pattern is one of the simplest design patterns, implementing it in Java is anything but simple. The rest of this article addresses Java-specific considerations for the Singleton pattern.

Synchronization for multithreading considerations

Making Singleton thread-safe is easy-just synchronize the getInstance() method:



1 public class Singleton {
2     private static Singleton instance = null;
3 
4     private Singleton() {
5         // Exists only to defeat instantiation.
6     }
7 
8     public synchronized static Singleton getInstance() {
9         if (instance == null) {
10             instance = new Singleton();
11         }
12         return instance;
13     } 


However, the astute reader may realize that the getInstance() method only needs to be synchronized the first time it is called. Because synchronization is very expensive performance-wise, perhaps we can introduce a performance enhancement that only synchronizes the singleton assignment in getInstance().

A performance enhancement

In search of a performance enhancement, you might choose to rewrite the getInstance()method like this:


1 // CAUTION, BUGS AHEAD
2 public static Singleton getInstance() {
3    if(singleton == null) {
4       synchronized(Singleton.class) { 
5          singleton = new Singleton();
6       }
7    }
8    return singleton; 

Instead of synchronizing the entire method, the preceding code fragment only synchronizes the critical code. However, the preceding code fragment is not thread-safe. Consider the following scenario: Thread 1 enters the synchronized block, and, before it can assign the singleton member variable, the thread is preempted. Subsequently, another thread can enter the if block. The second thread will wait for the first thread to finish, but we will still wind up with two distinct singleton instances. Is there a way to fix this problem? Read on.

Double-checked locking

Double-checked locking is a technique that, at first glance, appears to make lazy instantiation thread-safe. That technique is illustrated in the following code fragment:

1 // CAUTION, BUGS AHEAD
2 public static Singleton getInstance() {
3   if(singleton == null) {
4      synchronized(Singleton.class) {
5        if(singleton == null) {
6          singleton = new Singleton();
7        }
8     }
9   }
10   return singleton; 
11

What happens if two threads simultaneously access getInstance()? Imagine Thread 1 enters the synchronized block and is preempted. Subsequently, a second thread enters the if block. When Thread 1 exits the synchronized block, Thread 2 makes a second check to see if the singleton instance is still null. Since Thread 1 set the singleton member variable, Thread 2’s second check will fail, and a second singleton will not be created. Or so it seems.
Unfortunately, double-checked locking is not guaranteed to work because the compiler is free to assign a value to the singleton member variable before the singleton’s constructor is called. If that happens, Thread 1 can be preempted after the singleton reference has been assigned, but before the singleton is initialized, so Thread 2 can return a reference to an uninitialized singleton instance.
Since double-checked locking is not guaranteed to work, you must synchronize the entire getInstance() method. However, another alternative is simple, fast, and thread-safe.

An alternative thread-safe singleton implementation


1 public class Singleton {
2    public final static Singleton INSTANCE = new Singleton();
3    private Singleton() {
4        // Exists only to defeat instantiation.
5    }
6 }
The preceding singleton implementation is thread-safe because static member variables created when declared are guaranteed to be created the first time they are accessed. You get a thread-safe implementation that automatically employs lazy instantiation, until the class file get loaded into memory, their is no instance instanciated at all.


Of course, like nearly everything else, the preceding singleton is a compromise; if you use that implementation, you can’t change your mind and allow multiple singleton instances later on. With a more conservative singleton implementation, instances are obtained through a getInstance() method, and you can change those methods to return a unique instance or one of hundreds. You can’t do the same with a public static member variable.
1 public class Singleton {
2    private final static Singleton INSTANCE = new Singleton();
3    private Singleton() {
4        // Exists only to defeat instantiation.
5    }
6 
7    public static Singleton getInstance() {
8        return INSTANCE;
9    }
10 }

Leveraging volatile to change Java Memory Model

We can recheck the instance again in synchronized block to ensure that only one instance of the Singleton object be instantiated, shown as below code:
1 public class LazySingleton {
2     private static volatile LazySingleton instance;
3 
4     // private constructor
5     private LazySingleton() {
6     }
7 
8     public static LazySingleton getInstance() {
9         if (instance == null) {
10             synchronized (LazySingleton.class) {
11                 // Double check
12                 if (instance == null) {
13                     instance = new LazySingleton();
14                 }
15             }
16         }
17         return instance;
18     }
19 }
Please ensure to use volatile keyword with instance variable otherwise you can run into out of order write error scenario, where reference of instance is returned before actually the object is constructed i.e. JVM has only allocated the memory and constructor code is still not executed. In this case, your other thread, which refer to uninitialized object may throw null pointer exception and can even crash the whole application.
Although above code is the correct way to implement Singleton pattern, this is not recommended since it introduce extra complexity of code, which may introduce subtle bugs.

Classloaders

Because multiple classloaders are commonly used in many situations—including servlet containers—you can wind up with multiple singleton instances no matter how carefully you’ve implemented your singleton classes. If you want to make sure the same classloader loads your singletons, you must specify the classloader yourself; for example:
1 private static Class getClass(String classname) throws ClassNotFoundException {
2     ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
3     if(classLoader == null)
4         classLoader = Singleton.class.getClassLoader();
5         return (classLoader.loadClass(classname));
6     }
7 }
The preceding method tries to associate the classloader with the current thread; if that classloader is null, the method uses the same classloader that loaded a singleton base class. The preceding method can be used instead of Class.forName().

Serialization2

If you serialize a singleton and then deserialize it twice, you will have two instances of your singleton, unless you implement the readResolve() method, like this:
1 public class Singleton implements java.io.Serializable {
2     private static final long serialVersionUID = 1L;
3     public static Singleton INSTANCE = new Singleton();
4 
5     private Singleton() {
6         // Exists only to thwart instantiation.
7     }
8 
9     private Object readResolve() {
10         return INSTANCE;
11     }
12 }
The previous singleton implementation returns the lone singleton instance from the readResolve() method; therefore, whenever the Singleton class is deserialized, it will return the same singleton instance. Don’t forget to add serial version id in this case, or you will get an exception during de-serialise process.

Bill Pugh solution3

Bill Pugh was main force behind java memory model changes. His principle “Initialization-on-demand holder idiom” also uses static block but in different way. It suggest to use static inner class:
1 public class BillPughSingleton {
2     private BillPughSingleton() {
3     }
4 
5     private static class LazyHolder {
6         private static final BillPughSingleton INSTANCE = new BillPughSingleton();
7     }
8 
9     public static BillPughSingleton getInstance() {
10         return LazyHolder.INSTANCE;
11     }
12 }
As you can see, until we need an instance, the LazyHolder class will not be initialized until required and you can still use other static members of BillPughSingleton class. This is the solution, i will recommend to use. I also use it in my all projects.

Using Enum

As of release 1.5, there is a another approach to implementing singletons. which provide implicit support for thread safety and only one instance is guaranteed. This is also a good way to have singleton with minimum effort. Simply make an enum type with one element:
1 // Enum singleton - the preferred approach
2 public enum LazyEnumSingleton {
3     INSTANCE;
4     public void otherMethods() { System.out.println("Other methods go"); }
5 }
This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton. JVM does the lazy-loading in a thread-safe manner. That’s why using this kind of lazy class loading is the preferred method—the JVM handles all the synchronization. We can see that with below little example code, try run it your self:
1 public class LazyEnumSingletonExample {
2     public static void main(String[] args) throws InterruptedException {
3         System.out.println("Accessing enum for the first time.");
4         LazyEnumSingleton lazy = LazyEnumSingleton.INSTANCE;
5         System.out.println("Done.");
6     }
7 }
8 
9 enum LazyEnumSingleton {
10     INSTANCE;
11 
12     static {
13         System.out.println("Initialize in process...");
14     }
15 }
Output of the code:
Accessing enum for the first time.
Initialize in process...
Done.
In Java, enum can hold state, which makes the single-element enum type the perfect condidate for Singleton pattern, see below code:
1 enum LazyEnumSingletonWithState {
2     INSTANCE("State") {
3 
4         @Override
5         public String toOverwrittenOps(String str) {
6             return str + this.state;
7         }
8     };
9 
10     private String state;
11 
12     private LazyEnumSingletonWithState(String state) {
13         this.state = state;
14     }
15 
16     public String otherOps(String arg) {
17         return arg + state;
18     }
19 
20     @Override
21     public String toString() {
22         return this.state;
23     }
24 
25     public abstract String toOverwrittenOps(String str);
26 }

Preventing privileged clients

As we mentioned before, single pattern can be broken with reflection, as below code shown:
1 public static void main(String[] args) throws Exception {
2     Singleton s1 = Singleton.getInstance();
3     Class clazz = Singleton.class;
4     Constructor cons = clazz.getDeclaredConstructor();
5     cons.setAccessible(true);
6     // Another instance can be instantiated now.
7     Singleton s2 = (Singleton) cons.newInstance();
8 }
It’s easy to get over this issue:
1 public class PrivilegedSingleton {
2     private static final PrivilegedSingleton INSTANCE = new PrivilegedSingleton();
3 
4     private PrivilegedSingleton() {
5 
6         // Check if we already have an instance
7         if (INSTANCE != null) {
8             throw new IllegalStateException("Singleton instance already created.");
9         }
10     }
11 
12     public static PrivilegedSingleton getInstance() {
13         return INSTANCE;
14     }
15 }
Sometimes, your IDE may remind you that the INSTANCE variable will never be null, don’t rely on that, IDE can make mistake too.



PS. copied from http://codethoughts.info/java/2014/04/07/singleton-pattern-in-java/ 

test

 import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutorServi...