Monday, 21 November 2022

Angular #2 Data Binding {{}} , [ ], ( ), [()]

Let’s Build Our First Angular Project! 🚀

Ex 1: One Way Binding {{}}

Step 1: Create a New Angular Project

ng new ex1
  • Say ‘N’ when asked about Angular Routing.
  • Choose CSS for stylesheets.
  • Wait for npm packages to install.

Step 2: Open Your Project in VS Code

cd ex1
code .

Expand the src directory to see app, assets, and environments folders.

Step 3: Modify app.component.html

Delete everything and add:

<h1>{{title}}</h1>

Save the file and run:

ng serve

Open http://localhost:4200 in a browser, and boom! You’ll see your title!


Ex 2: User-Defined Object Binding

Step 1: Modify app.component.ts

Add this inside the AppComponent class:

inputData = 'User Defined Data in Class';

Step 2: Modify app.component.html

<p style="color: rgb(128, 0, 28);"><b>{{inputData}}</b></p>

Save and check the browser!


Ex 3: Creating a New Component

Step 1: Generate a Component

ng generate component container

This creates four new files and updates app.module.ts.

Step 2: Modify app.component.html

Add this:

<app-container></app-container>

Step 3 a): Modify container.component.html

<h1>Header Comes Here</h1>
<h3>Nav Bar Comes Here</h3>
<h5>Content Comes Here</h5>
      b) Modify app.component.ts as shown below and save

@Component({
  selector: 'app-root',
  imports: [ContainerComponent],

Run:

ng serve

Check the browser to see the changes as shown above!



Ex 4: Event Data Binding

Step 1: Modify container.component.html

<div>
    <label>First Name:</label>
    <input type="text"> 
    <button (click)="onClick()">Click Me</button>
</div>

Step 2: Modify container.component.ts

Inside ContainerComponent class, add:

onClick() {
    alert('Somebody clicked the button!');
}

Save and run ng serve, then check http://localhost:4200. Click the button and watch the magic happen!


Ex 5: Two-Way Binding with ngModel

Step 1: Modify app.component.ts (delete the old contents)

import { Component } from '@angular/core';
import { FormsModule } from '@angular/forms'; // Import FormsModule

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [FormsModule], // Add FormsModule here
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  userName: string = 'iMMSS Inc'; // Variable for Two-Way Binding
}

Step 2. Modify (delete the old contents) app.component.html file

<h1>Test App Works!</h1>
<div>
  <label>Enter your name:</label>
  <input type="text" [(ngModel)]="userName">
</div>

<h1>Hello, {{ userName }}!</h1>

+ add the following in app.component.css

h1 {
    color :rgb(168, 26, 104);
}

Run ng serve and check **http://localhost:4200**—whatever you type will update in real-time!





🎯 What’s Next?

  • Try experimenting with Directives and Pipes!
  • Build dynamic forms and API integrations.
  • Show off your Angular skills to the world! 🚀

Happy Coding! 🎉


Hand on Outputs:

Ex 1.

One Way Binding {{}}

In Visual Studio, Terminal 

create a project using 

 ng new ex1

Ans N for Would you like to Add Angular Routing ?

Choose CSS for Which Style sheet format you like to use?

Will install packages(npm).

Open folder ex1

Expand src directory to see app, assets, environments.. directories.

In app directory, open app.component.html files. Delete all the contents.

add the following and save.

<h1>{{title}}</h1>

Invoke by 

ng serve to run the server in Terminal Window. 

Open any browser and go to http://localhost:/4200

will display the title ex1 in browser

 Ex 2.

Add user defined object inputData

Add  the above USO in app.component.ts file AppCompenet class by 

inputData = 'User Defined Data in Class';

In app directory, open app.component.html files. 

add the following and save.

<p style="color: rgb(128, 0, 28);"><b>{{inputData}}</b></p>

Check in browser.


Ex  3.

Add a new Component 'Container'In terminal 

In Terminal Window, command prompt

ng generate component container

to create a new componont. Will create four new files and one update one file.

PS F:\AngularCourse\ex1> ng generate component container
CREATE src/app/container/container.component.html (24 bytes)
CREATE src/app/container/container.component.spec.ts (620 bytes)
CREATE src/app/container/container.component.ts (287 bytes)
CREATE src/app/container/container.component.css (0 bytes)
UPDATE src/app/app.module.ts (408 bytes)

Now check the container.component.html file.

Add the following contents inside app.compoent.html

<app-container></app-container>

Delete the contents. Add the following

<h1>Header Comes here</h1>
<h3>Nav Bar comes here</h3>
<h5>Content  comes here</h5>

Now invoke webpack by 

ng serve

command inside the terminal prompt to check the browser contents. 

Ex 4.

Evet data binding 

add the following contents  in container.component.html file.

<div>
    <Label> First Name : </Label>
    <input type="text">
    <button (click) = "onClick()">Clik Me</button>
</div>

 in src\app\container\container.component.ts file, add the following 

Inside ContainerComponent class after ngOnInit(): void{}  and save

onClick(){
    alert('Some body kicked the Button');
  }

Now invoke webpack by ng serve and check http://localhost:4200 in browser. Click the button to see alert box.


Ex4: 

Two way Binding [(ngModule)]y

create a new project using 

ng new ex4


Add the following contents  in container.component.html file.

<div>
    <Label> First Name : </Label>
    <input type="text" [(ngModel)] = "inputData"> <br><br>
    Entered Choice is  : {{inputData}}
</div>

Open app.component.ts File , add inside the class AppComponent  and save file.

inputData = 'Two way Binding Example';

Add the following in app.module.ts file import section and save.

import { FormsModule } from '@angular/forms';

Register  FormsModule   as shown below:


@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})

