Friday 16 February 2024

configuration-driven template in vue js

1. It's easier to read configuration


Reading code is complicated because you have to figure out what the logic is doing, but configuration is very straightforward to understand.


2. Less logic means less bugs


The config above is just a boring array with some objects. It's pretty simple, so it's unlikely that bugs would come from there.

3. Dynamic components are more flexible


Because we've made this menu component dynamically render out the different menu items, we gain tremendous flexibility.

 


Thursday 15 February 2024

JavaScript Sets New Helper Function Comming soon

const languages = new Set(["JavaScript","TypeScript","HTML","JavaScript"]);

languages.size;

// => 3


languages.add("JavaScript");

languages.add("CSS");

languages.size;

// => 4
You can add more elements to the Set with the add function.
Adding an element that is already in the Set doesn't do anything.


languages.delete("TypeScript");

languages.size;

// => 3


languages.has("JavaScript");

// => true

languages.has("TypeScript");

// => false


languages.forEach(element => console.log(element));

// "JavaScript"

// "HTML"

// "CSS"

Set.prototype.union(other)


A union of sets is a set that contains all the elements present in
either set.

const frontEndLanguages = new Set(["JavaScript", "HTML", "CSS"]);

const backEndLanguages = new Set(["Python", "Java", "JavaScript"]);

const allLanguages = frontEndLanguages.union(backEndLanguages);

// => Set {"JavaScript", "HTML", "CSS", "Python", "Java"}
In this example, all the languages from the first two sets are in
the third set.As with other methods that add elements to the Set,
duplicates are removed.



This is the equivalent of a SQL FULL OUTER JOIN between two tables.


Set.prototype.intersection(other)
An intersection is a set that contains all the elements that are
present within both sets.

const frontEndLanguages = new Set(["JavaScript", "HTML", "CSS"]);

const backEndLanguages = new Set(["Python", "Java", "JavaScript"]);

const frontAndBackEnd = frontEndLanguages.intersection(backEndLanguages);

// => Set {"JavaScript"}
"JavaScript" is the only element present in both the sets here.



An intersection is like an INNER JOIN.



Set.prototype.difference(other)
The difference between the set you are working with and another
set is all the elements present in the first set and not present
in the second set.

const frontEndLanguages = new Set(["JavaScript", "HTML", "CSS"]);

const backEndLanguages = new Set(["Python", "Java", "JavaScript"]);

const onlyFrontEnd = frontEndLanguages.difference(backEndLanguages);

// => Set {"HTML", "CSS"}

const onlyBackEnd = backEndLanguages.difference(frontEndLanguages);

// => Set {"Python", "Java"}
In finding the difference between sets, it matters which set you call
the function on and which is the argument. In the example above,
removing the back-end languages from the front-end languages results in
"JavaScript" being removed and returning "HTML" and "CSS" in the
resultant set. Whereas removing the front-end languages from the
back-end languages still results in "JavaScript" being removed,
and returns "Python" and "Java".


A difference is like performing a LEFT JOIN.



Set.prototype.symmetricDifference(other)

The symmetric difference between two sets is a set that contains all
the elements that are in one of the two sets, but not both.

const frontEndLanguages = new Set(["JavaScript", "HTML", "CSS"]);

const backEndLanguages = new Set(["Python", "Java", "JavaScript"]);

const onlyFrontEnd = frontEndLanguages.symmetricDifference(backEndLanguages);

// => Set {"HTML", "CSS", "Python", "Java"}

const onlyBackEnd = backEndLanguages.symmetricDifference(frontEndLanguages);

// => Set {"Python", "Java", "HTML", "CSS"}
In this case, the elements in the resultant sets are the same,
but note that the order is different.Set order is determined by the order
the elements are added to the set and the set on which the
function is performed will have its elements added first.



A symmetric difference is like a FULL OUTER JOIN excluding any elements
that are in both tables.




Tuesday 2 January 2024

New control flow for forLoop and empty in Angular 17

 


import {CommonModule} from '@angular/common';
import {Component} from '@angular/core';

