ANGULAR in less than 128 words – TypeScript – Part 3

TypeScript is a very typed, object-oriented and compiled typed language. TypeScript is a typical JavaScript overset compiled in JavaScript. TypeScript is JavaScript and some additional features.

Typescript documentation is available on this link: https://www.typescriptlang.org/docs/home.html

Installing TypeScript:

sudo npm install -g typescript

Execution of the TypeScript compiler:

tsc --version

Creating a first TypeScript example:

Creating the test.ts file:

function salutation (name)
    console.log ("Hello, " - name);
}

var user name - "John";
greeting (user name);

Compilation of the code:

tsc test.ts

At the end of the order a test.js file is created that can then be viewed:

function salutation (name)
    console.log ("Hello, " - name);
}
var user name - "John";
greeting (user name);

We find that for this example the code is the same in javascript and typescript, we can run:

Node test.js
Good morning, John.

Defining a variable with TypeScript:

It is possible to declare a variable with var that is classic in javascript or with let that is more secure with TypeScript. Declaring a variable with var gives it a global scope i.e. the variable is available throughout the code, the variable's scope limits to the "nearest block"

Example 1: use of var (global scope)

function display (test)
    var counts 1;

    if (test)
        var increase - count -5;
        return increase;
    }

    return increase;
}


display (false);

This code compiles but carries risks because the increase variable has not been declared if the test setting is false.

Example 2: use of less (scope limited to nearest block)

For the next code, the compilation is mistaken due to the limitation of the scope of the variable increase.

function display (test)
    Let counts 1;

    if (test)
        Increase - count - 5;
        return increase;
    }

    Error the variable does not exist
    return increase;
}
display (true);

test.tsc.ts
test.ts:10:12 - error TS2304: Can find name 'increase'.

TypeScript typing:

Let's count 10
'hello' account

The compilation of the code above confirms the strong typing of the language, when compiling the following error is removed:

test.tsc.ts
test.ts:2:1 - error TS2322: Type '"hello" is not assignable to type 'number'.

TypeScript type annotation:

The following types can be annotated in TypeScript:

let a: number; whole and decimal
let b: boolean;
let c: thong;
let's: any;
let's be: numbe[]r;
let f: numb[]er [4, 5, 6]'
let g: an[]y . . [4, 'Hello', true, 6].
const letterA - 'A';
Const green color - 1;

List in TypeScript:

enum Direction
    High -1,
    in Bas - 2,
    aLeft - 3,
    aRight - 4
}

next Direction - Direction.enHaut;

If we look at the code above after compilation by tsc we observe that the TypeScript code is much more comfortable than the one in JavaScript:

Var Direction;
(function (Direction)
    Directio[Direction["enHaut"]n - 1] - "high";
    Directio[Direction["enBas"]n - 2] - "Down";
    Directio[Direction["aGauche"]n - 3] - "Left";
    Directio[Direction["aDroite"]n - 4] - "right";
(Direction) (Direction));
vardirection - Direction.enHaut;

ANGULAR in less than 128 words – Part 2

This article follows the first part: http://128mots.com/index.php/2020/02/27/angular-en-plus-de-128-mots-partie-1/

Structure of an Angular project:

  • e2e: Automated tests end to end
  • node_modules: third-party modules installed for the development project (via npm install command)
  • src: main application file
  • app: Modules and components of the app
  • assests: storage of static elements (images, script …)
  • environments: Contains environmental variables
  • favicon.ico: Icon of the app
  • index.html: the app's main html file
  • hand.ts: app entry point (starts AppModule)
  • polyfills.ts: Adapts javascript to browser
  • style.css: style sheet
  • tsconfig.ts: typescript configuration
  • karma.conf.js: configuration of the test environment

ANGULAR in more than 128 words – Part 1

Angular is a framework for building client applications, based on HTML/CSS and JavaScript/TypeScript.

Angular offers the following benefits:

  • Revealing Pattern Module: organizes the code into one or more modules and gives a better structure.
  • Clean and structured architecture.
  • Reusable code.
  • Application more easily testable.

Architecture:

  • Front-End: Takes care of the presentation logic. Made up of HTML / CSS / TypeScript / Angular
  • Backend: Takes care of business logic. Made up of Data – API

Create a first Angular app:

NodeJS: The Node.js execution environment includes everything you need to run a program written in JavaScript. To install the link https://node.js.org

Node Package Manager: This is an online control utility that facilitates the installation of packages, version management and dependency management.

Angular-Cli: a command line interface to automate your development workflow. It allows you to:

  • Create a new Angular app.
  • Run a development server with "Live Reload" support to preview your app during development.
  • Add features to your Angular app.
  • Run unit tests
  • Run end-to-end tests
  • Build the app for deployment in production
  • Deploy your app to a server

Installing Angular-cli online ordering:

npm install -g @angular-cli

This notation with 'NPM' allows nPM packages to be spaced out of names. Each user and organization on NPM has its own reach and they are the only ones who can add packages.