run ng serve in terminal. Check in the opened browser http://localhost:4200.

Whatever you typed will be displayed immediately next to  Entered Choice is  :



Thursday, 17 November 2022

Angular #1 Installation

Why is it called Angular?

Because it's written between < >! Get it? (Okay, bad joke, but now you won’t forget it!)

Angular is a powerful framework built with TypeScript for developing client-side applications. It’s like a superhero for web developers—making code cleaner, reusable, and testable!


Angular Architecture (Frontend + Backend)

Frontend (UI)

This is what users see in their browsers! It includes:

  • HTML & CSS (Templates & Styles)
  • TypeScript (Super-powered JavaScript)
  • Angular (The magic framework!)

Backend (Data Processing)

This is where the data magic happens!

  • Data + API (Application Programming Interface)
  • Business Logic (The brain behind the app)

In short, Angular makes life easier!


Angular Versions: What’s the Deal?

  • The first version was AngularJS.
  • Later versions dropped the "JS" and are called Angular (Vx) (Latest: Angular 14.0).

AngularJS vs Angular – What’s Different?

Feature AngularJS Angular
Architecture MVC Model Components & Directives
Language JavaScript TypeScript
Mobile Friendly? Nope Yes!
Expression Syntax {{ }} () []
Dependency Injection Not used Hierarchical DI
Routing @routeProvider @Route Configuration
Code Structure Messy 😵‍💫 Well-structured ✅

Let’s Build Our First Angular Project! 🚀

Step 1: Install Node.js

  • Go to nodejs.org
  • Download the latest stable version (Windows/Mac/Linux)
  • Install it like a pro! (Run as Administrator)
  • Check if it's installed by running:
    node --version
    

Step 2: Install Angular CLI (Command Line Interface)

CLI is your best friend for Angular projects!

npm install -g @angular/cli

Check if it's installed:

ng version

Step 3: Create Your First Angular Project

Run this command:

ng new hello-universe

hello-universe is your project name! It will ask a few questions:

  • Would you like to add Angular routing? (Say ‘N’)
  • Which stylesheet format to use? (Choose CSS)
  • Then, it will take some time to set up all the files. Grab a coffee! ☕