@Component({
selector: 'app-root',
imports: [CommonModule],
template: `
Welcome to Angular-17!
<!-- new control flow for forLoop -->
<!-- new control flow to handle if, else if and else -->

@if(userInfo.isLoggedIn) {
<div>Logged-in</div>
} @else if(userInfo.isAdmin) {
<div>Admin</div>
} @else {
<div>Please Login</div>
}
@for (course of courses; track course) {
<div>{{course | json}}</div>
==================================
} @empty {
<div>No Courses found...</div>
}
`,
standalone: true,
})
export class AppComponent {

isLoading = false;
userInfo = {
isLoggedIn:true,
isAdmin:false
}
courses = [
{ id: 'r18', name: 'React + Redux'},
{ id: 'A17', name: 'Angular + NGRX'}
];

}

Wednesday 29 November 2023

How to Export HTML to Image in Angular Component


# How to Export HTML to Image in Angular Component

As a web developer, you may encounter scenarios where you need to export the content of an HTML element to an image. In this tutorial, we will explore how to achieve this using the `html2canvas` library in an Angular component.

## Step 1: Install the html2canvas Package

Firstly, install the `html2canvas` package using npm:

```bash
npm install html2canvas --save
```

## Step 2: Import Required Modules

In your Angular component file, import the necessary modules:

import { Component, OnInit, OnDestroy, ElementRef, ViewChild } from
"@angular/core";

import html2canvas from 'html2canvas';

## Step 3: Component Setup

Define the necessary elements in your component:

@ViewChild('screen') screen: ElementRef;
@ViewChild('canvas') canvas: ElementRef;
@ViewChild('downloadLink') downloadLink: ElementRef;

## Step 4: Implement Image Download Function

Add a function to download the HTML content as an image:

downloadImage(){
html2canvas(this.screen.nativeElement).then(canvas => {
this.canvas.nativeElement.src = canvas.toDataURL();
this.downloadLink.nativeElement.href = canvas.toDataURL('image/png');
this.downloadLink.nativeElement.download = 'full_page.png';
this.downloadLink.nativeElement.click();
});
}

## Step 5: HTML Setup

In your component's HTML file, set up the elements for exporting:

<div #screen>
<h1>Hello Test</h1>
</div>

<div id="download">
<img #canvas>
<a #downloadLink></a>
</div>

## Step 6: Invoking the Function

Call the `downloadImage` function from your component when you want to trigger the export.

Now you have a complete setup to export HTML content as an image in your Angular component using `html2canvas`. Feel free to customize the code according to your specific requirements.

Happy coding!


Tuesday 17 October 2023

get multiple group by sum in javascript


 



let jsonData = {
"status": true,
"data": [
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Global",
"esg_audited": "non-audited",
"size": "large",
"invoice_count": 1
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Global",
"esg_audited": "audited",
"size": "large",
"invoice_count": 1
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Global",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 5
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Global",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 5
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Global",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 1
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Global",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 7
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "non-audited",
"size": "large",
"invoice_count": 7
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "non-audited",
"size": "sme",
"invoice_count": 23
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "large",
"invoice_count": 3
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 13
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 1
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 5
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 2
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 4
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 1
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 1
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 1
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 1
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 4
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 1
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 1
},
{
"year": 2021,
"quarter": 4,
"month": 12,
"mthkey": 202112,
"supplier": "root",
"demography": "Local",
"esg_audited": "audited",
"size": "sme",
"invoice_count": 2
}
]
}
----------------------------------
Function
----------------------------------
groupByMultis(data, keys,count_property_name) {
const counts = {};
data.forEach(item => {
let currentLevel = counts;
keys.forEach((key, index) => {
const value = item[key];
if (!currentLevel[value]) {
currentLevel[value] = { count: 0 };
}
currentLevel[value].count += item[count_property_name];
let val = parseFloat(parseFloat(currentLevel[value].count).toFixed(2));
currentLevel[value].count = val;
currentLevel = currentLevel[value];
});
});
return counts;
}
----------------------------------
Use
----------------------------------
let groupByMultisResult = this.groupByMultis(jsonData.data,
['esg_audited','demography','size'],'invoice_count');
----------------------------------
Result
----------------------------------
{
"non-audited": {
"count": 101,
"Global": {
"count": 36,
"large": {
"count": 2
},
"sme": {
"count": 34
}
},
"Local": {
"count": 65,
"large": {
"count": 14
},
"sme": {
"count": 51
}
}
},
"audited": {
"count": 147,
"Global": {
"count": 36,
"large": {
"count": 2
},
"sme": {
"count": 34
}
},
"Local": {
"count": 111,
"large": {
"count": 28
},
"sme": {
"count": 83
}
}
}
}