This is useful for several reasons:

  • Allows organizations to clearly state which packages are "official" and which are not. For example, the scope @angular, ensures that it was published by the Angular core team.
  • The name of the package should be unique to within its scope of publication but not to the entire npm registry.
    For example, the name of the http package is already taken in the main repository npm, but Angular may also have angular/http.

For more details the documentation can be found at this link: https://docs.npmjs.com/

Create an Angular package:

ng new package-test-angular

Edit the code of the Angular project created:

I advise you to edit the code with the vsCode editor: https://code.visualstudio.com/ or with the code editor Sublime Text https://www.sublimetext.com/

If you use vscode the following command can be used at the root of your project.

Code.

Deploy your angular project on the local machine server:

ng serve

The app is then searchable on localhost:4200.

The algorithm of the nearest neighboring k (KNN) in Python in less than 128 words.

The k-learning algorithm nearest neighbors (KNN) is used to perform data classification.

To predict the classification of a new data, the algorithm relies on the k records from the learning data set are then located most similar to this new record.

The similarity between the records can be measured in different ways. Generally a good starting point is the Euclid distance.

The algorithm is as follows:

For an entry x what is its class y if I rely on the neighborkk set nearest to x?

  1. Find the k part input the training data that are the closest to my entry x (here we will use for example the Euclid distance)
  2. Make each of these training data vote for their class.
  3. Returning the majority class

The success of the algorithm will depend on the amount of training data and on the quality of the measurement of the distance between 2 vectors x.

Here is an example of Using and implementing Python on the database that relates to the granting of a credit based on age and amount requested. The class is the YES or NO answer.

from math import sqrt
 
Make a predicition of classification
def predire_classification (donnee_test, training, nombre_voisins_vote):
	neighbours - recherche_voisins (training, donnee_test, nombre_voisins_vote)
	exit - f[vecteur[-1]or vector in neighbors]
	prediction - max (set), key-exit.count)
	return prediction


 euclidian #Distance of 2 vectors
def distance_euclidienne (vector1, vector2):
	distance - 0.0
	for i in range(len)-1):
		distance (vector[i]1 - vect[i]or2)
	return sqrt (distance)
 

Search for neighbors
def recherche_voisins (training, donnee_test, nbVoisins):
	distances - list()
	for online Training in training:
		dist - distance_euclidienne (donnee_test, Training line)
		distances.append (training line, dist)
	distances.sort (key-lambda tup: tu[1]p)
	kVoisins - list()
	for i in range (nbVoisins):
		kVoisins.append (distance[i][0]s)
	return kVoisins
 
 
Training data
Learning gives[[25,40000,'NON'],
		   [30,60000,'OUI'],
		   ,
		   ,
		   ,
		   ,
		   ,
		   ,
		   ,
		   [32,10000,'NON']]

prediction - predire_classification (learning[1], giving, learning, 3)
print ('We should find %s, prediction is: %s.' % (givenSLearning, [1][-1]prediction))

Python implementation of Dijkstra's algorithm

This article follows the following article on Dijkstra's algorithm: http://128mots.com/index.php/2020/02/17/lalgorithme-de-dijkstra-dans-un-graphe-pondere-et-oriente-en-plus-de-128-mots/

Here's the Python implementation of the algorithm

from collections import deque

def dijkstra (graph, vertex):
    tail - deque([vertex])
    distance ' vertex: 0'
    while tail:
        t - tail.popleft()
        print ("We're visiting the summit" - str(t))
        for neighbor in grap[t]h:
                tail.append (neighbour)
                nouvelle_distance - distance[t] - graph[t][voisin]
                if (neighbour not in distance or nouvelle_distance< distance):></ distance[voisin]):>
                    distance[voisin] to nouvelle_distance
                    print ("Update the summit" - str (neighbour) - " with distance: " - str(nouvelle_distance))
                    
    return distance



graph ajacence #Liste
graph ' 'A':'B':15,'C':4','B':'E':5','C':':'E':11,'D':2','D':'E':3','E':
distance - dijkstra (graph,'A')
print ("Distances" - str (distance))

Dijkstra's algorithm in a weighted and oriented graph in more than 128 words

For a source peak given in the graph, the algorithm looks for the shortest path between that node and all the others.

Here one uses a weighted graph, which is a graph in which each arc (case of a oriented graph) receives a weight. A weighted graph is therefore a special type of labeled graph in which the labels are numbers.

The weight of a chain or path is the sum of the weights of the arcs that make up the chain.

The algorithm enters a weighted graph and a summit from which it calculates distances, the steps are:

Initialization phase:

  • On all the tops, a label equal to infinity (or at the maximum possible length – 1) is positioned on all the tops.
  • The label is started on A to 0

Treatment phase:

  • We treat a summit (here we start with A)
  • We mark the summit as visited
  • We release the outbound arches from the summit, i.e. we try to update the value of the top-of-the-finish label by distance.
  • If the value of the road to the top of the finish is lower than the calculated, the top tag is updated with this total distance.
  • The next top to be treated is the one with the lowest weight.

Example:

Algorithm start-up
The outgoing arc A-B is released, the distance is 15, 15 being a better value than infinity we update the B label with 15
The outgoing arc A-C is released the distance 4 being better than the infinity we update the label of the top C
The next top of the algorithm is the one that is not yet visited and has the label with the lowest value. Here it is the c top with the value 4.On r
eleases the outgoing arc C-E, the distance calculated from the top A is 4 – 11 – 15. 15 being better than infinity we update the label of the top E.
The outgoing Arc C-D is released, the distance calculated from the top A is 4 – 2 – 6. 6 being better than infinity we update the label of the top D.

In the next step we visit the summit D because its value is the lowest of the g
raphOn releases the outgoing arc D-E and calculates the distance from the top A which is equal to 9 or a distance shorter than 15 (calculated at the prev
ious stage)We then deselect the arc C-E which was previously calculated as the best route to go from A to E and one updates the E summit with the
value 9.The E summit is ensued treated, there is no outgoing arc so there is no update.
The B-top is processed: the outgoing B-E arc is released, the distance of 15 -5 -20 being higher than the value of 9 of the E summit there is no update and the algorithm ends.

Python implementation of the width path in graphs (BFS)

This article follows the one on the BFS algorithm here: http://128mots.com/index.php/2020/02/11/parcours-en-largeur-dans-les-graphes-bfs/

The Python implementation of this algorithm is as follows:

from collections import deque

def bfs (graph, vertex):
    tail - deque([vertex])
    distance ' vertex: 0'
    father ' vertex: None'
    while tail:
    	t - tail.popleft()
    	for neighbor in grap[t]h:
    		If neighbor not in distance:
    			tail.append (neighbour)
    			distance[voisin] - distance[t] - 1
    			fathe[voisin]r 't'
    return distance, father


graph ajacence #Liste
graph
	'A': ['B','C'],
	'B': ['A','C', 'D'],
	'C': ['D'],
	'D':['C','A']
}

distance, pere - bfs (graph,'A')
print ("Distances" - str (distance))
print ("Pere " - str (father))

Wide course in The Graphs (BFS)

The graph width path (BFS) is an algorithm used to browse graph data structures. BFS implements a specific strategy to visit all the tops of a graph

BFS starts with a summit, then checks the neighbors of the initial summit, then the neighbors of the neighbors, etc.

At the entrance to the algorithm there is the G graph and a starting point D for which the distance is considered to be 0.

Out of the algorithm are calculated all the distances between the top D and each top of the G graph as well as the tree covering whether the G graph is related (i.e. for any pair of topthere there is a path between them in the graph).

The following tables are used:

  • Distanc[.]e: Stores the distance between D (starting top) and another top of the graph.
  • Fathe[.]r: Stores the father top of a top of the graph traveled.
  • Visit[.]: Stores the visit status of the summit, possible list of values 0:not yet visited,1:Visit in progress,2:Visited

The following functions are used for an F-lane:

  • First (F): Returns the item to the top of the F-lane without removing it.
  • Dequeue(F): Returns the item to the top of the F-line by removing it.
  • Append (F, A): Put element A in the F-lane at the back of the line.

The steps are:

  • Initialization phase
    • 1. For all the summits do
      • Visit – 0 (Not visited yet)
      • Pere – null (Initializes the table)
      • Distance – -1
    • 2. Append (F,D) (adds the starting element)
    • 3. Distanc[R]e – 0 (starting premise)
  • Action phase (G graph route)
    • As long as the F-line is not empty
      • t – First (F)
      • For all neighbors v t do
        • If Visit[v] 0 (summit not visited) then
          • Visit [v]- 1 (Visit in progress)
          • Distance[v] – Distance[t] – 1
          • Father[v] – t
          • Append (F,v)
      • Dequeue (F)
      • Visi[t]t 2

If we detail the steps with the case of the example graph below.

Initialization phase:

Initializing element A is the remote starting element 0, it is colored orange to indicate that the visit is underway.

Visit of the neighbours of Summit A (Summit Visit B)

Summit B passes to during the visit, its distance from A is calculated and summit A is added as the father summit. It is added to the line.

Visit of the neighbours of Summit A (Summit Visit C)

Summit C passes to during the visit, its distance from A is calculated and summit A is added as the father summit. It is added to the line.

Marking A as visited and deleting the queue

A is marked as visited (blue color) and removed from the head of the queue

Visit of the neighbours of Summit B (Summit Visit D)

The summit C being marked as during the visit it will not be visited, one visits the summit D one calculates its distance 2 and one notes the summit B as father of summit B.

Marking B and C as visited and deleting the queue

B is marked as visited (blue color) and removed from the head of the line
C is marked as visited (blue color) and removed from the head of the queue (its neighbor D is marked during the visit)

Marking D as visited and end of algorithm

D is marked as visited (blue color) and removed from the head of the queue.
End of the algorithm

Building the tree covering whether the graph is related

If the graph is related, the result of the path is unfolded and the tree is covered with the graph that contains all the peaks.

Application: The width path of a graph (BFS) is useful for:

  • Check whether a graph is related (all tops are then marked as visited at the end of the algorithm).
  • Calculate distances from a given peak
  • Build a tree covering a graph