Step 4: Install Visual Studio Code (VS Code)

  • Download it from Visual Studio Code
  • Install it as Administrator
  • Open your project by running:
    cd hello-universe
    code .
    

Now, your VS Code will open with your first Angular project! 🎉

Step 5: Run Your First Angular App! 🚀

Run this command inside your project folder:

ng serve

Wait for the magic words: Compiled Successfully!

Now, open your browser and go to:

localhost:4200


Great My friend, You have done it!



Boom! Your first Angular app is live! 🎉🎉🎉


🎯 What’s Next?

  • Learn about Components, Modules & Directives
  • Play around with Routing and Services
  • Build something cool & show off your Angular skills! 😎

Happy Coding! 🚀

Tuesday, 12 July 2022

#0 Intro to Data Analysis

 Two Words

Data & Analysis

Data : oil, Electricity,  everywhere, every time, even now.

Analysis : Answer how and Why ?

Analysis :

Data analysis is the process of collecting, modeling, and analyzing data to extract insights that support decision-making. There are several methods and techniques to perform analysis depending on the industry and the aim of the investigation


Why Is Data Analysis Important?

Informed decision-making: 

Reduce costs| Increase Profits

Target Customers Better


DA is a Process

Identify-Collect-Clean-Analyze-Interpret or Infer- Act

(ICCAIA)


Types of DA

1.Descriptive: What ?-Data to Valuable Insights

2.Exploratory: How  ?-To generate Hypothesis to solve specific 3.Problems

4.Diagnostic : Why ? - To tackle and to cure 

5.Predictive  : What if ? - Future Projection

6.Prescriptive : IF-?.Then-This : 


Top DA Methods

1. Cluster Analysis: Similar elements - Grouping Data 

2. Cohort Analysis : Historical data to examine and compare -Google Analytics:

3. Regression Analysis - y=mx+c

4. Factor Analysis : Dimension Reduction

5. Neural Networks : Mimic Human Brain to find solutions

6. Data Mining: Identify patterns, Dependencies, realations, Trends

7. Text Analysis : Actional Insights with Relevant Data

8. TimeSeries Analysis : Data Collected over a specified period of time.

9. Decison Trees: To support smart and strategic Decisions

10. Conjoint Analysis : How individuals value different attributes of a product or Service



Top 17 Data Analysis Techniques:


Collaborate your needs

Establish your questions

Data democratization

Think of data governance 

Clean your data

Set your KPIs

Omit useless data

Build a data management roadmap

Integrate technology

Answer your questions

Visualize your data

Interpretation of data

Consider autonomous technology

Build a narrative

Share the load

Data Analysis tools

Refine your process constantly 


Quality Criteria For Data Analysis 

Internal Validity

External Validity

Reliability

Objectivity



Application of DA:


Academics: Universities and academic institutions can perform data analysis to measure student performance and gather insights on how certain behaviors can further improve education.


Human Resources: Organizations can use data analysis to offer a great experience to their employees and ensure an excellent work environment. They can also utilize the data to find out the best resources whose skill set matches the organizational goals



Communication is very Important


Qualitative


Stephen Few - 8 Types of Quantitative Messages out of DA:

1. Time Series : Line Chart

2. Ranking : Bar Chart

3. Part-to-Whole : Pie Chart

4. Deviation: Bar Comparison : Actual Vs Variation

5. Frequency Distribuition : Histogram

6. Correlation: Scatter Plot 

7. Nominal Comparison : bar Chart

8. Geographical : Cartogram


Quantitative

mean, median, mode, Standard deviation, chi-square, eigen vector



Free software for data analysis


Notable free software for data analysis include:


DevInfo – A database system endorsed by the United Nations Development Group for monitoring and analyzing human development.[149]

ELKI – Data mining framework in Java with data mining oriented visualization functions.

KNIME – The Konstanz Information Miner, a user friendly and comprehensive data analytics framework.

Orange – A visual programming tool featuring interactive data visualization and methods for statistical data analysis, data mining, and machine learning.

Pandas – Python library for data analysis.