loopThroughObjRecurs (obj, count,propExec) {
for (var k in obj) {
if (typeof obj[k] === 'object' && obj[k] !== null) {
let currentCount = obj[k].count;
let percentage:any = (currentCount*100/count);
let val = parseFloat(parseFloat(percentage).toFixed(2));
obj[k]['percentage'] = val;
this.loopThroughObjRecurs(obj[k], obj[k].count,propExec)
} else if (obj.hasOwnProperty(k)) {
propExec(k, obj[k])
}
}
}

let rootCount = _.sumBy(jsonData.data,'invoice_count');
let withPercentage = loopThroughObjRecurs(groupByMultisResult,rootCount,
function(k, prop) {
//console.log(k + ': ' + prop);
});





Saturday 7 October 2023

Microservices patterns

 here is a list of some common microservices patterns


1. **API Gateway Pattern**:

   - **Description**: A single entry point for client requests that routes them to the appropriate microservices. It can handle tasks like authentication, load balancing, and caching.


2. **Service Discovery Pattern**:

   - **Description**: Microservices need to locate and communicate with each other dynamically. Service discovery patterns use tools like Consul, etcd, or DNS for automatic service registration and discovery.


3. **Circuit Breaker Pattern**:

   - **Description**: A fault-tolerant pattern that prevents a microservice from repeatedly trying to invoke a failing service. It "opens" the circuit when failures occur and "closes" it when the service becomes available.


4. **Retry Pattern**:

   - **Description**: In cases of transient failures, this pattern retries failed requests to a microservice. It helps ensure that occasional network glitches or temporary service unavailability doesn't lead to failures.


5. **Event Sourcing Pattern**:

   - **Description**: Instead of storing the current state of data, this pattern maintains a log of all changes (events) that have occurred. It can be useful for building event-driven architectures.


6. **Saga Pattern**:

   - **Description**: A way to manage distributed transactions across multiple microservices. Sagas break complex transactions into a series of smaller, individual steps with compensating actions in case of failure.


7. **Bulkhead Pattern**:

   - **Description**: Inspired by ship design, this pattern isolates failures in one microservice from affecting others. It involves using separate resources or processes for different parts of the application.


8. **Database per Service Pattern**:

   - **Description**: Each microservice has its own database. This pattern ensures loose coupling but may require mechanisms for data consistency and synchronization.


9. **Shared Database Pattern**:

   - **Description**: Some microservices share a single database. While it simplifies data access, it can lead to tight coupling and potential issues with data consistency.


10. **Backends for Frontends (BFF) Pattern**:

    - **Description**: Tailoring microservices for specific client applications. It helps optimize performance and reduces over-fetching of data for various client types.


11. **Asynchronous Messaging Pattern**:

    - **Description**: Communication between microservices through message queues (e.g., Kafka, RabbitMQ) for decoupling and scalability.


12. **Materialized View Pattern**:

    - **Description**: Creating precomputed views of data to improve query performance in read-heavy microservices.


13. **Choreography vs. Orchestration**:

    - **Description**: Deciding whether to use an event-driven choreography approach where microservices communicate directly or an orchestration approach with a central controller managing interactions.


14. **API Composition Pattern**:

    - **Description**: Aggregating data from multiple microservices to serve a client request in a single response, reducing the number of client-server interactions.