PAW – FORTRAN/C data analysis framework developed at CERN.

R – A programming language and software environment for statistical computing and graphics.[150]

ROOT – C++ data analysis framework developed at CERN.

SciPy – Python library for data analysis.

Julia - A programming language well-suited for numerical analysis and computational science.


Thursday, 30 June 2022

DATA SCIENCE ETHICS

 DSE definition:

“Data ethics is a new branch of ethics that studies and evaluates moral problems related to data (including generation, recording, curation, processing, dissemination, sharing and use), algorithms (including artificial intelligence, artificial agents, machine learning and robots) and corresponding practices (including responsible innovation, programming, hacking and professional codes), in order to formulate and support morally good solutions (e.g. right conducts or right values).”



MongoDB - Introduction

 MongaDB Features

  • Full cloud-based application data platform.
  • Flexible document schemas.
  • JSON..BSON (BJSON)..
  • Widely supported and code-native data access.
  • Change-friendly design.
  • Powerful querying and analytics.
  • Easy horizontal scale-out with sharding.
  • Simple installation.
  • Cost-effective.

Learning to use MongoDB

Step 1:

Download and install "PyMongo":


                pip install mongadb

Step 2:

                    import pymonga

step 3: list database names

                # import library
import pymongo
# creating a client
myc = pymongo.MongoClient("mongodb://localhost:27017/")
# Just printing existing databases
print(myc.list_database_names()) # ['admin', 'config', 'db1', 'local']

Step 4: Create Collections

# import library
import pymongo
# creating a client
c = pymongo.MongoClient("mongodb://localhost:27017/")
# Just printing existing databases
print(c.list_database_names()) # ['admin', 'config', 'db1', 'local']

# choose any demo db as db1
# create collection customers in db1
db = c['db1']
col = db["customers"]
print(db.list_collection_names())

# add Dict data
dict = { "name": "John", "address": "Highway 37" }
x = col.insert_one(dict)
print(x.inserted_id)

#add Dict1 data
dict2 = { "name": "Peter", "address": "Lowstreet 27" }
y = col.insert_one(dict2)
print(y.inserted_id)

"""
['admin', 'config', 'db1', 'local']
['customers']
62bd57445c7e7af908e87efa
62bd57445c7e7af908e87efb

"""

To display with Object_ID


clist = db.list_collection_names()
if "customers" in clist:
print("The collection exists.")

for x in col.find():
print(x)

"""
['admin', 'config', 'local']
[]
62bd58d899982b27053eb9cc
62bd58d899982b27053eb9cd
The collection exists.
{'_id': ObjectId('62bd58d899982b27053eb9cc'), 'name': 'John', 'address': 'Highway 37'}
{'_id': ObjectId('62bd58d899982b27053eb9cd'), 'name': 'Peter', 'address': 'Lowstreet 27'}
"""

Before and After deleting 

# import library
import pymongo
# creating a client
c = pymongo.MongoClient("mongodb://localhost:27017/")
db = c['db1']
col = db["customers"]
col.drop()
q1 = { 'address': 'Highway 37'}
q2 = { 'address': 'Highway 38'}
q3 = { 'address': 'Highway 39'}

print(10*'-', 'Insering 3 qs')
col.insert_one(q1)
col.insert_one(q2)
col.insert_one(q3)

print(10*'-', 'Before Delete')
for x in col.find():
print(x)

q4 = { 'address': 'Highway 39'}
col.delete_many(q4)
print(10*'-', 'After Delete')
for x in col.find():
print(x)
"""
---------- Insering 3 qs
---------- Before Delete
{'_id': ObjectId('62bd5db330e379663c8851ce'), 'address': 'Highway 37'}
{'_id': ObjectId('62bd5db430e379663c8851cf'), 'address': 'Highway 38'}
{'_id': ObjectId('62bd5db430e379663c8851d0'), 'address': 'Highway 39'}
---------- After Delete
{'_id': ObjectId('62bd5db330e379663c8851ce'), 'address': 'Highway 37'}
{'_id': ObjectId('62bd5db430e379663c8851cf'), 'address': 'Highway 38'}
"""