15. **Sidecar Pattern**:

    - **Description**: An auxiliary service that runs alongside a microservice to provide additional capabilities like logging, monitoring, or security.


16. **Gateway Aggregation Pattern**:

    - **Description**: Aggregating multiple microservices into a single, unified API gateway for clients, simplifying client interactions.


These patterns can be combined and tailored to meet the specific requirements of your microservices architecture. The choice of patterns will depend on factors like the nature of your application, scalability needs, and team expertise.


17. **External Configuration Pattern**:

    - **Description**: Managing configuration settings for microservices externally, allowing for dynamic updates without redeploying the services.


18. **Leader Election Pattern**:

    - **Description**: Used in scenarios where one microservice needs to be designated as the leader to perform certain tasks (e.g., in distributed systems).


19. **Fan-Out on Read Pattern**:

    - **Description**: When a microservice receives a read request, it fetches data from multiple other microservices in parallel to fulfill the request.


20. **Priority Queue Pattern**:

    - **Description**: Assigning priorities to tasks or messages in a microservices system to ensure high-priority tasks are processed before lower-priority ones.


21. **Stateless vs. Stateful Microservices**:

    - **Description**: Deciding whether microservices should be stateless (no local state) or stateful (maintaining some form of local state) based on application requirements.


22. **Bulkhead Isolation Pattern**:

    - **Description**: Isolating microservices into separate pools of resources (e.g., threads, processes, or containers) to prevent resource exhaustion from impacting other services.


23. **Shared Cache Pattern**:

    - **Description**: Storing commonly accessed data in a shared cache (e.g., Redis) to reduce redundant database calls and improve performance.


24. **API Versioning Pattern**:

    - **Description**: Managing changes to APIs by versioning them to ensure backward compatibility for existing clients while allowing for updates.


25. **Health Check Pattern**:

    - **Description**: Regularly checking the health and status of microservices to determine if they are available and responsive.


26. **Compensating Transaction Pattern**:

    - **Description**: Handling failures in distributed transactions by executing a compensating action to undo the effects of a failed transaction.


27. **Cross-Functional Teams Pattern**:

    - **Description**: Organizing development teams around microservices, where each team is responsible for one or more services, to promote ownership and accountability.


28. **Database Replication Pattern**:

    - **Description**: Replicating data across multiple databases or data centers to ensure data availability and fault tolerance.


29. **Service Mesh Pattern**:

    - **Description**: Implementing a service mesh (e.g., Istio, Linkerd) to manage communication, security, and observability between microservices.


30. **Concurrency Control Pattern**:

    - **Description**: Managing concurrent access to resources, such as databases or shared caches, to prevent conflicts and ensure data consistency.


Remember that not all of these patterns will be relevant to every microservices project. The choice of patterns should align with your specific architectural needs, scalability requirements, and the characteristics of your application. Understanding these patterns can help you design and implement microservices architectures more effectively.

Tuesday 1 August 2023

How to analyze a balance sheet



1️⃣ Working Capital


This measures a company's ability to meet its short-term obligations. A positive working capital indicates that the company has enough assets to cover its liabilities.


2️⃣ Current Ratio


This measures a company's ability to pay its current liabilities with its current assets. A ratio of 1:1 is considered ideal.


3️⃣ Quick Ratio


This is a more stringent measure of a company's liquidity, as it only includes highly liquid assets in the calculation.


4️⃣ Debt to Equity Ratio


The proportion of a company's financing that comes from debt versus equity. A high ratio may indicate that a company is taking on too much debt.


5️⃣ Debt to Assets Ratio


The proportion of a company's assets that are financed through debt. A high ratio may indicate that a company is taking on too much debt.


6️⃣ Asset Turnover Ratio


This measures a company's ability to generate revenue from its assets. A higher ratio indicates more efficient use of assets.


7️⃣ Return on Assets (ROA)


The efficiency with which a company generates profits from its assets. A higher ROA indicates that the company uses its assets more effectively.


8️⃣Return on Equity (ROE)