After deleting another Record

print('After Prinitng')

q5 = { 'address': 'Highway 37'}
col.delete_many(q5)
for x in col.find():
print(x)
"""
After Prinitng
{'_id': ObjectId('62bd5f3cf32b68f5a744b5ab'), 'address': 'Highway 38'}\
"""
Before and After dropping collections
import pymongo
# creating a client
c = pymongo.MongoClient("mongodb://localhost:27017/")
db = c['db1']
col = db["customers"]

many = [
{ "_id": 1, "name": "AMET", "address": "ECR, Chennai"},
{ "_id": 2, "name": "ABS", "address": "Anna Nagar, Chennai"},
]
x = col.insert_many(many)

print('Before dropping')
for x in col.find():
print(x)
col.drop()
print('After dropping')
for x in col.find():
print(x)
"""
Before dropping
{'_id': 1, 'name': 'AMET', 'address': 'ECR, Chennai'}
{'_id': 2, 'name': 'ABS', 'address': 'Anna Nagar, Chennai'}
After dropping

"""

Sorting Collections

import pymongo

# creating a client
c = pymongo.MongoClient("mongodb://localhost:27017/")
db = c['db1']
col = db["customers"]
col.drop()
many = [
{ "_id": 11, "name": "AMET", "address": "ECR, Chennai"},
{ "_id": 21, "name": "ABS", "address": "Anna Nagar, Chennai"},
]
x = col.insert_many(many)
print('Before Sorting')
for x in col.find():
print(x)
doc = col.find().sort("name")

print('After Sorting')
for x in doc:
print(x)

"""
Before Sorting
{'_id': 11, 'name': 'AMET', 'address': 'ECR, Chennai'}
{'_id': 21, 'name': 'ABS', 'address': 'Anna Nagar, Chennai'}
After Sorting
{'_id': 21, 'name': 'ABS', 'address': 'Anna Nagar, Chennai'}
{'_id': 11, 'name': 'AMET', 'address': 'ECR, Chennai'}
"""
Before and After Updating
import pymongo

# creating a client
c = pymongo.MongoClient("mongodb://localhost:27017/")
db = c['db1']
col = db["customers"]
col.drop()
many = [
{ "_id": 11, "name": "AMET", "address": "ECR, Chennai"},
{ "_id": 21, "name": "ABS", "address": "Anna Nagar, Chennai"},
]
x = col.insert_many(many)
q6 = { "address": 'ECR, Chennai' }
newvalues = { "$set": { "address": "#123, East Coast Road, Chennai" } }
print('Before Updation')
for x in col.find():
print(x)
col.update_one(q6, newvalues)
print("After Updation")
#print "customers" after the update:
for x in col.find():
print(x)
"""
Before Updation
{'_id': 11, 'name': 'AMET', 'address': 'ECR, Chennai'}
{'_id': 21, 'name': 'ABS', 'address': 'Anna Nagar, Chennai'}
After Updation
{'_id': 11, 'name': 'AMET', 'address': '#123, East Coast Road, Chennai'}
{'_id': 21, 'name': 'ABS', 'address': 'Anna Nagar, Chennai'}
"""
B4 and After Many Updating using regular expression


import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["mydatabase"]
col = db["customers"]
col.drop()

many = [
{ "_id": 10, "name": "AMET", "address": "ECR, Chennai"},
{ "_id": 12, "name": "ABS", "address": "Anna Nagar, Chennai"},
{ "_id": 13, "name": "ABS!@", "address": "ECR, Chennai"},
{ "_id": 14, "name": "Stanford", "address": "Anna Nagar, Chennai"},
]
x = col.insert_many(many)


print('Before Updation')
for x in col.find():
print(x)

query = { "address": { "$regex": "^A" } }
newvalues = { "$set": { "name": "AMET Updated" } }
x = col.update_many(query, newvalues)
print(x.modified_count, "documents updated.")