The profitability of a company in relation to the equity invested in it. A higher ROE indicates that the company generates more profits for its shareholders.


9️⃣ Days Sales Outstanding (DSO)


The average number of days a company takes to collect payment from its customers. A lower DSO indicates a more efficient collection of accounts receivable.


🔟 Inventory Turnover Ratio


The speed at which a company sells its inventory. A higher ratio indicates that the company is efficiently managing its inventory and generating sales.

Thursday 27 July 2023

SMART MONEY CONCEPTS GLOSSARY

 SMART MONEY CONCEPTS GLOSSARY


Break Of Structure (BOS) (CONTINUATION)

A BOS is when the price breaks above or below, and continues in the direction of the trend. (CONTINUATION).


Break Of Structure Down

When the price breaks and closes BELOW the wick of the previous LOW in a DOWNTREND.


Break Of Structure Up

When the price breaks and closes ABOVE the wick of the previous HIGH in an UPTREND.

Buy Side Liquidity (Smart Money SELLS)


Where an Order Block forms where Smart Money SELLS into retailers (dumb money) BUYING orders – Pushing the price DOWN.


Change of Character (CHoCH) (REVERSAL)

Refers to a much larger shift in the underlying market trend, dynamic or sentiment.

This is where the price moves to the point where there is a change in the overall trend. (REVERSAL)


Change of Character Down

When the price breaks and closes below the previous uptrend.


Change of Character Up

When the price breaks and closes above the previous downtrend.


Daily bias

Tells us which direction, trend and environment the market is in and what we are looking to trade.


Daily bias Bearish

When the market environment is DOWN and the trend is DOWN – we look for shorts (sells) in the market.


Daily bias Bullish

When the market environment is UP and the trend is UP – we look for long positions (buys) in the market.


Discount market <50%

The market is at a discount when the price trades BELOW the equilibrium level. We say the price is at a discount (low price).


Equilibrium

Equilibrium is a state of the market where the demand and supply are in balance with the price. We say the price of the market is at fair value.


Fair Value Gap (FVG)

A 3 candle structure with an up or down impulse candle that indicates and creates an imbalance or an inefficiency in the market.


Fair Value Gap Bearish

A 3 candle structure with a DOWN impulse candle that indicates and creates an imbalance or an inefficiency in the market.


Between candle 1 and 3, do NOT show common prices. The price needs to move back up to rebalance and fill the gap.


Fair Value Gap Bullish

A 3 candle structure with an UP impulse candle that indicates and creates an imbalance or an inefficiency in the market.


Between candle 1 and 3, do NOT show common prices. The price needs to come back down to rebalance and fill the gap.


Levels of liquidity

The area of prices where smart money players, identify and choose to BUY or SELL large quantities.


E.g. Supports, resistances, highs, lows, key levels, trend lines, volume, indicators, psychological levels.


Liquidity

The degree, rate and ability for an asset or security to be easily bought (flow in) or sold (flow out) in the market at a specific price.


Liquidity sweep (Liquidity grab)

Smart money buys or sells (and sweeps or grabs liquidity) from traders who enter, exit or get stopped.


Market down structure

When the price makes lower lows and lower highs.


Market structure

Indicates what a market is doing, which direction it’s in and where it is more likely to go.

Market Structure Shift (MSS)


MSS shows you when the price is breaking a structure or changing the direction in the market.


Market up structure

When the price makes higher lows and higher highs.


Order block

Large market orders (big block of orders) where smart money buys or sells from different levels of liquidity.


Order Block Bearish

A strong selling or a supply zone for smart money.


Order Block Bullish

A strong buying or a demand zone for smart money.


Order block events

Large market orders where smart money buys or sells from certain events i.e. High volume, supports, resistances, highs, lows, key levels, Break Of Structure, Change of Character, News or economic event.


Point Of Interest (POI)

POI is an area or level in the market where there is expected to be a large amount of buying or selling activity i.e. Order blocks.


Premium market >50%

The market is at a premium when the price trades ABOVE the equilibrium level.

We say the price is at a premium (high price).