print('After many Updation')
for x in col.find():
print(x)
"""
Before Updation
{'_id': 10, 'name': 'AMET', 'address': 'ECR, Chennai'}
{'_id': 12, 'name': 'ABS', 'address': 'Anna Nagar, Chennai'}
{'_id': 13, 'name': 'ABS!@', 'address': 'ECR, Chennai'}
{'_id': 14, 'name': 'Stanford', 'address': 'Anna Nagar, Chennai'}
2 documents updated.
After many Updation
{'_id': 10, 'name': 'AMET', 'address': 'ECR, Chennai'}
{'_id': 12, 'name': 'AMET Updated', 'address': 'Anna Nagar, Chennai'}
{'_id': 13, 'name': 'ABS!@', 'address': 'ECR, Chennai'}
{'_id': 14, 'name': 'AMET Updated', 'address': 'Anna Nagar, Chennai'}
"""
After using limit to display 
# limit parameter to limit two records
output = col.find().limit(2)
print('After setting Limit(2)')
for x in output:
print(x)
"""
After setting Limit(2)
{'_id': 10, 'name': 'AMET', 'address': 'ECR, Chennai'}
{'_id': 12, 'name': 'AMET Updated', 'address': 'Anna Nagar, Chennai'}
"""

Bon Appetite and Happy MongoDB Coding....Learning!!!



Monday, 27 June 2022

Recommendations System - Course for +2 Students

 Recommendation System using pandas and Sklearn

Student Dataset1.csv

id,gender,stream,subject,marks,course,specialization
1,m,science,physics,78,btech,civil
2,f,commerce,maths,56,bsc,maths
3,m,humanities,history,79,ba,history
4,f,commerce,economics,88,bcom,hons
5,m,science,chemistry,79,bsc,biology
6,m,science,maths,98,btech,mech
7,f,commerce,physics,56,bsc,maths
8,m,humanities,history,79,ba,history
9,f,commerce,commerce,76,bcom,hons
10,m,science,physics,89,bsc,biology

Code snippet (Thanks to  Siddharth Sachdeva — August 25, 2021, Analytics Vidya)

#S1 importing necessary libraries.
import pandas as pd
data = pd.read_csv(
r"dataset1.csv")
#s2
descriptions =data['gender'] +' '+ data['subject'] + ' ' + data['stream'] +' '+ data['marks'].apply(str)
#Printing the first description
print(descriptions[0])
# s3 similarity matrix
#import sklearn.TfidfVector
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import linear_kernel
def create_similarity_matrix(new_description, overall_descriptions):
overall_descriptions.append(new_description)
# Define a tfidf [Term Frequency Inverse document frequency] vectorizer and remove all stopwords.
tfidf = TfidfVectorizer(stop_words="english")
tfidf_matrix = tfidf.fit_transform(overall_descriptions)
tfidf_matrix.shape
cosine_sim = linear_kernel(tfidf_matrix
,tfidf_matrix)
return cosine_sim
#s5 Sim Matrix reco
def get_recommendations(new_description,overall_descriptions):

cosine_sim = create_similarity_matrix(new_description
,overall_descriptions)
sim_scores =
list(enumerate(cosine_sim[-1]))
sim_scores =
sorted(sim_scores,key =lambda x:x[1],reverse= True )
sim_scores = sim_scores[
1:10]
indices = [i[
0]for i in sim_scores]
return data.iloc[indices]
# s6 Recommendations
new_description = pd.Series('m physics science 78')
recommendation= get_recommendations(new_description
,descriptions)
print(recommendation[0:3])
"""
id gender stream subject marks course specialization 0 1 m science physics 78 btech civil 6 7 f commerce physics 56 bsc maths 4 5 m science chemistry 79 bsc biology
"""

Simple not refined. But throw some light on basics of Recommendation System.

Angular 18 Navigation for iMMSS

  🚀 Setting Up Angular Routing - The Fun Way! 😆 Hey there, future Angular ninjas! 🥷 If you’re new to Angular and struggling with routing...